Programs & Examples On #Replay

What is git fast-forwarding?

When you try to merge one commit with a commit that can be reached by following the first commit’s history, Git simplifies things by moving the pointer forward because there is no divergent work to merge together – this is called a “fast-forward.”

For more : http://git-scm.com/book/en/v2/Git-Branching-Basic-Branching-and-Merging

In another way,

If Master has not diverged, instead of creating a new commit, git will just point master to the latest commit of the feature branch. This is a “fast forward.”

There won't be any "merge commit" in fast-forwarding merge.

Edit and replay XHR chrome/firefox etc?

5 years have passed and this essential requirement didn't get ignored by the Chrome devs.
While they offer no method to edit the data like in Firefox, they offer a full XHR replay.
This allows to debug ajax calls.
enter image description here
"Replay XHR" will repeat the entire transmission.

Spring: Returning empty HTTP Responses with ResponseEntity<Void> doesn't work

You can also not specify the type parameter which seems a bit cleaner and what Spring intended when looking at the docs:

@RequestMapping(method = RequestMethod.HEAD, value = Constants.KEY )
public ResponseEntity taxonomyPackageExists( @PathVariable final String key ){
    // ...
    return new ResponseEntity(HttpStatus.NO_CONTENT);
}

.mp4 file not playing in chrome

This started out as an attempt to cast video from my pc to a tv (with subtitles) eventually using Chromecast. And I ended up in this "does not play mp4" situation. However I seemed to have proved that Chrome will play (exactly the same) mp4 as long as it isn't wrapped in html(5) So here is what I have constructed. I have made a webpage under localhost and in there is a default.htm which contains:-

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<video  controls >
 <source src="sample.mp4" type="video/mp4">
 <track kind="subtitles" src="sample.vtt" label="gcsubs" srclang="eng">
</video>
</body>
</html>

the video and subtitle files are stored in the same folder as default.htm

I have the very latest version of Chrome (just updated this morning)

When I type the appropriate localhost... into my Chrome browser a black square appears with a "GO" arrow and an elapsed time bar, a mute button and an icon which says "CC". If I hit the go arrow, nothing happens (it doesn't change to "pause", the elapsed time doesn't move, and the timer sticks at 0:00. There are no error messages - nothing!

(note that if I input localhost.. to IE11 the video plays!!!!

In Chrome if I enter the disc address of sample.mp4 (i.e. C:\webstore\sample.mp4 then Chrome will play the video fine?.

This last bit is probably a working solution for Chromecast except that I cannot see any subtitles. I really want a solution with working subtitles. I just don't understand what is different in Chrome between the two methods of playing mp4

Wait on the Database Engine recovery handle failed. Check the SQL server error log for potential causes

In my case, setting SQL Server Database Engine service startup account to NT AUTHORITY\NETWORK SERVICE failed, but setting it to NT Authority\System allowed me to succesfully install my SQL Server 2016 STD instance.

Just check the following snapshot.

enter image description here

For further details, check @Shanky's answer at https://dba.stackexchange.com/a/71798/66179

Remember: you can avoid server rebooting using setup's SkipRules switch:

setup.exe /ACTION=INSTALL /SkipRules=RebootRequiredCheck

setup.exe /ACTION=UNINSTALL /SkipRules=RebootRequiredCheck

How to hide the bar at the top of "youtube" even when mouse hovers over it?

Since YouTube has deprecated the showinfo parameter you can trick the player. Youtube will always try to center its video but logo, title, watch later button etc.. will always stay at the left and right side respectively.

So what you can do is put your Youtube iframe inside some div:

<div class="frame-container">
   <iframe></iframe>
</div>

Then you can increase the size of frame-container to be out of browser window, while aligning it so that the iframe video comes to the center. Example:

.frame-container {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 */  
    padding-top: 25px;
    width: 300%; /* enlarge beyond browser width */
    left: -100%; /* center */
}

.frame-container iframe {
    position: absolute; 
    top: 0; 
    left: 0; 
    width: 100%; 
    height: 100%;
}

Finnaly put everything inside a wrapper div to prevent page stretching due to 300% width:

<div class="wrapper">
   <div class="frame-container">
      <iframe></iframe>
   </div>
</div>

.wrapper {
   overflow: hidden;
   max-width: 100%;
}

How to dump raw RTSP stream to file?

With this command I had poor image quality

ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -vcodec copy -acodec copy -f mp4 -y MyVideoFFmpeg.mp4

With this, almost without delay, I got good image quality.

ffmpeg -i rtsp://192.168.XXX.XXX:554/live.sdp -b 900k -vcodec copy -r 60 -y MyVdeoFFmpeg.avi

How do I view / replay a chrome network debugger har file saved with content?

Hardiff.com is pretty useful tool. It allows you to compare one or more .har files.

How to update json file with python

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

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

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

git rebase merge conflict

When you have a conflict during rebase you have three options:

  • You can run git rebase --abort to completely undo the rebase. Git will return you to your branch's state as it was before git rebase was called.

  • You can run git rebase --skip to completely skip the commit. That means that none of the changes introduced by the problematic commit will be included. It is very rare that you would choose this option.

  • You can fix the conflict as iltempo said. When you're finished, you'll need to call git rebase --continue. My mergetool is kdiff3 but there are many more which you can use to solve conflicts. You only need to set your merge tool in git's settings so it can be invoked when you call git mergetool https://git-scm.com/docs/git-mergetool

If none of the above works for you, then go for a walk and try again :)

How to fill background image of an UIView

Repeat:

UIImage *img = [UIImage imageNamed:@"bg.png"];
view.backgroundColor = [UIColor colorWithPatternImage:img];

Stretched

UIImage *img = [UIImage imageNamed:@"bg.png"];
view.layer.contents = img.CGImage;

How to Compare a long value is equal to Long value

First your code is not compiled. Line Long b = 1113;

is wrong. You have to say

Long b = 1113L;

Second when I fixed this compilation problem the code printed "not equals".

What does "while True" mean in Python?

A while loop takes a conditional argument (meaning something that is generally either true or false, or can be interpreted as such), and only executes while the condition yields True.

As for while True? Well, the simplest true conditional is True itself! So this is an infinite loop, usually good in a game that requires lots of looping. (More common from my perspective, though, is to set some sort of "done" variable to false and then making that true to end the game, and the loop would look more like while not done: or whatever.)

Undoing a 'git push'

Another way to do this:

  1. create another branch
  2. checkout the previous commit on that branch using "git checkout"
  3. push the new branch.
  4. delete the old branch & push the delete (use git push origin --delete <branch_name>)
  5. rename the new branch into the old branch
  6. push again.

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

You can do this:

function Sleep(seconds)
    local endTime = os.time() + seconds
    while os.time() < endTime do
    end
end
print("This is printed first!")
Sleep(5)
print("This is printed 5 seconds later!")

Security of REST authentication schemes

A previous answer only mentioned SSL in the context of data transfer and didn't actually cover authentication.

You're really asking about securely authenticating REST API clients. Unless you're using TLS client authentication, SSL alone is NOT a viable authentication mechanism for a REST API. SSL without client authc only authenticates the server, which is irrelevant for most REST APIs because you really want to authenticate the client.

If you don't use TLS client authentication, you'll need to use something like a digest-based authentication scheme (like Amazon Web Service's custom scheme) or OAuth 1.0a or even HTTP Basic authentication (but over SSL only).

These schemes authenticate that the request was sent by someone expected. TLS (SSL) (without client authentication) ensures that the data sent over the wire remains untampered. They are separate - but complementary - concerns.

For those interested, I've expanded on an SO question about HTTP Authentication Schemes and how they work.

How do I shrink my SQL Server Database?

You also have to modify the minimum size of the data and log files. DBCC SHRINKDATABASE will shrink the data inside the files you already have allocated. To shrink a file to a size smaller than its minimum size, use DBCC SHRINKFILE and specify the new size.

Filter Extensions in HTML form upload

I use javascript to check file extension. Here is my code:

HTML

<input name="fileToUpload" type="file" onchange="check_file()" >

.. ..

javascript

function check_file(){
                str=document.getElementById('fileToUpload').value.toUpperCase();
        suffix=".JPG";
        suffix2=".JPEG";
        if(str.indexOf(suffix, str.length - suffix.length) == -1||
                       str.indexOf(suffix2, str.length - suffix2.length) == -1){
        alert('File type not allowed,\nAllowed file: *.jpg,*.jpeg');
            document.getElementById('fileToUpload').value='';
        }
    }

Undoing a git rebase

If you successfully rebased against remote branch and can not git rebase --abort you still can do some tricks to save your work and don't have forced pushes. Suppose your current branch that was rebased by mistake is called your-branch and is tracking origin/your-branch

  • git branch -m your-branch-rebased # rename current branch
  • git checkout origin/your-branch # checkout to latest state that is known to origin
  • git checkout -b your-branch
  • check git log your-branch-rebased, compare to git log your-branch and define commits that are missing from your-branch
  • git cherry-pick COMMIT_HASH for every commit in your-branch-rebased
  • push your changes. Please aware that two local branches are associated with remote/your-branch and you should push only your-branch

Comparing two hashmaps for equal values and same key sets?

if you have two maps lets say map1 and map2 then using java8 Streams,we can compare maps using code below.But it is recommended to use equals rather then != or ==

boolean b = map1.entrySet().stream().filter(value -> 
            map2.entrySet().stream().anyMatch(value1 -> 
            (value1.getKey().equals(value.getKey()) && 
  value1.getValue().equals(value.getValue())))).findAny().isPresent();   


System.out.println("comparison  "+b);

Drawing an image from a data URL to a canvas

in javascript , using jquery for canvas id selection :

 var Canvas2 = $("#canvas2")[0];
        var Context2 = Canvas2.getContext("2d");
        var image = new Image();
        image.src = "images/eye.jpg";
        Context2.drawImage(image, 0, 0);

html5:

<canvas id="canvas2"></canvas>

PostgreSQL error: Fatal: role "username" does not exist

Working method,

  1. vi /etc/postgresql/9.3/main/pg_hba.conf
  2. local all postgres peer here change peer to trust
  3. restart, sudo service postgresql restart

  4. now try, psql -U postgres

How to make fixed header table inside scrollable div?

This is my "crutches" solution by using html and css. There used 2 tables and fixed width of tables and table cell`s

https://jsfiddle.net/babaikawow/s2xyct24/1/

HTML:

  <div class="container">
<table class="table" border = 1; >  <!-- fixed width header -->
                            <thead >
                                <tr>
                                    <th class="tbDataId" >?</th>
                                    <th class="tbDataName">?????????</th>
                                    <th class="tbDataData">????</th>
                                    <th class="tbDataData">?????? ??</th>
                                    <th class="tbDataDiseases">????????1</th>
                                    <th class="tbDataDiseases">????????2</th>
                                    <th class="tbDataDiseases">????????3</th>
                                    <th class="tbDataDiseases">????????4</th>
                                    <th class="tbDataDiseases">????????5</th>  
                                </tr>
                            </thead>  
                        </table> 

                        <div class="scrollTable"> <!-- scrolling block -->
                            <table class="table" border = 1;>
                                 <tbody>
                   <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                    <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                    <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                    <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                    <tr>
                      <td class="tbDataId" >?</td>
                                    <td class="tbDataName">?????????</td>
                                    <td class="tbDataData">????</td>
                                    <td class="tbDataData">?????? ??</td>
                                    <td class="tbDataDiseases">????????1</td>
                                    <td class="tbDataDiseases">????????2</td>
                                    <td class="tbDataDiseases">????????3</td>
                                    <td class="tbDataDiseases">????????4</td>
                                    <td class="tbDataDiseases">????????5</td> 
                   </tr>
                                </tbody>
                            </table>
                        </div> 
</div>

CSS:

*{
  box-sizing: border-box;
}

.container{
 width:1000px;
}
.scrollTable{

    overflow: scroll;
  overflow-x: hidden;
    height: 100px;
} 
table{
margin: 0px!important;
width:983px!important;
border-collapse: collapse; 

}

/*   Styles of the th and td  */

/* Id */
.tbDataId{
    width:5%;
}

/* ????,
?????? ?? */
.tbDataData{
    /*width:170px;*/
    width: 15%;
}

/* ? ? ? */
.tbDataName{
    width: 15%;
}

/*???????? */
.tbDataDiseases{
    width:10%;
}

Updating MySQL primary key

You can use the IGNORE keyword too, example:

 update IGNORE table set primary_field = 'value'...............

AndroidStudio: Failed to sync Install build tools

I had the same problem, in my cases this happened because I changed the time on my computer to load .apk on google play. I spent a few hours to fix "this" problem until I remembered and changed the time back.

How to determine the Schemas inside an Oracle Data Pump Export file

My solution (similar to KyleLanser's answer) (on a Unix box):

strings dumpfile.dmp | grep SCHEMA_LIST

iterating quickly through list of tuples

The question is dead but still knowing one more way doesn't hurt:

my_list = [ (old1, new1), (old2, new2), (old3, new3), ... (oldN, newN)]

for first,*args in my_list:
    if first == Value:
        PAIR_FOUND = True
        MATCHING_VALUE = args
        break

How does the data-toggle attribute work? (What's its API?)

The data-toggle attribute simple tell Bootstrap what exactly to do by giving it the name of the toggle action it is about to perform on a target element. If you specify collapse. It means bootstrap will collapse or uncollapse the element pointed by data-target of the action you clicked

Note: the target element must have the appropriate class for bootstrap to carry out the action

Source action:
data-toggle = collapse //type of toggle
data-target = #myDiv

Target:
class=collapse //I can collapse
id=myDiv

This is same for other type of toggle actions like tab, modal, dropdown

How to post SOAP Request from PHP

In my experience, it's not quite that simple. The built-in PHP SOAP client didn't work with the .NET-based SOAP server we had to use. It complained about an invalid schema definition. Even though .NET client worked with that server just fine. By the way, let me claim that SOAP interoperability is a myth.

The next step was NuSOAP. This worked for quite a while. By the way, for God's sake, don't forget to cache WSDL! But even with WSDL cached users complained the damn thing is slow.

Then, we decided to go bare HTTP, assembling the requests and reading the responses with SimpleXMLElemnt, like this:

$request_info = array();

$full_response = @http_post_data(
    'http://example.com/OTA_WS.asmx',
    $REQUEST_BODY,
    array(
        'headers' => array(
            'Content-Type' => 'text/xml; charset=UTF-8',
            'SOAPAction'   => 'HotelAvail',
        ),
        'timeout' => 60,

    ),
    $request_info
);

$response_xml = new SimpleXMLElement(strstr($full_response, '<?xml'));

foreach ($response_xml->xpath('//@HotelName') as $HotelName) {
    echo strval($HotelName) . "\n";
}

Note that in PHP 5.2 you'll need pecl_http, as far as (surprise-surpise!) there's no HTTP client built in.

Going to bare HTTP gained us over 30% in SOAP request times. And from then on we redirect all the performance complains to the server guys.

In the end, I'd recommend this latter approach, and not because of the performance. I think that, in general, in a dynamic language like PHP there's no benefit from all that WSDL/type-control. You don't need a fancy library to read and write XML, with all that stubs generation and dynamic proxies. Your language is already dynamic, and SimpleXMLElement works just fine, and is so easy to use. Also, you'll have less code, which is always good.

PHP - print all properties of an object

<?php var_dump(obj) ?>

or

<?php print_r(obj) ?>

These are the same things you use for arrays too.

These will show protected and private properties of objects with PHP 5. Static class members will not be shown according to the manual.

If you want to know the member methods you can use get_class_methods():

$class_methods = get_class_methods('myclass');
// or
$class_methods = get_class_methods(new myclass());
foreach ($class_methods as $method_name) 
{
    echo "$method_name<br/>";
}

Related stuff:

get_object_vars()

get_class_vars()

get_class() <-- for the name of the instance

Run JavaScript in Visual Studio Code

I am surprised this has not been mentioned yet:

Simply open the .js file in question in VS Code, switch to the 'Debug Console' tab, hit the debug button in the left nav bar, and click the run icon (play button)!

Requires nodejs to be installed!

Change Bootstrap tooltip color

We are using bootstrap 3.0 on our website, but none of the above steps worked in updating the styling of the tooltip. But I did find a solution using jQueryUI styling instead

https://jqueryui.com/tooltip/#custom-style

CSS

  .ui-tooltip, .arrow:after {
    background: black;
    border: 2px solid white;
  }
  .ui-tooltip {
    padding: 10px 20px;
    color: white;
    border-radius: 20px;
    font: bold 14px "Helvetica Neue", Sans-Serif;
    text-transform: uppercase;
    box-shadow: 0 0 7px black;
  }

HTML

<div class="qu_help" data-toggle="tooltip" title="Some Random Title"> 
   <span class="glyphicon glyphicon-question-sign" aria-hidden="true"></span>
</div>

I'm adding this answer in case someone else is in a similar situation as I was.

Reload the page after ajax success

You use the ajaxStop to execute code when the ajax are completed:

$(document).ajaxStop(function(){
  setTimeout("window.location = 'otherpage.html'",100);
});

How do I change the color of radio buttons?

As Fred mentioned, there is no way to natively style radio buttons in regards to color, size, etcc. But you can use CSS Pseudo elements to setup an impostor of any given radio button, and style it. Touching on what JamieD said, on how we can use the :after Pseudo element, you can use both :before and :after to achieve a desirable look.

Benefits of this approach:

  • Style your radio button and also Include a label for content.
  • Change the outer rim color and/or checked circle to any color you like.
  • Give it a transparent look with modifications to background color property and/or optional use of the opacity property.
  • Scale the size of your radio button.
  • Add various drop shadow properties such as CSS drop shadow inset where needed.
  • Blend this simple CSS/HTML trick into various Grid systems, such as Bootstrap 3.3.6, so it matches the rest of your Bootstrap components visually.

Explanation of short demo below:

  • Set up a relative in-line block for each radio button
  • Hide the native radio button sense there is no way to style it directly.
  • Style and align the label
  • Rebuilding CSS content on the :before Pseudo-element to do 2 things - style the outer rim of the radio button and set element to appear first (left of label content). You can learn basic steps on Pseudo-elements here - http://www.w3schools.com/css/css_pseudo_elements.asp
  • If the radio button is checked, request for label to display CSS content (the styled dot in the radio button) afterwards.

The HTML

<div class="radio-item">
    <input type="radio" id="ritema" name="ritem" value="ropt1">
    <label for="ritema">Option 1</label>
</div>

<div class="radio-item">
    <input type="radio" id="ritemb" name="ritem" value="ropt2">
    <label for="ritemb">Option 2</label>
</div>

The CSS

.radio-item {
  display: inline-block;
  position: relative;
  padding: 0 6px;
  margin: 10px 0 0;
}

.radio-item input[type='radio'] {
  display: none;
}

.radio-item label {
  color: #666;
  font-weight: normal;
}

.radio-item label:before {
  content: " ";
  display: inline-block;
  position: relative;
  top: 5px;
  margin: 0 5px 0 0;
  width: 20px;
  height: 20px;
  border-radius: 11px;
  border: 2px solid #004c97;
  background-color: transparent;
}

.radio-item input[type=radio]:checked + label:after {
  border-radius: 11px;
  width: 12px;
  height: 12px;
  position: absolute;
  top: 9px;
  left: 10px;
  content: " ";
  display: block;
  background: #004c97;
}

A short demo to see it in action

In conclusion, no JavaScript, images or batteries required. Pure CSS.

Does java have a int.tryparse that doesn't throw an exception for bad data?

Edit -- just saw your comment about the performance problems associated with a potentially bad piece of input data. I don't know offhand how try/catch on parseInt compares to a regex. I would guess, based on very little hard knowledge, that regexes are not hugely performant, compared to try/catch, in Java.

Anyway, I'd just do this:

public Integer tryParse(Object obj) {
  Integer retVal;
  try {
    retVal = Integer.parseInt((String) obj);
  } catch (NumberFormatException nfe) {
    retVal = 0; // or null if that is your preference
  }
  return retVal;
}

How to use the command update-alternatives --config java

update-alternatives is problematic in this case as it forces you to update all the elements depending on the JDK.

For this specific purpose, the package java-common contains a tool called update-java-alternatives.

It's straightforward to use it. First list the JDK installs available on your machine:

root@mylaptop:~# update-java-alternatives -l
java-1.7.0-openjdk-amd64 1071 /usr/lib/jvm/java-1.7.0-openjdk-amd64
java-1.8.0-openjdk-amd64 1069 /usr/lib/jvm/java-1.8.0-openjdk-amd64

And then pick one up:

root@mylaptop:~# update-java-alternatives -s java-1.7.0-openjdk-amd64

How to undo a successful "git cherry-pick"?

Faced with this same problem, I discovered if you have committed and/or pushed to remote since your successful cherry-pick, and you want to remove it, you can find the cherry-pick's SHA by running:

git log --graph --decorate --oneline

Then, (after using :wq to exit the log) you can remove the cherry-pick using

git rebase -p --onto YOUR_SHA_HERE^ YOUR_SHA_HERE

where YOUR_SHA_HERE equals the cherry-picked commit's 40- or abbreviated 7-character SHA.

At first, you won't be able to push your changes because your remote repo and your local repo will have different commit histories. You can force your local commits to replace what's on your remote by using

git push --force origin YOUR_REPO_NAME

(I adapted this solution from Seth Robertson: See "Removing an entire commit.")

How do I push a new local branch to a remote Git repository and track it too?

I think this is the simplest alias, add to your ~/.gitconfig

[alias]
  publish-branch = !git push -u origin $(git rev-parse --abbrev-ref HEAD)

You just run

git publish-branch

and... it publishes the branch

Android : difference between invisible and gone?

For ListView or GridView there is an another difference, when visibility initially set to

INVISIBLE:

Adapter's getView() function called

GONE:

Adapter's getView() function didn't call, thus preventing views to load, when it is unnecessary

CASE .. WHEN expression in Oracle SQL

Following syntax would work :

....
where x.p_NBR =to_number(substr(y.k_str,11,5))
and x.q_nbr = 
 (case 
 when instr(substr(y.m_str,11,9),'_') = 6   then  to_number(substr(y.m_str,11,5))
 when instr(substr(y.m_str,11,9),'_') = 0   then  to_number(substr(y.m_str,11,9))
  else 
       1
  end
)

jQuery Clone table row

Try this code, I used the following code for cloning and removing the cloned element, i have also used new class (newClass) which can be added automatically with the newly cloned html

for cloning..

 $(".tr_clone_add").live('click', function() {
    var $tr    = $(this).closest('.tr_clone');
    var newClass='newClass';
    var $clone = $tr.clone().addClass(newClass);
    $clone.find(':text').val('');
    $tr.after($clone);
});

for removing the clone element.

$(".tr_clone_remove").live('click', function() { //Once remove button is clicked
    $(".newClass:last").remove(); //Remove field html
    x--; //Decrement field counter
});

html is as followinng

<tr class="tr_clone">
                       <!-- <td>1</td>-->
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span12"></td>
                        <td><input type="text" class="span10" readonly>
                        <span><a href="javascript:void(0);" class="tr_clone_add" title="Add field"><span><i class="icon-plus-sign"></i></span></a> <a href="javascript:void(0);" class="tr_clone_remove" title="Remove field"><span style="color: #D63939;"><i class="icon-remove-sign"></i></span></a> </span> </td> </tr>

MySQL compare DATE string with string from DATETIME field

If you want to select all rows where the DATE part of a DATETIME column matches a certain literal, you cannot do it like so:

WHERE startTime = '2010-04-29'

because MySQL cannot compare a DATE and a DATETIME directly. What MySQL does, it extends the given DATE literal with the time '00:00:00'. So your condition becomes

WHERE startTime = '2010-04-29 00:00:00'

Certainly not what you want!

The condition is a range and hence it should be given as range. There are several possibilities:

WHERE startTime BETWEEN '2010-04-29 00:00:00' AND '2010-04-29 23:59:59'
WHERE startTime >= '2010-04-29' AND startTime < ('2010-04-29' + INTERVAL 1 DAY)

There is a tiny possibility for the first to be wrong - when your DATETIME column uses subsecond resolution and there is an appointment at 23:59:59 + epsilon. In general I suggest to use the second variant.

Both variants can use an index on startTime which will become important when the table grows.

How to flush route table in windows?

You can open a command prompt and do a

route print

and see your current routing table.

You can modify it by

route add    d.d.d.d mask m.m.m.m g.g.g.g 
route delete d.d.d.d mask m.m.m.m g.g.g.g 
route change d.d.d.d mask m.m.m.m g.g.g.g

these seem to work

I run a ping d.d.d.d -t change the route and it changes. (my test involved routing to a dead route and the ping stopped)

Change Default branch in gitlab

In 8.0+ it looks like this was moved into the project. If you open your project and go to the gear icon on the right, then "Edit Project" you can set the default branch for the project.

C++ vector's insert & push_back difference

The biggest difference is their functionality. push_back always puts a new element at the end of the vector and insert allows you to select new element's position. This impacts the performance. vector elements are moved in the memory only when it's necessary to increase it's length because too little memory was allocated for it. On the other hand insert forces to move all elements after the selected position of a new element. You simply have to make a place for it. This is why insert might often be less efficient than push_back.

Check if string is neither empty nor space in shell script

In case you need to check against any amount of whitespace, not just single space, you can do this:

To strip string of extra white space (also condences whitespace in the middle to one space):

trimmed=`echo -- $original`

The -- ensures that if $original contains switches understood by echo, they'll still be considered as normal arguments to be echoed. Also it's important to not put "" around $original, or the spaces will not get removed.

After that you can just check if $trimmed is empty.

[ -z "$trimmed" ] && echo "empty!"

Error: free(): invalid next size (fast):

I encountered the same problem, even though I did not make any dynamic memory allocation in my program, but I was accessing a vector's index without allocating memory for it. So, if the same case, better allocate some memory using resize() and then access vector elements.

How to change column width in DataGridView?

Set the "AutoSizeColumnsMode" property to "Fill".. By default it is set to 'NONE'. Now columns will be filled across the DatagridView. Then you can set the width of other columns accordingly.

DataGridView1.Columns[0].Width=100;// The id column 
DataGridView1.Columns[1].Width=200;// The abbrevation columln
//Third Colulmns 'description' will automatically be resized to fill the remaining 
//space

What is the best way to iterate over multiple lists at once?

The usual way is to use zip():

for x, y in zip(a, b):
    # x is from a, y is from b

This will stop when the shorter of the two iterables a and b is exhausted. Also worth noting: itertools.izip() (Python 2 only) and itertools.izip_longest() (itertools.zip_longest() in Python 3).

Redirect to new Page in AngularJS using $location

Try entering the url inside the function

$location.url('http://www.google.com')

How to add a new line in textarea element?

just use <br>
ex:

<textarea>
blablablabla <br> kakakakakak <br> fafafafafaf 
</textarea>

result:
blablablabla
kakakakakak
fafafafafaf

load csv into 2D matrix with numpy for plotting

You can read a CSV file with headers into a NumPy structured array with np.genfromtxt. For example:

import numpy as np

csv_fname = 'file.csv'
with open(csv_fname, 'w') as fp:
    fp.write("""\
"A","B","C","D","E","F","timestamp"
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291111964948E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291113113366E12
611.88243,9089.5601,5133.0,864.07514,1715.37476,765.22777,1.291120650486E12
""")

# Read the CSV file into a Numpy record array
r = np.genfromtxt(csv_fname, delimiter=',', names=True, case_sensitive=True)
print(repr(r))

which looks like this:

array([(611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111196e+12),
       (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29111311e+12),
       (611.88243, 9089.5601, 5133., 864.07514, 1715.37476, 765.22777, 1.29112065e+12)],
      dtype=[('A', '<f8'), ('B', '<f8'), ('C', '<f8'), ('D', '<f8'), ('E', '<f8'), ('F', '<f8'), ('timestamp', '<f8')])

You can access a named column like this r['E']:

array([1715.37476, 1715.37476, 1715.37476])

Note: this answer previously used np.recfromcsv to read the data into a NumPy record array. While there was nothing wrong with that method, structured arrays are generally better than record arrays for speed and compatibility.

what is trailing whitespace and how can I handle this?

This is just a warning and it doesn't make problem for your project to run, you can just ignore it and continue coding. But if you're obsessed about clean coding, same as me, you have two options:

  1. Hover the mouse on warning in VS Code or any IDE and use quick fix to remove white spaces.
  2. Press f1 then type trim trailing whitespace.

Search all tables, all columns for a specific value SQL Server

I published one here: FullParam SQL Blog

/* Reto Egeter, fullparam.wordpress.com */

DECLARE @SearchStrTableName nvarchar(255), @SearchStrColumnName nvarchar(255), @SearchStrColumnValue nvarchar(255), @SearchStrInXML bit, @FullRowResult bit, @FullRowResultRows int
SET @SearchStrColumnValue = '%searchthis%' /* use LIKE syntax */
SET @FullRowResult = 1
SET @FullRowResultRows = 3
SET @SearchStrTableName = NULL /* NULL for all tables, uses LIKE syntax */
SET @SearchStrColumnName = NULL /* NULL for all columns, uses LIKE syntax */
SET @SearchStrInXML = 0 /* Searching XML data may be slow */

IF OBJECT_ID('tempdb..#Results') IS NOT NULL DROP TABLE #Results
CREATE TABLE #Results (TableName nvarchar(128), ColumnName nvarchar(128), ColumnValue nvarchar(max),ColumnType nvarchar(20))

SET NOCOUNT ON

DECLARE @TableName nvarchar(256) = '',@ColumnName nvarchar(128),@ColumnType nvarchar(20), @QuotedSearchStrColumnValue nvarchar(110), @QuotedSearchStrColumnName nvarchar(110)
SET @QuotedSearchStrColumnValue = QUOTENAME(@SearchStrColumnValue,'''')
DECLARE @ColumnNameTable TABLE (COLUMN_NAME nvarchar(128),DATA_TYPE nvarchar(20))

WHILE @TableName IS NOT NULL
BEGIN
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM    INFORMATION_SCHEMA.TABLES
        WHERE       TABLE_TYPE = 'BASE TABLE'
            AND TABLE_NAME LIKE COALESCE(@SearchStrTableName,TABLE_NAME)
            AND QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND OBJECTPROPERTY(OBJECT_ID(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)), 'IsMSShipped') = 0
    )
    IF @TableName IS NOT NULL
    BEGIN
        DECLARE @sql VARCHAR(MAX)
        SET @sql = 'SELECT QUOTENAME(COLUMN_NAME),DATA_TYPE
                FROM    INFORMATION_SCHEMA.COLUMNS
                WHERE       TABLE_SCHEMA    = PARSENAME(''' + @TableName + ''', 2)
                AND TABLE_NAME  = PARSENAME(''' + @TableName + ''', 1)
                AND DATA_TYPE IN (' + CASE WHEN ISNUMERIC(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@SearchStrColumnValue,'%',''),'_',''),'[',''),']',''),'-','')) = 1 THEN '''tinyint'',''int'',''smallint'',''bigint'',''numeric'',''decimal'',''smallmoney'',''money'',' ELSE '' END + '''char'',''varchar'',''nchar'',''nvarchar'',''timestamp'',''uniqueidentifier''' + CASE @SearchStrInXML WHEN 1 THEN ',''xml''' ELSE '' END + ')
                AND COLUMN_NAME LIKE COALESCE(' + CASE WHEN @SearchStrColumnName IS NULL THEN 'NULL' ELSE '''' + @SearchStrColumnName + '''' END  + ',COLUMN_NAME)'
        INSERT INTO @ColumnNameTable
        EXEC (@sql)
        WHILE EXISTS (SELECT TOP 1 COLUMN_NAME FROM @ColumnNameTable)
        BEGIN
            PRINT @ColumnName
            SELECT TOP 1 @ColumnName = COLUMN_NAME,@ColumnType = DATA_TYPE FROM @ColumnNameTable
            SET @sql = 'SELECT ''' + @TableName + ''',''' + @ColumnName + ''',' + CASE @ColumnType WHEN 'xml' THEN 'LEFT(CAST(' + @ColumnName + ' AS nvarchar(MAX)), 4096),''' 
            WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + '),'''
            ELSE 'LEFT(' + @ColumnName + ', 4096),''' END + @ColumnType + ''' 
                    FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))' 
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
            INSERT INTO #Results
            EXEC(@sql)
            IF @@ROWCOUNT > 0 IF @FullRowResult = 1 
            BEGIN
                SET @sql = 'SELECT TOP ' + CAST(@FullRowResultRows AS VARCHAR(3)) + ' ''' + @TableName + ''' AS [TableFound],''' + @ColumnName + ''' AS [ColumnFound],''FullRow>'' AS [FullRow>],*' +
                    ' FROM ' + @TableName + ' (NOLOCK) ' +
                    ' WHERE ' + CASE @ColumnType WHEN 'xml' THEN 'CAST(' + @ColumnName + ' AS nvarchar(MAX))' 
                    WHEN 'timestamp' THEN 'master.dbo.fn_varbintohexstr('+ @ColumnName + ')'
                    ELSE @ColumnName END + ' LIKE ' + @QuotedSearchStrColumnValue
                EXEC(@sql)
            END
            DELETE FROM @ColumnNameTable WHERE COLUMN_NAME = @ColumnName
        END 
    END
END
SET NOCOUNT OFF

SELECT TableName, ColumnName, ColumnValue, ColumnType, COUNT(*) AS Count FROM #Results
GROUP BY TableName, ColumnName, ColumnValue, ColumnType

Insert php variable in a href

in php

echo '<a href="' . $folder_path . '">Link text</a>';

or

<a href="<?=$folder_path?>">Link text</a>;

or

<a href="<?php echo $folder_path ?>">Link text</a>;

How to fix libeay32.dll was not found error

I encountered the same problem when I tried to install curl in my 32 bit win 7 machine. As answered by Buravchik it is indeed dependency of SSL and installing openssl fixed it. Just a point to take care is that while installing openssl you will get a prompt to ask where do you wish to put the dependent DLLS. Make sure to put it in windows system directory as other programs like curl and wget will also be needing it.

enter image description here

Difference between request.getSession() and request.getSession(true)

request.getSession() is just a convenience method. It does exactly the same as request.getSession(true).

EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType

My issue was similar - I had a new table i was creating that ahd to tie in to the identity users. After reading the above answers, realized it had to do with IsdentityUser and the inherited properites. I already had Identity set up as its own Context, so to avoid inherently tying the two together, rather than using the related user table as a true EF property, I set up a non-mapped property with the query to get the related entities. (DataManager is set up to retrieve the current context in which OtherEntity exists.)

    [Table("UserOtherEntity")]
        public partial class UserOtherEntity
        {
            public Guid UserOtherEntityId { get; set; }
            [Required]
            [StringLength(128)]
            public string UserId { get; set; }
            [Required]
            public Guid OtherEntityId { get; set; }
            public virtual OtherEntity OtherEntity { get; set; }
        }

    public partial class UserOtherEntity : DataManager
        {
            public static IEnumerable<OtherEntity> GetOtherEntitiesByUserId(string userId)
            {
                return Connect2Context.UserOtherEntities.Where(ue => ue.UserId == userId).Select(ue => ue.OtherEntity);
            }
        }

public partial class ApplicationUser : IdentityUser
    {
        public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
        {
            // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
            var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
            // Add custom user claims here
            return userIdentity;
        }

        [NotMapped]
        public IEnumerable<OtherEntity> OtherEntities
        {
            get
            {
                return UserOtherEntities.GetOtherEntitiesByUserId(this.Id);
            }
        }
    }

How to make gradient background in android

Following link may help you http://angrytools.com/gradient/ .This will create custom gradient background in android as like in photoshop.

Is there a way to ignore a single FindBugs warning?

I'm going to leave this one here: https://stackoverflow.com/a/14509697/1356953

Please note that this works with java.lang.SuppressWarningsso no need to use a separate annotation.

@SuppressWarnings on a field only suppresses findbugs warnings reported for that field declaration, not every warning associated with that field.

For example, this suppresses the "Field only ever set to null" warning:

@SuppressWarnings("UWF_NULL_FIELD") String s = null; I think the best you can do is isolate the code with the warning into the smallest method you can, then suppress the warning on the whole method.

Unzip All Files In A Directory

In any POSIX shell, this will unzip into a different directory for each zip file:

for file in *.zip
do
    directory="${file%.zip}"
    unzip "$file" -d "$directory"
done

How can I check if two segments intersect?

Suppose the two segments have endpoints A,B and C,D. The numerically robust way to determine intersection is to check the sign of the four determinants:

| Ax-Cx  Bx-Cx |    | Ax-Dx  Bx-Dx |
| Ay-Cy  By-Cy |    | Ay-Dy  By-Dy |

| Cx-Ax  Dx-Ax |    | Cx-Bx  Dx-Bx |
| Cy-Ay  Dy-Ay |    | Cy-By  Dy-By |

For intersection, each determinant on the left must have the opposite sign of the one to the right, but there need not be any relationship between the two lines. You are basically checking each point of a segment against the other segment to make sure they lie on opposite sides of the line defined by the other segment.

See here: http://www.cs.cmu.edu/~quake/robust.html

Catch paste input

See this example: http://www.p2e.dk/diverse/detectPaste.htm

It essentialy tracks every change with oninput event and then checks if it’s a paste by string comparison. Oh, and in IE there’s an onpaste event. So:

$ (something).bind ("input paste", function (e) {
    // check for paste as in example above and
    // do something
})

How to see which flags -march=native will activate?

It should be (-### is similar to -v):

echo | gcc -### -E - -march=native 

To show the "real" native flags for gcc.

You can make them appear more "clearly" with a command:

gcc -### -E - -march=native 2>&1 | sed -r '/cc1/!d;s/(")|(^.* - )//g'

and you can get rid of flags with -mno-* with:

gcc -### -E - -march=native 2>&1 | sed -r '/cc1/!d;s/(")|(^.* - )|( -mno-[^\ ]+)//g'

iOS 9 not opening Instagram app with URL SCHEME

Facebook sharing from a share dialog fails even with @Matthieu answer (which is 100% correct for the rest of social URLs). I had to add a set of URL i reversed from Facebook SDK.

<array>
        <string>fbapi</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
        <string>fb-messenger-api</string>
        <string>twitter</string>
        <string>whatsapp</string>
        <string>wechat</string>
        <string>line</string>
        <string>instagram</string>
        <string>kakaotalk</string>
        <string>mqq</string>
        <string>vk</string>
        <string>comgooglemaps</string>
        <string>fbapi20130214</string>                                                    
        <string>fbapi20130410</string>                                                     
        <string>fbapi20130702</string>                                                    
        <string>fbapi20131010</string>                                                    
        <string>fbapi20131219</string>                                                    
        <string>fbapi20140410</string>                                                     
        <string>fbapi20140116</string>                                                     
        <string>fbapi20150313</string>                                                     
        <string>fbapi20150629</string>
    </array>

html 5 audio tag width

Set it the same way you'd set the width of any other HTML element, with CSS:

audio { width: 200px; }

Note that audio is an inline element by default in Firefox, so you might also want to set it to display: block. Here's an example.

Can I do Android Programming in C++, C?

There is more than one library for working in C++ in Android programming:

  1. C++ - qt (A Nokia product, also available as LGPL)
  2. C++ - Wxwidget (Available as GPL)

Is it correct to use alt tag for an anchor link?

No, an alt attribute (it would be an attribute, not a tag) is not allowed for an a element in any HTML specification or draft. And it does not seem to be recognized by any browser either as having any significance.

It’s a bit mystery why people try to use it, then, but the probable explanation is that they are doing so in analog with alt attribute for img elements, expecting to see a “tooltip” on mouseover. There are two things wrong with this. First, each element has attributes of its own, defined in the specs for each element. Second, the “tooltip” rendering of alt attributes in some ancient browsers is/was a quirk or even a bug, rather than something to be expected; the alt attribute is supposed to be presented to the user if and only if the image itself is not presented, for whatever reason.

To create a “tooltip”, use the title attribute instead or, much better, Google for "CSS tooltips" and use CSS-based tooltips of your preference (they can be characterized as hidden “layers” that become visible on mouseover).

Is Task.Result the same as .GetAwaiter.GetResult()?

I checked the source code of TaskOfResult.cs (Source code of TaskOfResult.cs):

If Task is not completed, Task.Result will call Task.Wait() method in getter.

public TResult Result
{
    get
    {
        // If the result has not been calculated yet, wait for it.
        if (!IsCompleted)
        {
            // We call NOCTD for two reasons: 
            //    1. If the task runs on another thread, then we definitely need to notify that thread-slipping is required.
            //    2. If the task runs inline but takes some time to complete, it will suffer ThreadAbort with possible state corruption.
            //         - it is best to prevent this unless the user explicitly asks to view the value with thread-slipping enabled.
            //#if !PFX_LEGACY_3_5
            //                    Debugger.NotifyOfCrossThreadDependency();  
            //#endif
            Wait();
        }

        // Throw an exception if appropriate.
        ThrowIfExceptional(!m_resultWasSet);

        // We shouldn't be here if the result has not been set.
        Contract.Assert(m_resultWasSet, "Task<T>.Result getter: Expected result to have been set.");

        return m_result;
    }
    internal set
    {
        Contract.Assert(m_valueSelector == null, "Task<T>.Result_set: m_valueSelector != null");

        if (!TrySetResult(value))
        {
            throw new InvalidOperationException(Strings.TaskT_TransitionToFinal_AlreadyCompleted);
        }
    }
}

If We call GetAwaiter method of Task, Task will wrapped TaskAwaiter<TResult> (Source code of GetAwaiter()), (Source code of TaskAwaiter) :

public TaskAwaiter GetAwaiter()
{
    return new TaskAwaiter(this);
}

And If We call GetResult() method of TaskAwaiter<TResult>, it will call Task.Result property, that Task.Result will call Wait() method of Task ( Source code of GetResult()):

public TResult GetResult()
{
    TaskAwaiter.ValidateEnd(m_task);
    return m_task.Result;
}

It is source code of ValidateEnd(Task task) ( Source code of ValidateEnd(Task task) ):

internal static void ValidateEnd(Task task)
{
    if (task.Status != TaskStatus.RanToCompletion)
         HandleNonSuccess(task);
}

private static void HandleNonSuccess(Task task)
{
    if (!task.IsCompleted)
    {
        try { task.Wait(); }
        catch { }
    }
    if (task.Status != TaskStatus.RanToCompletion)
    {
        ThrowForNonSuccess(task);
    }
}

This is my conclusion:

As can be seen GetResult() is calling TaskAwaiter.ValidateEnd(...), therefore Task.Result is not same GetAwaiter.GetResult().

I think GetAwaiter().GetResult() is a beter choice instead of .Result because it don't wrap exceptions.

I read this at page 582 in C# 7 in a Nutshell (Joseph Albahari & Ben Albahari) book

If an antecedent task faults, the exception is re-thrown when the continuation code calls awaiter.GetResult() . Rather than calling GetResult , we could simply access the Result property of the antecedent. The benefit of calling GetResult is that if the antecedent faults, the exception is thrown directly without being wrapped in AggregateException , allowing for simpler and cleaner catch blocks.

Source: C# 7 in a Nutshell's page 582

How to get the current TimeStamp?

I think you are looking for this function:

http://doc.qt.io/qt-5/qdatetime.html#toTime_t

uint QDateTime::toTime_t () const

Returns the datetime as the number of seconds that have passed since 1970-01-01T00:00:00, > Coordinated Universal Time (Qt::UTC).

On systems that do not support time zones, this function will behave as if local time were Qt::UTC.

See also setTime_t().

How can I read an input string of unknown length?

Enter while securing an area dynamically

E.G.

#include <stdio.h>
#include <stdlib.h>

char *inputString(FILE* fp, size_t size){
//The size is extended by the input with the value of the provisional
    char *str;
    int ch;
    size_t len = 0;
    str = realloc(NULL, sizeof(*str)*size);//size is start size
    if(!str)return str;
    while(EOF!=(ch=fgetc(fp)) && ch != '\n'){
        str[len++]=ch;
        if(len==size){
            str = realloc(str, sizeof(*str)*(size+=16));
            if(!str)return str;
        }
    }
    str[len++]='\0';

    return realloc(str, sizeof(*str)*len);
}

int main(void){
    char *m;

    printf("input string : ");
    m = inputString(stdin, 10);
    printf("%s\n", m);

    free(m);
    return 0;
}

How can I override inline styles with external CSS?

!important, after your CSS declaration.

div {
   color: blue !important; 

   /* This Is Now Working */
}

Refresh a page using PHP

header('Location: .'); seems to refresh the page in Chrome, Firefox, Edge, and Internet Explorer 11.

Invariant Violation: Could not find "store" in either the context or props of "Connect(SportsDatabase)"

in my case just

const myReducers = combineReducers({
  user: UserReducer
});

const store: any = createStore(
  myReducers,
  applyMiddleware(thunk)
);

shallow(<Login />, { context: { store } });

Get Category name from Post ID

here you go get_the_category( $post->ID ); will return the array of categories of that post you need to loop through the array

$category_detail=get_the_category('4');//$post->ID
foreach($category_detail as $cd){
echo $cd->cat_name;
}

get_the_category

PHP 7 RC3: How to install missing MySQL PDO

['class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost:3306;dbname=testdb',
    'username' => 'user',
    'password' => 'password',
    'charset' => 'utf8',]

It's simple: Just provide the port number along with the host name and set default sock path to your mysql.sock file path in php.ini which the server is running on.

Custom ImageView with drop shadow

I've built upon the answer above - https://stackoverflow.com/a/11155031/2060486 - to create a shadow around ALL sides..

 private static final int GRAY_COLOR_FOR_SHADE = Color.argb(50, 79, 79, 79);

// this method takes a bitmap and draws around it 4 rectangles with gradient to create a
// shadow effect.
public static Bitmap addShadowToBitmap(Bitmap origBitmap) {
    int shadowThickness = 13; // can be adjusted as needed
    int bmpOriginalWidth = origBitmap.getWidth();
    int bmpOriginalHeight = origBitmap.getHeight();
    int bigW = bmpOriginalWidth + shadowThickness * 2; // getting dimensions for a bigger bitmap with margins
    int bigH = bmpOriginalHeight + shadowThickness * 2;
    Bitmap containerBitmap = Bitmap.createBitmap(bigW, bigH, Bitmap.Config.ARGB_8888);
    Bitmap copyOfOrigBitmap = Bitmap.createScaledBitmap(origBitmap, bmpOriginalWidth, bmpOriginalHeight, false);
    Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
    Canvas canvas = new Canvas(containerBitmap); // drawing the shades on the bigger bitmap
    //right shade - direction of gradient is positive x (width)
    Shader rightShader = new LinearGradient(bmpOriginalWidth, 0, bigW, 0, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(rightShader);
    canvas.drawRect(bigW - shadowThickness, shadowThickness, bigW, bigH - shadowThickness, paint);
    //bottom shade - direction is positive y (height)
    Shader bottomShader = new LinearGradient(0, bmpOriginalHeight, 0, bigH, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(bottomShader);
    canvas.drawRect(shadowThickness, bigH - shadowThickness, bigW - shadowThickness, bigH, paint);
    //left shade - direction is negative x
    Shader leftShader = new LinearGradient(shadowThickness, 0, 0, 0, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(leftShader);
    canvas.drawRect(0, shadowThickness, shadowThickness, bigH - shadowThickness, paint);
    //top shade - direction is negative y
    Shader topShader = new LinearGradient(0, shadowThickness, 0, 0, GRAY_COLOR_FOR_SHADE,
            Color.TRANSPARENT, Shader.TileMode.CLAMP);
    paint.setShader(topShader);
    canvas.drawRect(shadowThickness, 0, bigW - shadowThickness, shadowThickness, paint);
    // starting to draw bitmap not from 0,0 to get margins for shade rectangles
    canvas.drawBitmap(copyOfOrigBitmap, shadowThickness, shadowThickness, null);
    return containerBitmap;
}

Change the color in the const as you see fit.

How to get the list of files in a directory in a shell script?

find "${search_dir}" "${work_dir}" -mindepth 1 -maxdepth 1 -type f -print0 | xargs -0 -I {} echo "{}"

How to determine a Python variable's type?

a = "cool"
type(a)

//result 'str'
<class 'str'>
or 
do 
`dir(a)` 
to see the list of inbuilt methods you can have on the variable.

Using Python's os.path, how do I go up one directory?

If you are using Python 3.4 or newer, a convenient way to move up multiple directories is pathlib:

from pathlib import Path

full_path = "path/to/directory"
str(Path(full_path).parents[0])  # "path/to"
str(Path(full_path).parents[1])  # "path"
str(Path(full_path).parents[2])  # "."

Tool to monitor HTTP, TCP, etc. Web Service traffic

I second Wireshark. It is very powerful and versatile. And since this tool will work not only on Windows but also on Linux or Mac OSX, investing your time to learn it (quite easy actually) makes sense. Whatever the platform or the language you use, it makes sense.

Regards,

Richard Just Programmer http://sili.co.nz/blog

What size should apple-touch-icon.png be for iPad and iPhone?

TL;DR: use one PNG icon at 180 x 180 px @ 150 ppi and then link to it like this:

<link rel="apple-touch-icon" href="path/to/apple-touch-icon.png">

Details on the Approach

As of 2020-04, the canonical response from Apple is reflected in their documentation on iOS.

Officially, the spec says:

  • iPhone 180px × 180px (60pt × 60pt @3x)
  • iPhone 120px × 120px (60pt × 60pt @2x)
  • iPad Pro 167px × 167px (83.5pt × 83.5pt @2x)
  • iPad, iPad mini 152px × 152px (76pt × 76pt @2x)

In reality, these sizing differences are tiny, so the performance savings will really only matter on very high traffic sites.

For lower traffic sites, I typically use one PNG icon at 180 x 180 px @ 150 ppi and get very good results on all devices, even the plus sized ones.

Copy map values to vector in STL

One way is to use functor:

 template <class T1, class T2>
    class CopyMapToVec
    {
    public: 
        CopyMapToVec(std::vector<T2>& aVec): mVec(aVec){}

        bool operator () (const std::pair<T1,T2>& mapVal) const
        {
            mVec.push_back(mapVal.second);
            return true;
        }
    private:
        std::vector<T2>& mVec;
    };


int main()
{
    std::map<std::string, int> myMap;
    myMap["test1"] = 1;
    myMap["test2"] = 2;

    std::vector<int>  myVector;

    //reserve the memory for vector
    myVector.reserve(myMap.size());
    //create the functor
    CopyMapToVec<std::string, int> aConverter(myVector);

    //call the functor
    std::for_each(myMap.begin(), myMap.end(), aConverter);
}

how to create a cookie and add to http response from inside my service layer?

Following @Aravind's answer with more details

@RequestMapping("/myPath.htm")
public ModelAndView add(HttpServletRequest request, HttpServletResponse response) throws Exception{
    myServiceMethodSettingCookie(request, response);        //Do service call passing the response
    return new ModelAndView("CustomerAddView");
}

// service method
void myServiceMethodSettingCookie(HttpServletRequest request, HttpServletResponse response){
    final String cookieName = "my_cool_cookie";
    final String cookieValue = "my cool value here !";  // you could assign it some encoded value
    final Boolean useSecureCookie = false;
    final int expiryTime = 60 * 60 * 24;  // 24h in seconds
    final String cookiePath = "/";

    Cookie cookie = new Cookie(cookieName, cookieValue);

    cookie.setSecure(useSecureCookie);  // determines whether the cookie should only be sent using a secure protocol, such as HTTPS or SSL

    cookie.setMaxAge(expiryTime);  // A negative value means that the cookie is not stored persistently and will be deleted when the Web browser exits. A zero value causes the cookie to be deleted.

    cookie.setPath(cookiePath);  // The cookie is visible to all the pages in the directory you specify, and all the pages in that directory's subdirectories

    response.addCookie(cookie);
}

Related docs:

http://docs.oracle.com/javaee/7/api/javax/servlet/http/Cookie.html

http://docs.spring.io/spring-security/site/docs/3.0.x/reference/springsecurity.html

How to set some xlim and ylim in Seaborn lmplot facetgrid

You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)

Then you can get hold of the axes objects (an array of axes):

axes = lm.axes

After that you can tweak the axes properties

axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)

creates:

enter image description here

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

The dependencies must be applied as shown below to solve this issue :

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.android.support:support-v4:27.1.0'
implementation 'com.android.support:appcompat-v7:27.1.0'
implementation 'com.android.support:recyclerview-v7:27.1.0'
}

Please do not use the version of :

v7:28.0.0-alpha1

Why doesn't height: 100% work to expand divs to the screen height?

You should try with the parent elements;

html, body, form, main {
    height: 100%;
}

Then this will be enough :

#s7 {
   height: 100%;
}

Redis: How to access Redis log file

Found it with:

sudo tail /var/log/redis/redis-server.log -n 100

So if the setup was more standard that should be:

sudo tail /var/log/redis_6379.log -n 100

This outputs the last 100 lines of the file.

Where your log file is located is in your configs that you can access with:

redis-cli CONFIG GET *

The log file may not always be shown using the above. In that case use

tail -f `less  /etc/redis/redis.conf | grep logfile|cut -d\  -f2`

REST API - Use the "Accept: application/json" HTTP Header

Basically I use Fiddler or Postman for testing API's.

In fiddler, in request header you need to specify instead of xml, html you need to change it to json. Eg: Accept: application/json. That should do the job.

How can I find matching values in two arrays?

You can use :

const intersection = array1.filter(element => array2.includes(element));

How is an HTTP POST request made in node.js?

Posting another axios example of an axios.post request that uses additional configuration options and custom headers.

_x000D_
_x000D_
var postData = {_x000D_
  email: "[email protected]",_x000D_
  password: "password"_x000D_
};_x000D_
_x000D_
let axiosConfig = {_x000D_
  headers: {_x000D_
      'Content-Type': 'application/json;charset=UTF-8',_x000D_
      "Access-Control-Allow-Origin": "*",_x000D_
  }_x000D_
};_x000D_
_x000D_
axios.post('http://<host>:<port>/<path>', postData, axiosConfig)_x000D_
.then((res) => {_x000D_
  console.log("RESPONSE RECEIVED: ", res);_x000D_
})_x000D_
.catch((err) => {_x000D_
  console.log("AXIOS ERROR: ", err);_x000D_
})
_x000D_
_x000D_
_x000D_

Counting Number of Letters in a string variable

You can simply use

int numberOfLetters = yourWord.Length;

or to be cool and trendy, use LINQ like this :

int numberOfLetters = yourWord.ToCharArray().Count();

and if you hate both Properties and LINQ, you can go old school with a loop :

int numberOfLetters = 0;
foreach (char letter in yourWord)
{
    numberOfLetters++;
}

Run local java applet in browser (chrome/firefox) "Your security settings have blocked a local application from running"

This problem happens when older versions of java still on your system disrupt any new versions installed. To stop this problem you need to first remove all java software using - Control Panel + Remove Programs + then uninstall java. (At this stage, I recommend cleaning out your registry using CCleaner using their Registry option or similar program to ensure a clean sweep then reboot) After rebooting reinstall the most recent version of java and all will be well.

http://www.filehippo.com/download_ccleaner -LINK TO CCLEANER

Shell equality operators (=, ==, -eq)

It depends on the Test Construct around the operator. Your options are double parentheses, double brackets, single brackets, or test.

If you use (()), you are testing arithmetic equality with == as in C:

$ (( 1==1 )); echo $?
0
$ (( 1==2 )); echo $?
1

(Note: 0 means true in the Unix sense and a failed test results in a non-zero number.)

Using -eq inside of double parentheses is a syntax error.

If you are using [] (or single brackets) or [[]] (or double brackets), or test you can use one of -eq, -ne, -lt, -le, -gt, or -ge as an arithmetic comparison.

$ [ 1 -eq 1 ]; echo $?
0
$ [ 1 -eq 2 ]; echo $?
1
$ test 1 -eq 1; echo $?
0

The == inside of single or double brackets (or the test command) is one of the string comparison operators:

$ [[ "abc" == "abc" ]]; echo $?
0
$ [[ "abc" == "ABC" ]]; echo $?
1

As a string operator, = is equivalent to ==. Also, note the whitespace around = or ==: it’s required.

While you can do [[ 1 == 1 ]] or [[ $(( 1+1 )) == 2 ]] it is testing the string equality — not the arithmetic equality.

So -eq produces the result probably expected that the integer value of 1+1 is equal to 2 even though the right-hand side is a string and has a trailing space:

$ [[ $(( 1+1 )) -eq  "2 " ]]; echo $?
0

While a string comparison of the same picks up the trailing space and therefore the string comparison fails:

$ [[ $(( 1+1 )) == "2 " ]]; echo $?
1

And a mistaken string comparison can produce a completely wrong answer. 10 is lexicographically less than 2, so a string comparison returns true or 0. So many are bitten by this bug:

$ [[ 10 < 2 ]]; echo $?
0

The correct test for 10 being arithmetically less than 2 is this:

$ [[ 10 -lt 2 ]]; echo $?
1

In comments, there is a question about the technical reason why using the integer -eq on strings returns true for strings that are not the same:

$ [[ "yes" -eq "no" ]]; echo $?
0

The reason is that Bash is untyped. The -eq causes the strings to be interpreted as integers if possible including base conversion:

$ [[ "0x10" -eq 16 ]]; echo $?
0
$ [[ "010" -eq 8 ]]; echo $?
0
$ [[ "100" -eq 100 ]]; echo $?
0

And 0 if Bash thinks it is just a string:

$ [[ "yes" -eq 0 ]]; echo $?
0
$ [[ "yes" -eq 1 ]]; echo $?
1

So [[ "yes" -eq "no" ]] is equivalent to [[ 0 -eq 0 ]]


Last note: Many of the Bash specific extensions to the Test Constructs are not POSIX and therefore may fail in other shells. Other shells generally do not support [[...]] and ((...)) or ==.

Print page numbers on pages when printing html

As @page with pagenumbers don't work in browsers for now I was looking for alternatives.
I've found an answer posted by Oliver Kohll.
I'll repost it here so everyone could find it more easily:
For this answer we are not using @page, which is a pure CSS answer, but work in FireFox 20+ versions. Here is the link of an example.
The CSS is:

#content {
    display: table;
}

#pageFooter {
    display: table-footer-group;
}

#pageFooter:after {
    counter-increment: page;
    content: counter(page);
}

And the HTML code is:

<div id="content">
  <div id="pageFooter">Page </div>
  multi-page content here...
</div>

This way you can customize your page number by editing parametrs to #pageFooter. My example:

#pageFooter:after {
    counter-increment: page;
    content:"Page " counter(page);
    left: 0; 
    top: 100%;
    white-space: nowrap; 
    z-index: 20;
    -moz-border-radius: 5px; 
    -moz-box-shadow: 0px 0px 4px #222;  
    background-image: -moz-linear-gradient(top, #eeeeee, #cccccc);  
  }

This trick worked for me fine. Hope it will help you.

How to sum up elements of a C++ vector?

#include<boost/range/numeric.hpp>
int sum = boost::accumulate(vector, 0);

"Failed to install the following Android SDK packages as some licences have not been accepted" error

This works for me:

yes | ./sdkmanager "platforms;android-28"

yes | ./sdkmanager "build-tools;28.0.3"

yes | ./sdkmanager --licenses

Why do we need to install gulp globally and locally?

Just because I haven't seen it here, if you are on MacOS or Linux, I suggest you add this to your PATH (in your bashrc etc):

node_modules/.bin

With this relative path entry, if you are sitting in the root folder of any node project, you can run any command line tool (eslint, gulp, etc. etc.) without worrying about "global installs" or npm run etc.

Once I did this, I've never installed a module globally.

Catch multiple exceptions in one line (except block)

How do I catch multiple exceptions in one line (except block)

Do this:

try:
    may_raise_specific_errors():
except (SpecificErrorOne, SpecificErrorTwo) as error:
    handle(error) # might log or have some other default behavior...

The parentheses are required due to older syntax that used the commas to assign the error object to a name. The as keyword is used for the assignment. You can use any name for the error object, I prefer error personally.

Best Practice

To do this in a manner currently and forward compatible with Python, you need to separate the Exceptions with commas and wrap them with parentheses to differentiate from earlier syntax that assigned the exception instance to a variable name by following the Exception type to be caught with a comma.

Here's an example of simple usage:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError): # the parens are necessary
    sys.exit(0)

I'm specifying only these exceptions to avoid hiding bugs, which if I encounter I expect the full stack trace from.

This is documented here: https://docs.python.org/tutorial/errors.html

You can assign the exception to a variable, (e is common, but you might prefer a more verbose variable if you have long exception handling or your IDE only highlights selections larger than that, as mine does.) The instance has an args attribute. Here is an example:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError) as err: 
    print(err)
    print(err.args)
    sys.exit(0)

Note that in Python 3, the err object falls out of scope when the except block is concluded.

Deprecated

You may see code that assigns the error with a comma. This usage, the only form available in Python 2.5 and earlier, is deprecated, and if you wish your code to be forward compatible in Python 3, you should update the syntax to use the new form:

import sys

try:
    mainstuff()
except (KeyboardInterrupt, EOFError), err: # don't do this in Python 2.6+
    print err
    print err.args
    sys.exit(0)

If you see the comma name assignment in your codebase, and you're using Python 2.5 or higher, switch to the new way of doing it so your code remains compatible when you upgrade.

The suppress context manager

The accepted answer is really 4 lines of code, minimum:

try:
    do_something()
except (IDontLikeYouException, YouAreBeingMeanException) as e:
    pass

The try, except, pass lines can be handled in a single line with the suppress context manager, available in Python 3.4:

from contextlib import suppress

with suppress(IDontLikeYouException, YouAreBeingMeanException):
     do_something()

So when you want to pass on certain exceptions, use suppress.

MySql Table Insert if not exist otherwise update

Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE.

Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES() function to make sure the proper values are used when updating the other columns.

Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE syntax for MySQL:

INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE 
  Timestamp=VALUES(Timestamp)

How do I create a master branch in a bare Git repository?

A branch is just a reference to a commit. Until you commit anything to the repository, you don't have any branches. You can see this in a non-bare repository as well.

$ mkdir repo
$ cd repo
$ git init
Initialized empty Git repository in /home/me/repo/.git/
$ git branch
$ touch foo
$ git add foo
$ git commit -m "new file"
1 file changed, 0 insertions(+), 0 deletions(-)
create mode 100644 foo
$ git branch
* master

XML element with attribute and content using JAXB

Annotate type and gender properties with @XmlAttribute and the description property with @XmlValue:

package org.example.sport;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Sport {

    @XmlAttribute
    protected String type;

    @XmlAttribute
    protected String gender;

    @XmlValue;
    protected String description;

}

For More Information

Why do people write #!/usr/bin/env python on the first line of a Python script?

The exec system call of the Linux kernel understands shebangs (#!) natively

When you do on bash:

./something

on Linux, this calls the exec system call with the path ./something.

This line of the kernel gets called on the file passed to exec: https://github.com/torvalds/linux/blob/v4.8/fs/binfmt_script.c#L25

if ((bprm->buf[0] != '#') || (bprm->buf[1] != '!'))

It reads the very first bytes of the file, and compares them to #!.

If the comparison is true, then the rest of the line is parsed by the Linux kernel, which makes another exec call with:

  • executable: /usr/bin/env
  • first argument: python
  • second argument: script path

therefore equivalent to:

/usr/bin/env python /path/to/script.py

env is an executable that searches PATH to e.g. find /usr/bin/python, and then finally calls:

/usr/bin/python /path/to/script.py

The Python interpreter does see the #! line in the file, but # is the comment character in Python, so that line just gets ignored as a regular comment.

And yes, you can make an infinite loop with:

printf '#!/a\n' | sudo tee /a
sudo chmod +x /a
/a

Bash recognizes the error:

-bash: /a: /a: bad interpreter: Too many levels of symbolic links

#! just happens to be human readable, but that is not required.

If the file started with different bytes, then the exec system call would use a different handler. The other most important built-in handler is for ELF executable files: https://github.com/torvalds/linux/blob/v4.8/fs/binfmt_elf.c#L1305 which checks for bytes 7f 45 4c 46 (which also happens to be human readable for .ELF). Let's confirm that by reading the 4 first bytes of /bin/ls, which is an ELF executable:

head -c 4 "$(which ls)" | hd 

output:

00000000  7f 45 4c 46                                       |.ELF|
00000004                                                                 

So when the kernel sees those bytes, it takes the ELF file, puts it into memory correctly, and starts a new process with it. See also: How does kernel get an executable binary file running under linux?

Finally, you can add your own shebang handlers with the binfmt_misc mechanism. For example, you can add a custom handler for .jar files. This mechanism even supports handlers by file extension. Another application is to transparently run executables of a different architecture with QEMU.

I don't think POSIX specifies shebangs however: https://unix.stackexchange.com/a/346214/32558 , although it does mention in on rationale sections, and in the form "if executable scripts are supported by the system something may happen". macOS and FreeBSD also seem to implement it however.

PATH search motivation

Likely, one big motivation for the existence of shebangs is the fact that in Linux, we often want to run commands from PATH just as:

basename-of-command

instead of:

/full/path/to/basename-of-command

But then, without the shebang mechanism, how would Linux know how to launch each type of file?

Hardcoding the extension in commands:

 basename-of-command.py

or implementing PATH search on every interpreter:

python basename-of-command

would be a possibility, but this has the major problem that everything breaks if we ever decide to refactor the command into another language.

Shebangs solve this problem beautifully.

Assign pandas dataframe column dtypes

For those coming from Google (etc.) such as myself:

convert_objects has been deprecated since 0.17 - if you use it, you get a warning like this one:

FutureWarning: convert_objects is deprecated.  Use the data-type specific converters 
pd.to_datetime, pd.to_timedelta and pd.to_numeric.

You should do something like the following:

Converting NSData to NSString in Objective c

-[NSString initWithData:encoding] is your friend but only when you use a proper encoding.

Get list of databases from SQL Server

Execute:

SELECT name FROM master.sys.databases

This the preferred approach now, rather than dbo.sysdatabases, which has been deprecated for some time.


Execute this query:

SELECT name FROM master.dbo.sysdatabases

or if you prefer

EXEC sp_databases

Is there a program to decompile Delphi?

You can use IDR it is a great program to decompile Delphi, it is updated to the current Delphi versions and it has a lot of features.

Enable the display of line numbers in Visual Studio

Type 'line numbers' into the Quick Launch textbox (top right VS 2015), and it'll take you right where you need to be (tick Line Numbers checkbox).

What is the best way to connect and use a sqlite database from C#

Another way of using SQLite database in NET Framework is to use Fluent-NHibernate.
[It is NET module which wraps around NHibernate (ORM module - Object Relational Mapping) and allows to configure NHibernate programmatically (without XML files) with the fluent pattern.]

Here is the brief 'Getting started' description how to do this in C# step by step:

https://github.com/jagregory/fluent-nhibernate/wiki/Getting-started

It includes a source code as an Visual Studio project.

Generating matplotlib graphs without a running X server

@Neil's answer is one (perfectly valid!) way of doing it, but you can also simply call matplotlib.use('Agg') before importing matplotlib.pyplot, and then continue as normal.

E.g.

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
fig.savefig('temp.png')

You don't have to use the Agg backend, as well. The pdf, ps, svg, agg, cairo, and gdk backends can all be used without an X-server. However, only the Agg backend will be built by default (I think?), so there's a good chance that the other backends may not be enabled on your particular install.

Alternately, you can just set the backend parameter in your .matplotlibrc file to automatically have matplotlib.pyplot use the given renderer.

how to attach url link to an image?

"How to attach url link to an image?"

You do it like this:

<a href="http://www.google.com"><img src="http://www.google.com/intl/en_ALL/images/logo.gif"/></a>

See it in action.

What is the meaning of single and double underscore before an object name?

Getting the facts of _ and __ is pretty easy; the other answers express them pretty well. The usage is much harder to determine.

This is how I see it:

_

Should be used to indicate that a function is not for public use as for example an API. This and the import restriction make it behave much like internal in c#.

__

Should be used to avoid name collision in the inheritace hirarchy and to avoid latebinding. Much like private in c#.

==>

If you want to indicate that something is not for public use, but it should act like protected use _. If you want to indicate that something is not for public use, but it should act like private use __.

This is also a quote that I like very much:

The problem is that the author of a class may legitimately think "this attribute/method name should be private, only accessible from within this class definition" and use the __private convention. But later on, a user of that class may make a subclass that legitimately needs access to that name. So either the superclass has to be modified (which may be difficult or impossible), or the subclass code has to use manually mangled names (which is ugly and fragile at best).

But the problem with that is in my opinion that if there's no IDE that warns you when you override methods, finding the error might take you a while if you have accidentially overriden a method from a base-class.

Ambiguous overload call to abs(double)

Its boils down to this: math.h is from C and was created over 10 years ago. In math.h, due to its primitive nature, the abs() function is "essentially" just for integer types and if you wanted to get the absolute value of a double, you had to use fabs(). When C++ was created it took math.h and made it cmath. cmath is essentially math.h but improved for C++. It improved things like having to distinguish between fabs() and abs, and just made abs() for both doubles and integer types. In summary either: Use math.h and use abs() for integers, fabs() for doubles or use cmath and just have abs for everything (easier and recommended)

Hope this helps anyone who is having the same problem!

Populate dropdown select with array using jQuery

The solution I used was to create a javascript function that uses jquery:

This will populate a dropdown object on the HTML page. Please let me know where this can be optimized - but works fine as is.

function util_PopulateDropDownListAndSelect(sourceListObject, sourceListTextFieldName, targetDropDownName, valueToSelect)
{
    var options = '';

    // Create the list of HTML Options
    for (i = 0; i < sourceListObject.List.length; i++)
    {
        options += "<option value='" + sourceListObject.List[i][sourceListTextFieldName] + "'>" + sourceListObject.List[i][sourceListTextFieldName] + "</option>\r\n";
    }

    // Assign the options to the HTML Select container
    $('select#' + targetDropDownName)[0].innerHTML = options;

    // Set the option to be Selected
    $('#' + targetDropDownName).val(valueToSelect);

    // Refresh the HTML Select so it displays the Selected option
    $('#' + targetDropDownName).selectmenu('refresh')
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Calling Oracle stored procedure from C#?

Please visit this ODP site set up by oracle for Microsoft OracleClient Developers: http://www.oracle.com/technetwork/topics/dotnet/index-085703.html

Also below is a sample code that can get you started to call a stored procedure from C# to Oracle. PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT is the stored procedure built on Oracle accepting parameters PUNIT, POFFICE, PRECEIPT_NBR and returning the result in T_CURSOR.

using Oracle.DataAccess;
using Oracle.DataAccess.Client;

public DataTable GetHeader_BySproc(string unit, string office, string receiptno)
{
    using (OracleConnection cn = new OracleConnection(DatabaseHelper.GetConnectionString()))
    {
        OracleDataAdapter da = new OracleDataAdapter();
        OracleCommand cmd = new OracleCommand();
        cmd.Connection = cn;
        cmd.InitialLONGFetchSize = 1000;
        cmd.CommandText = DatabaseHelper.GetDBOwner() + "PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("PUNIT", OracleDbType.Char).Value = unit;
        cmd.Parameters.Add("POFFICE", OracleDbType.Char).Value = office;
        cmd.Parameters.Add("PRECEIPT_NBR", OracleDbType.Int32).Value = receiptno;
        cmd.Parameters.Add("T_CURSOR", OracleDbType.RefCursor).Direction = ParameterDirection.Output;

        da.SelectCommand = cmd;
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }
}

Converting List<String> to String[] in Java

I've designed and implemented Dollar for this kind of tasks:

String[] strarray= $(strlist).toArray();

Set variable with multiple values and use IN

You need a table variable:

declare @values table
(
    Value varchar(1000)
)

insert into @values values ('A')
insert into @values values ('B')
insert into @values values ('C')

select blah
from foo
where myField in (select value from @values)

Speed tradeoff of Java's -Xms and -Xmx options

I have found that in some cases too much memory can slow the program down.

For example I had a hibernate based transform engine that started running slowly as the load increased. It turned out that each time we got an object from the db, hibernate was checking memory for objects that would never be used again.

The solution was to evict the old objects from the session.

Stuart

Failed to decode downloaded font

I was having the same issue with font awesome v4.4 and I fixed it by removing the woff2 format. I was getting a warning in Chrome only.

@font-face {
  font-family: 'FontAwesome';
  src: url('../fonts/fontawesome-webfont.eot?v=4.4.0');
  src: url('../fonts/fontawesome-webfont.eot?#iefix&v=4.4.0') format('embedded-opentype'), url('../fonts/fontawesome-webfont.woff?v=4.4.0') format('woff'), url('../fonts/fontawesome-webfont.ttf?v=4.4.0') format('truetype'), url('../fonts/fontawesome-webfont.svg?v=4.4.0#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

jquery.ajax Access-Control-Allow-Origin

At my work we have our restful services on a different port number and the data resides in db2 on a pair of AS400s. We typically use the $.getJSON AJAX method because it easily returns JSONP using the ?callback=? without having any issues with CORS.

data ='USER=<?echo trim($USER)?>' +
         '&QRYTYPE=' + $("input[name=QRYTYPE]:checked").val();

        //Call the REST program/method returns: JSONP 
        $.getJSON( "http://www.stackoverflow.com/rest/resttest?callback=?",data)
        .done(function( json ) {        

              //  loading...
                if ($.trim(json.ERROR) != '') {
                    $("#error-msg").text(message).show();
                }
                else{
                    $(".error").hide();
                    $("#jsonp").text(json.whatever);

                }

        })  
        .fail(function( jqXHR, textStatus, error ) {
        var err = textStatus + ", " + error;
        alert('Unable to Connect to Server.\n Try again Later.\n Request Failed: ' + err);
        });     

How to get numeric position of alphabets in java?

Convert each character to its ASCII code, subtract the ASCII code for "a" and add 1. I'm deliberately leaving the code as an exercise.

This sounds like homework. If so, please tag it as such.

Also, this won't deal with upper case letters, since you didn't state any requirement to handle them, but if you need to then just lowercase the string before you start.

Oh, and this will only deal with the latin "a" through "z" characters without any accents, etc.

Echo a blank (empty) line to the console from a Windows batch file

There is often the tip to use 'echo.'

But that is slow, and it could fail with an error message, as cmd.exe will search first for a file named 'echo' (without extension) and only when the file doesn't exists it outputs an empty line.

You could use echo(. This is approximately 20 times faster, and it works always. The only drawback could be that it looks odd.

More about the different ECHO:/\ variants is at DOS tips: ECHO. FAILS to give text or blank line.

How Do I Take a Screen Shot of a UIView?

you can use following UIView category -

@implementation UIView (SnapShot)

 - (UIImage *)snapshotImage
{
    UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);        
    [self drawViewHierarchyInRect:self.bounds afterScreenUpdates:NO];        
    // old style [self.layer renderInContext:UIGraphicsGetCurrentContext()];        
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();        
    UIGraphicsEndImageContext();        
    return image;
}    
@end

How to show Snackbar when Activity starts?

A utils function for show snack bar

fun showSnackBar(activity: Activity, message: String, action: String? = null,
    actionListener: View.OnClickListener? = null, duration: Int = Snackbar.LENGTH_SHORT) {
    val snackBar = Snackbar.make(activity.findViewById(android.R.id.content), message, duration)
        .setBackgroundColor(Color.parseColor("#CC000000")) // todo update your color
        .setTextColor(Color.WHITE)
    if (action != null && actionListener!=null) {
        snackBar.setAction(action, actionListener)
    }
    snackBar.show()
}

Example using in Activity

  showSnackBar(this, "No internet")
  showSnackBar(this, "No internet", duration = Snackbar.LENGTH_LONG)
  showSnackBar(activity, "No internet", "OK", View.OnClickListener { 
       // handle click 
  })

Example using in Fragment

  showSnackBar(getActivity(), "No internet")

Hope it help

Read from a gzip file in python

python: read lines from compressed text files

Using gzip.GzipFile:

import gzip

with gzip.open('input.gz','r') as fin:        
    for line in fin:        
        print('got line', line)

How to convert timestamps to dates in Bash?

some example:

$ date
Tue Mar 22 16:47:06 CST 2016

$ date -d "Tue Mar 22 16:47:06 CST 2016" "+%s"
1458636426

$ date +%s
1458636453

$ date -d @1458636426
Tue Mar 22 16:47:06 CST 2016

$ date --date='@1458636426'
Tue Mar 22 16:47:06 CST 2016


String concatenation in Jinja

If stuffs is a list of strings, just this would work:

{{ stuffs|join(", ") }}

Link to join filter documentation, link to filters in general documentation.

p.s.

More reader friendly way {{ my ~ ', ' ~ string }}

Linking a qtDesigner .ui file to python/pyqt?

In order to compile .ui files to .py files, I did:

python pyuic.py form1.ui > form1.py

Att.

Command copy exited with code 4 when building - Visual Studio restart solves it

I don't see anything in here to suggest that this is a web-app but I have experienced this issue myself - I've got two xcopy commands on a post-build event and only one of them was failing. Something had a lock on the file, and it wasn't Visual Studio (as I tried restarting it.)

The only other thing that would have used the dll I built was IIS. And lo and behold,

A simple iisreset did the trick for me.

The Definitive C Book Guide and List

Beginner

Introductory, no previous programming experience

  • C++ Primer * (Stanley Lippman, Josée Lajoie, and Barbara E. Moo) (updated for C++11) Coming at 1k pages, this is a very thorough introduction into C++ that covers just about everything in the language in a very accessible format and in great detail. The fifth edition (released August 16, 2012) covers C++11. [Review]

    * Not to be confused with C++ Primer Plus (Stephen Prata), with a significantly less favorable review.

  • Programming: Principles and Practice Using C++ (Bjarne Stroustrup, 2nd Edition - May 25, 2014) (updated for C++11/C++14) An introduction to programming using C++ by the creator of the language. A good read, that assumes no previous programming experience, but is not only for beginners.

Introductory, with previous programming experience

  • A Tour of C++ (Bjarne Stroustrup) (2nd edition for C++17) The “tour” is a quick (about 180 pages and 14 chapters) tutorial overview of all of standard C++ (language and standard library, and using C++11) at a moderately high level for people who already know C++ or at least are experienced programmers. This book is an extended version of the material that constitutes Chapters 2-5 of The C++ Programming Language, 4th edition.

  • Accelerated C++ (Andrew Koenig and Barbara Moo, 1st Edition - August 24, 2000) This basically covers the same ground as the C++ Primer, but does so on a fourth of its space. This is largely because it does not attempt to be an introduction to programming, but an introduction to C++ for people who've previously programmed in some other language. It has a steeper learning curve, but, for those who can cope with this, it is a very compact introduction to the language. (Historically, it broke new ground by being the first beginner's book to use a modern approach to teaching the language.) Despite this, the C++ it teaches is purely C++98. [Review]

Best practices

  • Effective C++ (Scott Meyers, 3rd Edition - May 22, 2005) This was written with the aim of being the best second book C++ programmers should read, and it succeeded. Earlier editions were aimed at programmers coming from C, the third edition changes this and targets programmers coming from languages like Java. It presents ~50 easy-to-remember rules of thumb along with their rationale in a very accessible (and enjoyable) style. For C++11 and C++14 the examples and a few issues are outdated and Effective Modern C++ should be preferred. [Review]

  • Effective Modern C++ (Scott Meyers) This is basically the new version of Effective C++, aimed at C++ programmers making the transition from C++03 to C++11 and C++14.

  • Effective STL (Scott Meyers) This aims to do the same to the part of the standard library coming from the STL what Effective C++ did to the language as a whole: It presents rules of thumb along with their rationale. [Review]


Intermediate

  • More Effective C++ (Scott Meyers) Even more rules of thumb than Effective C++. Not as important as the ones in the first book, but still good to know.

  • Exceptional C++ (Herb Sutter) Presented as a set of puzzles, this has one of the best and thorough discussions of the proper resource management and exception safety in C++ through Resource Acquisition is Initialization (RAII) in addition to in-depth coverage of a variety of other topics including the pimpl idiom, name lookup, good class design, and the C++ memory model. [Review]

  • More Exceptional C++ (Herb Sutter) Covers additional exception safety topics not covered in Exceptional C++, in addition to discussion of effective object-oriented programming in C++ and correct use of the STL. [Review]

  • Exceptional C++ Style (Herb Sutter) Discusses generic programming, optimization, and resource management; this book also has an excellent exposition of how to write modular code in C++ by using non-member functions and the single responsibility principle. [Review]

  • C++ Coding Standards (Herb Sutter and Andrei Alexandrescu) “Coding standards” here doesn't mean “how many spaces should I indent my code?” This book contains 101 best practices, idioms, and common pitfalls that can help you to write correct, understandable, and efficient C++ code. [Review]

  • C++ Templates: The Complete Guide (David Vandevoorde and Nicolai M. Josuttis) This is the book about templates as they existed before C++11. It covers everything from the very basics to some of the most advanced template metaprogramming and explains every detail of how templates work (both conceptually and at how they are implemented) and discusses many common pitfalls. Has excellent summaries of the One Definition Rule (ODR) and overload resolution in the appendices. A second edition covering C++11, C++14 and C++17 has been already published. [Review]

  • C++ 17 - The Complete Guide (Nicolai M. Josuttis) This book describes all the new features introduced in the C++17 Standard covering everything from the simple ones like 'Inline Variables', 'constexpr if' all the way up to 'Polymorphic Memory Resources' and 'New and Delete with overaligned Data'. [Review]

  • C++ in Action (Bartosz Milewski). This book explains C++ and its features by building an application from ground up. [Review]

  • Functional Programming in C++ (Ivan Cukic). This book introduces functional programming techniques to modern C++ (C++11 and later). A very nice read for those who want to apply functional programming paradigms to C++.

  • Professional C++ (Marc Gregoire, 5th Edition - Feb 2021) Provides a comprehensive and detailed tour of the C++ language implementation replete with professional tips and concise but informative in-text examples, emphasizing C++20 features. Uses C++20 features, such as modules and std::format throughout all examples.


Advanced

  • Modern C++ Design (Andrei Alexandrescu) A groundbreaking book on advanced generic programming techniques. Introduces policy-based design, type lists, and fundamental generic programming idioms then explains how many useful design patterns (including small object allocators, functors, factories, visitors, and multi-methods) can be implemented efficiently, modularly, and cleanly using generic programming. [Review]

  • C++ Template Metaprogramming (David Abrahams and Aleksey Gurtovoy)

  • C++ Concurrency In Action (Anthony Williams) A book covering C++11 concurrency support including the thread library, the atomics library, the C++ memory model, locks and mutexes, as well as issues of designing and debugging multithreaded applications. A second edition covering C++14 and C++17 has been already published. [Review]

  • Advanced C++ Metaprogramming (Davide Di Gennaro) A pre-C++11 manual of TMP techniques, focused more on practice than theory. There are a ton of snippets in this book, some of which are made obsolete by type traits, but the techniques, are nonetheless useful to know. If you can put up with the quirky formatting/editing, it is easier to read than Alexandrescu, and arguably, more rewarding. For more experienced developers, there is a good chance that you may pick up something about a dark corner of C++ (a quirk) that usually only comes about through extensive experience.


Reference Style - All Levels

  • The C++ Programming Language (Bjarne Stroustrup) (updated for C++11) The classic introduction to C++ by its creator. Written to parallel the classic K&R, this indeed reads very much like it and covers just about everything from the core language to the standard library, to programming paradigms to the language's philosophy. [Review] Note: All releases of the C++ standard are tracked in the question "Where do I find the current C or C++ standard documents?".

  • C++ Standard Library Tutorial and Reference (Nicolai Josuttis) (updated for C++11) The introduction and reference for the C++ Standard Library. The second edition (released on April 9, 2012) covers C++11. [Review]

  • The C++ IO Streams and Locales (Angelika Langer and Klaus Kreft) There's very little to say about this book except that, if you want to know anything about streams and locales, then this is the one place to find definitive answers. [Review]

C++11/14/17/… References:

  • The C++11/14/17 Standard (INCITS/ISO/IEC 14882:2011/2014/2017) This, of course, is the final arbiter of all that is or isn't C++. Be aware, however, that it is intended purely as a reference for experienced users willing to devote considerable time and effort to its understanding. The C++17 standard is released in electronic form for 198 Swiss Francs.

  • The C++17 standard is available, but seemingly not in an economical form – directly from the ISO it costs 198 Swiss Francs (about $200 US). For most people, the final draft before standardization is more than adequate (and free). Many will prefer an even newer draft, documenting new features that are likely to be included in C++20.

  • Overview of the New C++ (C++11/14) (PDF only) (Scott Meyers) (updated for C++14) These are the presentation materials (slides and some lecture notes) of a three-day training course offered by Scott Meyers, who's a highly respected author on C++. Even though the list of items is short, the quality is high.

  • The C++ Core Guidelines (C++11/14/17/…) (edited by Bjarne Stroustrup and Herb Sutter) is an evolving online document consisting of a set of guidelines for using modern C++ well. The guidelines are focused on relatively higher-level issues, such as interfaces, resource management, memory management and concurrency affecting application architecture and library design. The project was announced at CppCon'15 by Bjarne Stroustrup and others and welcomes contributions from the community. Most guidelines are supplemented with a rationale and examples as well as discussions of possible tool support. Many rules are designed specifically to be automatically checkable by static analysis tools.

  • The C++ Super-FAQ (Marshall Cline, Bjarne Stroustrup and others) is an effort by the Standard C++ Foundation to unify the C++ FAQs previously maintained individually by Marshall Cline and Bjarne Stroustrup and also incorporating new contributions. The items mostly address issues at an intermediate level and are often written with a humorous tone. Not all items might be fully up to date with the latest edition of the C++ standard yet.

  • cppreference.com (C++03/11/14/17/…) (initiated by Nate Kohl) is a wiki that summarizes the basic core-language features and has extensive documentation of the C++ standard library. The documentation is very precise but is easier to read than the official standard document and provides better navigation due to its wiki nature. The project documents all versions of the C++ standard and the site allows filtering the display for a specific version. The project was presented by Nate Kohl at CppCon'14.


Classics / Older

Note: Some information contained within these books may not be up-to-date or no longer considered best practice.

  • The Design and Evolution of C++ (Bjarne Stroustrup) If you want to know why the language is the way it is, this book is where you find answers. This covers everything before the standardization of C++.

  • Ruminations on C++ - (Andrew Koenig and Barbara Moo) [Review]

  • Advanced C++ Programming Styles and Idioms (James Coplien) A predecessor of the pattern movement, it describes many C++-specific “idioms”. It's certainly a very good book and might still be worth a read if you can spare the time, but quite old and not up-to-date with current C++.

  • Large Scale C++ Software Design (John Lakos) Lakos explains techniques to manage very big C++ software projects. Certainly, a good read, if it only was up to date. It was written long before C++ 98 and misses on many features (e.g. namespaces) important for large-scale projects. If you need to work in a big C++ software project, you might want to read it, although you need to take more than a grain of salt with it. The first volume of a new edition is released in 2019.

  • Inside the C++ Object Model (Stanley Lippman) If you want to know how virtual member functions are commonly implemented and how base objects are commonly laid out in memory in a multi-inheritance scenario, and how all this affects performance, this is where you will find thorough discussions of such topics.

  • The Annotated C++ Reference Manual (Bjarne Stroustrup, Margaret A. Ellis) This book is quite outdated in the fact that it explores the 1989 C++ 2.0 version - Templates, exceptions, namespaces and new casts were not yet introduced. Saying that however, this book goes through the entire C++ standard of the time explaining the rationale, the possible implementations, and features of the language. This is not a book to learn programming principles and patterns on C++, but to understand every aspect of the C++ language.

  • Thinking in C++ (Bruce Eckel, 2nd Edition, 2000). Two volumes; is a tutorial style free set of intro level books. Downloads: vol 1, vol 2. Unfortunately they're marred by a number of trivial errors (e.g. maintaining that temporaries are automatically const), with no official errata list. A partial 3rd party errata list is available at http://www.computersciencelab.com/Eckel.htm, but it is apparently not maintained.

  • Scientific and Engineering C++: An Introduction to Advanced Techniques and Examples (John Barton and Lee Nackman) It is a comprehensive and very detailed book that tried to explain and make use of all the features available in C++, in the context of numerical methods. It introduced at the time several new techniques, such as the Curiously Recurring Template Pattern (CRTP, also called Barton-Nackman trick). It pioneered several techniques such as dimensional analysis and automatic differentiation. It came with a lot of compilable and useful code, ranging from an expression parser to a Lapack wrapper. The code is still available online. Unfortunately, the books have become somewhat outdated in the style and C++ features, however, it was an incredible tour-de-force at the time (1994, pre-STL). The chapters on dynamics inheritance are a bit complicated to understand and not very useful. An updated version of this classic book that includes move semantics and the lessons learned from the STL would be very nice.

log4net hierarchy and logging levels

For most applications you would like to set a minimum level but not a maximum level.

For example, when debugging your code set the minimum level to DEBUG, and in production set it to WARN.

Create Directory if it doesn't exist with Ruby

Simple way:

directory_name = "name"
Dir.mkdir(directory_name) unless File.exists?(directory_name)

?: ?? Operators Instead Of IF|ELSE

the ?: is the itinerary operator. (believe i spelled that properly) and it's simple to use. as in a boolean predicate ? iftrue : ifalse; But you must have a rvalue/lvalue as in rvalue = predicate ? iftrue: iffalse;

ex int i = x < 7 ? x : 7;

if x was less than 7, i would get assigned x, if not i would be 7.

you can also use it in a return, as in return x < 7 ? x : 7;

again, as above , this would have the same affect.

so, Source = Source == value ? Source : string.Empty; i believe is what your trying to acheive.

Calculate difference between 2 date / times in Oracle SQL

This will count time between to dates:

SELECT
  (TO_CHAR( TRUNC (ROUND(((sysdate+1) - sysdate)*24,2))*60,'999999')
  +
  TO_CHAR(((((sysdate+1)-sysdate)*24)- TRUNC(ROUND(((sysdate+1) - sysdate)*24,2)))/100*60 *100, '09'))/60
FROM dual

Python and JSON - TypeError list indices must be integers not str

You can simplify your code down to

url = "http://worldcup.kimonolabs.com/api/players?apikey=xxx"
json_obj = urllib2.urlopen(url).read
player_json_list = json.loads(json_obj)
for player in readable_json_list:
    print player['firstName']

You were trying to access a list element using dictionary syntax. the equivalent of

foo = [1, 2, 3, 4]
foo["1"]

It can be confusing when you have lists of dictionaries and keeping the nesting in order.

Padding between ActionBar's home icon and title

I used AppBarLayout and custom ImageButton do to so.

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:elevation="0dp"
    android:background="@android:color/transparent"
    android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

   <RelativeLayout
       android:layout_width="match_parent"
       android:layout_height="match_parent">

       <ImageView
           android:layout_width="32dp"
           android:layout_height="32dp"
           android:src="@drawable/selector_back_button"
           android:layout_centerVertical="true"
           android:layout_marginLeft="8dp"
           android:id="@+id/back_button"/>

       <android.support.v7.widget.Toolbar
           android:id="@+id/toolbar"
           android:layout_width="match_parent"
           android:layout_height="?attr/actionBarSize"
           app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    </RelativeLayout>    
</android.support.design.widget.AppBarLayout>

My Java code:

findViewById(R.id.appbar).bringToFront();
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
final ActionBar ab = getSupportActionBar();
getSupportActionBar().setDisplayShowTitleEnabled(false);

Parameter "stratify" from method "train_test_split" (scikit Learn)

In this context, stratification means that the train_test_split method returns training and test subsets that have the same proportions of class labels as the input dataset.

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

It is common to use the MAC address is associated with the network card.

The address is available in Java 6 through through the following API:

Java 6 Docs for Hardware Address

I haven't used it in Java, but for other network identification applications it has been helpful.

Access a function variable outside the function without using "global"

You could do something along this lines:

def static_example():
   if not hasattr(static_example, "static_var"):
       static_example.static_var = 0
   static_example.static_var += 1
   return static_example.static_var

print static_example()
print static_example()
print static_example()

Get UTC time in seconds

I believe +%s is seconds since epoch. It's timezone invariant.

Querying Datatable with where condition

something like this ? :

DataTable dt = ...
DataView dv = new DataView(dt);
dv.RowFilter = "(EmpName != 'abc' or EmpName != 'xyz') and (EmpID = 5)"

Is it what you are searching for?

Call removeView() on the child's parent first

I was calling parentView.removeView(childView) and childView was still showing. I eventually realized that a method was somehow being triggered twice and added the childView to the parentView twice.

So, use parentView.getChildCount() to determine how many children the parent has before you add a view and afterwards. If the child is added too many times then the top most child is being removed and the copy childView remains-which looks like removeView is working even when it is.

Also, you shouldn't use View.GONE to remove a view. If it's truly removed then you won't need to hide it, otherwise it's still there and you're just hiding it from yourself :(

How to parse JSON with VBA without external libraries?

Call me simple but I just declared a Variant and split the responsetext from my REST GET on the quote comma quote between each item, then got the value I wanted by looking for the last quote with InStrRev. I'm sure that's not as elegant as some of the other suggestions but it works for me.

         varLines = Split(.responsetext, """,""")
        strType = Mid(varLines(8), InStrRev(varLines(8), """") + 1)

How to implement a SQL like 'LIKE' operator in java?

The Comparator and Comparable interfaces are likely inapplicable here. They deal with sorting, and return integers of either sign, or 0. Your operation is about finding matches, and returning true/false. That's different.

How to check if an object is a certain type

In VB.NET, you need to use the GetType method to retrieve the type of an instance of an object, and the GetType() operator to retrieve the type of another known type.

Once you have the two types, you can simply compare them using the Is operator.

So your code should actually be written like this:

Sub FillCategories(ByVal Obj As Object)
    Dim cmd As New SqlCommand("sp_Resources_Categories", Conn)
    cmd.CommandType = CommandType.StoredProcedure
    Obj.DataSource = cmd.ExecuteReader
    If Obj.GetType() Is GetType(System.Web.UI.WebControls.DropDownList) Then

    End If
    Obj.DataBind()
End Sub

You can also use the TypeOf operator instead of the GetType method. Note that this tests if your object is compatible with the given type, not that it is the same type. That would look like this:

If TypeOf Obj Is System.Web.UI.WebControls.DropDownList Then

End If

Totally trivial, irrelevant nitpick: Traditionally, the names of parameters are camelCased (which means they always start with a lower-case letter) when writing .NET code (either VB.NET or C#). This makes them easy to distinguish at a glance from classes, types, methods, etc.

How to check whether a string is a valid HTTP URL?

Uri uri = null;
if (!Uri.TryCreate(url, UriKind.Absolute, out uri) || null == uri)
    return false;
else
    return true;

Here url is the string you have to test.

HTML table headers always visible at top of window when viewing a large table

If you use a full screen table you are maybe interested in setting th to display:fixed; and top:0; or try a very similar approach via css.

Update

Just quickly build up a working solution with iframes (html4.0). This example IS NOT standard conform, however you will easily be able to fix it:

outer.html

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">   
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">     
    <head>      
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />   
        <title>Outer</title>
  <body>
    <iframe src="test.html" width="200" height="100"></iframe>
    </body>
</html> 

test.html

<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">   
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">     
    <head>      
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />   
        <title>Floating</title>
    <style type="text/css">
      .content{
        position:relative; 
      }

      thead{
        background-color:red;
        position:fixed; 
        top:0;
      }
    </style>
  <body>
    <div class="content">      
      <table>
        <thead>
          <tr class="top"><td>Title</td></tr>
        </head>
        <tbody>
          <tr><td>a</td></tr>
          <tr><td>b</td></tr>
          <tr><td>c</td></tr>
          <tr><td>d</td></tr>
          <tr><td>e</td></tr>
          <tr><td>e</td></tr>
          <tr><td>e</td></tr>
          <tr><td>e</td></tr>
          <tr><td>e</td></tr>
          <tr><td>e</td></tr>
        </tbody>
      </table>
    </div>
    </body>
</html> 

What is the color code for transparency in CSS?

There is no transparency component of the color hex string. There is opacity, which is a float from 0.0 to 1.0.

Built in Python hash() function

Most answers suggest this is because of different platforms, but there is more to it. From the documentation of object.__hash__(self):

By default, the __hash__() values of str, bytes and datetime objects are “salted” with an unpredictable random value. Although they remain constant within an individual Python process, they are not predictable between repeated invocations of Python.

This is intended to provide protection against a denial-of-service caused by carefully-chosen inputs that exploit the worst case performance of a dict insertion, O(n²) complexity. See http://www.ocert.org/advisories/ocert-2011-003.html for details.

Changing hash values affects the iteration order of dicts, sets and other mappings. Python has never made guarantees about this ordering (and it typically varies between 32-bit and 64-bit builds).

Even running on the same machine will yield varying results across invocations:

$ python -c "print(hash('http://stackoverflow.com'))"
-3455286212422042986
$ python -c "print(hash('http://stackoverflow.com'))"
-6940441840934557333

While:

$ python -c "print(hash((1,2,3)))"
2528502973977326415
$ python -c "print(hash((1,2,3)))"
2528502973977326415

See also the environment variable PYTHONHASHSEED:

If this variable is not set or set to random, a random value is used to seed the hashes of str, bytes and datetime objects.

If PYTHONHASHSEED is set to an integer value, it is used as a fixed seed for generating the hash() of the types covered by the hash randomization.

Its purpose is to allow repeatable hashing, such as for selftests for the interpreter itself, or to allow a cluster of python processes to share hash values.

The integer must be a decimal number in the range [0, 4294967295]. Specifying the value 0 will disable hash randomization.

For example:

$ export PYTHONHASHSEED=0                            
$ python -c "print(hash('http://stackoverflow.com'))"
-5843046192888932305
$ python -c "print(hash('http://stackoverflow.com'))"
-5843046192888932305

How to get text box value in JavaScript

If you are using any user control and want to get any text box values then you can use the below code:

var result = document.getElementById('LE_OtherCostsDetails_txtHomeOwnerInsurance').value;

Here, LE_OtherCostsDetails, is the name of the user control and txtHomeOwnerInsurance is the id of the text box.

how to bind datatable to datagridview in c#

for example we want to set a DataTable 'Users' to DataGridView by followig 2 steps : step 1 - get all Users by :

public DataTable  getAllUsers()
    {
        OracleConnection Connection = new OracleConnection(stringConnection);
        Connection.ConnectionString = stringConnection;
        Connection.Open();

        DataSet dataSet = new DataSet();

        OracleCommand cmd = new OracleCommand("semect * from Users");
        cmd.CommandType = CommandType.Text;
        cmd.Connection = Connection;

        using (OracleDataAdapter dataAdapter = new OracleDataAdapter())
        {
            dataAdapter.SelectCommand = cmd;
            dataAdapter.Fill(dataSet);
        }

        return dataSet.Tables[0];
    }

step 2- set the return result to DataGridView :

public void setTableToDgv(DataGridView DGV, DataTable table)
    {
        DGV.DataSource = table;
    }

using example:

    setTableToDgv(dgv_client,getAllUsers());

How to implement the Softmax function in Python

Here is generalized solution using numpy and comparision for correctness with tensorflow ans scipy:

Data preparation:

import numpy as np

np.random.seed(2019)

batch_size = 1
n_items = 3
n_classes = 2
logits_np = np.random.rand(batch_size,n_items,n_classes).astype(np.float32)
print('logits_np.shape', logits_np.shape)
print('logits_np:')
print(logits_np)

Output:

logits_np.shape (1, 3, 2)
logits_np:
[[[0.9034822  0.3930805 ]
  [0.62397    0.6378774 ]
  [0.88049906 0.299172  ]]]

Softmax using tensorflow:

import tensorflow as tf

logits_tf = tf.convert_to_tensor(logits_np, np.float32)
scores_tf = tf.nn.softmax(logits_np, axis=-1)

print('logits_tf.shape', logits_tf.shape)
print('scores_tf.shape', scores_tf.shape)

with tf.Session() as sess:
    scores_np = sess.run(scores_tf)

print('scores_np.shape', scores_np.shape)
print('scores_np:')
print(scores_np)

print('np.sum(scores_np, axis=-1).shape', np.sum(scores_np,axis=-1).shape)
print('np.sum(scores_np, axis=-1):')
print(np.sum(scores_np, axis=-1))

Output:

logits_tf.shape (1, 3, 2)
scores_tf.shape (1, 3, 2)
scores_np.shape (1, 3, 2)
scores_np:
[[[0.62490064 0.37509936]
  [0.4965232  0.5034768 ]
  [0.64137274 0.3586273 ]]]
np.sum(scores_np, axis=-1).shape (1, 3)
np.sum(scores_np, axis=-1):
[[1. 1. 1.]]

Softmax using scipy:

from scipy.special import softmax

scores_np = softmax(logits_np, axis=-1)

print('scores_np.shape', scores_np.shape)
print('scores_np:')
print(scores_np)

print('np.sum(scores_np, axis=-1).shape', np.sum(scores_np, axis=-1).shape)
print('np.sum(scores_np, axis=-1):')
print(np.sum(scores_np, axis=-1))

Output:

scores_np.shape (1, 3, 2)
scores_np:
[[[0.62490064 0.37509936]
  [0.4965232  0.5034768 ]
  [0.6413727  0.35862732]]]
np.sum(scores_np, axis=-1).shape (1, 3)
np.sum(scores_np, axis=-1):
[[1. 1. 1.]]

Softmax using numpy (https://nolanbconaway.github.io/blog/2017/softmax-numpy) :

def softmax(X, theta = 1.0, axis = None):
    """
    Compute the softmax of each element along an axis of X.

    Parameters
    ----------
    X: ND-Array. Probably should be floats.
    theta (optional): float parameter, used as a multiplier
        prior to exponentiation. Default = 1.0
    axis (optional): axis to compute values along. Default is the
        first non-singleton axis.

    Returns an array the same size as X. The result will sum to 1
    along the specified axis.
    """

    # make X at least 2d
    y = np.atleast_2d(X)

    # find axis
    if axis is None:
        axis = next(j[0] for j in enumerate(y.shape) if j[1] > 1)

    # multiply y against the theta parameter,
    y = y * float(theta)

    # subtract the max for numerical stability
    y = y - np.expand_dims(np.max(y, axis = axis), axis)

    # exponentiate y
    y = np.exp(y)

    # take the sum along the specified axis
    ax_sum = np.expand_dims(np.sum(y, axis = axis), axis)

    # finally: divide elementwise
    p = y / ax_sum

    # flatten if X was 1D
    if len(X.shape) == 1: p = p.flatten()

    return p


scores_np = softmax(logits_np, axis=-1)

print('scores_np.shape', scores_np.shape)
print('scores_np:')
print(scores_np)

print('np.sum(scores_np, axis=-1).shape', np.sum(scores_np, axis=-1).shape)
print('np.sum(scores_np, axis=-1):')
print(np.sum(scores_np, axis=-1))

Output:

scores_np.shape (1, 3, 2)
scores_np:
[[[0.62490064 0.37509936]
  [0.49652317 0.5034768 ]
  [0.64137274 0.3586273 ]]]
np.sum(scores_np, axis=-1).shape (1, 3)
np.sum(scores_np, axis=-1):
[[1. 1. 1.]]

Using an attribute of the current class instance as a default value for method's parameter

There are multiple false assumptions you're making here - First, function belong to a class and not to an instance, meaning the actual function involved is the same for any two instances of a class. Second, default parameters are evaluated at compile time and are constant (as in, a constant object reference - if the parameter is a mutable object you can change it). Thus you cannot access self in a default parameter and will never be able to.

Google API for location, based on user IP address

Here's a script that will use the Google API to acquire the users postal code and populate an input field.

function postalCodeLookup(input) {
    var head= document.getElementsByTagName('head')[0],
        script= document.createElement('script');
    script.src= '//maps.googleapis.com/maps/api/js?sensor=false';
    head.appendChild(script);
    script.onload = function() {
        if (navigator.geolocation) {
            var a = input,
                fallback = setTimeout(function () {
                    fail('10 seconds expired');
                }, 10000);

            navigator.geolocation.getCurrentPosition(function (pos) {
                clearTimeout(fallback);
                var point = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
                new google.maps.Geocoder().geocode({'latLng': point}, function (res, status) {
                    if (status == google.maps.GeocoderStatus.OK && typeof res[0] !== 'undefined') {
                        var zip = res[0].formatted_address.match(/,\s\w{2}\s(\d{5})/);
                        if (zip) {
                            a.value = zip[1];
                        } else fail('Unable to look-up postal code');
                    } else {
                        fail('Unable to look-up geolocation');
                    }
                });
            }, function (err) {
                fail(err.message);
            });
        } else {
            alert('Unable to find your location.');
        }
        function fail(err) {
            console.log('err', err);
            a.value('Try Again.');
        }
    };
}

You can adjust accordingly to acquire different information. For more info, check out the Google Maps API documentation.

How do I output an ISO 8601 formatted string in JavaScript?

The problem with toISOString is that it gives datetime only as "Z".

ISO-8601 also defines datetime with timezone difference in hours and minutes, in the forms like 2016-07-16T19:20:30+5:30 (when timezone is ahead UTC) and 2016-07-16T19:20:30-01:00 (when timezone is behind UTC).

I don't think it is a good idea to use another plugin, moment.js for such a small task, especially when you can get it with a few lines of code.



    var timezone_offset_min = new Date().getTimezoneOffset(),
        offset_hrs = parseInt(Math.abs(timezone_offset_min/60)),
        offset_min = Math.abs(timezone_offset_min%60),
        timezone_standard;

    if(offset_hrs < 10)
        offset_hrs = '0' + offset_hrs;

    if(offset_min > 10)
        offset_min = '0' + offset_min;

    // getTimezoneOffset returns an offset which is positive if the local timezone is behind UTC and vice-versa.
    // So add an opposite sign to the offset
    // If offset is 0, it means timezone is UTC
    if(timezone_offset_min < 0)
        timezone_standard = '+' + offset_hrs + ':' + offset_min;
    else if(timezone_offset_min > 0)
        timezone_standard = '-' + offset_hrs + ':' + offset_min;
    else if(timezone_offset_min == 0)
        timezone_standard = 'Z';

    // Timezone difference in hours and minutes
    // String such as +5:30 or -6:00 or Z
    console.log(timezone_standard); 


Once you have the timezone offset in hours and minutes, you can append to a datetime string.

I wrote a blog post on it : http://usefulangle.com/post/30/javascript-get-date-time-with-offset-hours-minutes

Obtaining only the filename when using OpenFileDialog property "FileName"

Use: Path.GetFileName Method

var onlyFileName = System.IO.Path.GetFileName(ofd.FileName);

Interface vs Base class

An inheritor of a base class should have an "is a" relationship. Interface represents An "implements a" relationship. So only use a base class when your inheritors will maintain the is a relationship.

CSS selector (id contains part of text)

The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

C# listView, how do I add items to columns 2, 3 and 4 etc?

You can add items / sub-items to the ListView like:

ListViewItem item = new ListViewItem(new []{"1","2","3","4"});
listView1.Items.Add(item);

But I suspect your problem is with the View Type. Set it in the designer to Details or do the following in code:

listView1.View = View.Details;

XAMPP Start automatically on Windows 7 startup

I am using XAMPP on Win 7 and 8.1 too...it start normally.

Did you try to check the services on Start > RUN > services.msc

Find the service: Apache 2.x. (right click) choose Properties. At form "Startup type" choose "Automatically" and Start the service on.

you should reset the PC and check out again.

Do the same with mySQL.

If you can not solve the problem, use XAMPP Panel to start it manually.

Remove all child nodes from a parent?

A other users suggested,

.empty()

is good enought, because it removes all descendant nodes (both tag-nodes and text-nodes) AND all kind of data stored inside those nodes. See the JQuery's API empty documentation.

If you wish to keep data, like event handlers for example, you should use

.detach()

as described on the JQuery's API detach documentation.

The method .remove() could be usefull for similar purposes.

ant warning: "'includeantruntime' was not set"

Chet Hosey wrote a nice explanation here:

Historically, Ant always included its own runtime in the classpath made available to the javac task. So any libraries included with Ant, and any libraries available to ant, are automatically in your build's classpath whether you like it or not.

It was decided that this probably wasn't what most people wanted. So now there's an option for it.

If you choose "true" (for includeantruntime), then at least you know that your build classpath will include the Ant runtime. If you choose "false" then you are accepting the fact that the build behavior will change between older versions and 1.8+.

As annoyed as you are to see this warning, you'd be even less happy if your builds broke entirely. Keeping this default behavior allows unmodified build files to work consistently between versions of Ant.

How to detect if a browser is Chrome using jQuery?

User Endless is right,

$.browser.chrome = (typeof window.chrome === "object"); 

code is best to detect Chrome browser using jQuery.

If you using IE and added GoogleFrame as plugin then

var is_chrome = /chrome/.test( navigator.userAgent.toLowerCase() );

code will treat as Chrome browser because GoogleFrame plugin modifying the navigator property and adding chromeframe inside it.

Use latest version of Internet Explorer in the webbrowser control

I was able to implement Luca's solution, but I had to make a few changes for it to work. My goal was to use D3.js with a Web Browser control for a Windows Forms Application (targeting .NET 2.0). It is working for me now. I hope this can help someone else.

using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Threading;
using Microsoft.Win32;
using System.Diagnostics;

namespace ClientUI
{
    static class Program
    {
        static Mutex mutex = new System.Threading.Mutex(false, "jMutex");

        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            if (!mutex.WaitOne(TimeSpan.FromSeconds(2), false))
            {
                // Another application instance is running
                return;
            }
            try
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);

                var targetApplication = Process.GetCurrentProcess().ProcessName + ".exe";
                int ie_emulation = 11999;
                try
                {
                    string tmp = Properties.Settings.Default.ie_emulation;
                    ie_emulation = int.Parse(tmp);
                }
                catch { }
                SetIEVersioneKeyforWebBrowserControl(targetApplication, ie_emulation);

                Application.Run(new MainForm());
            }
            finally
            {
                mutex.ReleaseMutex();
            }
        }

        private static void SetIEVersioneKeyforWebBrowserControl(string appName, int ieval)
        {
            RegistryKey Regkey = null;
            try
            {
                Regkey = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer\Main\FeatureControl\FEATURE_BROWSER_EMULATION", true);

                // If the path is not correct or
                // if user doesn't have privileges to access the registry
                if (Regkey == null)
                {
                    MessageBox.Show("Application FEATURE_BROWSER_EMULATION Failed - Registry key Not found");
                    return;
                }

                string FindAppkey = Convert.ToString(Regkey.GetValue(appName));

                // Check if key is already present
                if (FindAppkey == ieval.ToString())
                {
                    MessageBox.Show("Application FEATURE_BROWSER_EMULATION already set to " + ieval);
                    Regkey.Close();
                    return;
                }

                // If key is not present or different from desired, add/modify the key , key value
                Regkey.SetValue(appName, unchecked((int)ieval), RegistryValueKind.DWord);

                // Check for the key after adding
                FindAppkey = Convert.ToString(Regkey.GetValue(appName));

                if (FindAppkey == ieval.ToString())
                {
                    MessageBox.Show("Application FEATURE_BROWSER_EMULATION changed to " + ieval + "; changes will be visible at application restart");
                }
                else
                {
                    MessageBox.Show("Application FEATURE_BROWSER_EMULATION setting failed; current value is  " + ieval);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Application FEATURE_BROWSER_EMULATION setting failed; " + ex.Message);
            }
            finally
            {
                //Close the Registry
                if (Regkey != null) Regkey.Close();
            }
        }
    }
}

Also, I added a string (ie_emulation) to the project's settings with the value of 11999. This value seems to be working for IE11(11.0.15).

Next, I had to change the permission for my application to allow access to the registry. This can be done by adding a new item to your project (using VS2012). Under the General Items, select Application Manifest File. Change the level from asInvoker to requireAdministrator (as shown below).

<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />

If someone reading this is trying to use D3.js with a webbrowser control, you may have to modify the JSON data to be stored within a variable inside your HTML page because D3.json uses XmlHttpRequest (easier to use with a webserver). After those changes and the above, my windows forms are able to load local HTML files that call D3.

How to hide a div after some time period?

In older versions of jquery you'll have to do it the "javascript way" using settimeout

setTimeout( function(){$('div').hide();} , 4000);

or

setTimeout( "$('div').hide();", 4000);

Recently with jquery 1.4 this solution has been added:

$("div").delay(4000).hide();

Of course replace "div" by the correct element using a valid jquery selector and call the function when the document is ready.

jQuery 'if .change() or .keyup()'

you can bind to multiple events by separating them with a space:

$(":input").on("keyup change", function(e) {
    // do stuff!
})

docs here.

hope that helps. cheers!

Open Form2 from Form1, close Form1 from Form2

on the form2.buttonclick put

this.close();

form1 should have object of form2.

you need to subscribe Closing event of form2.

and in closing method put

this.close();

add commas to a number in jQuery

Another way to do it:

function addCommas(n){
  var s = "",
      r;

  while (n) {
    r = n % 1000;
    s = r + s;
    n = (n - r)/1000;
    s = (n ? "," : "") + s;
  }

  return s;
}

alert(addCommas(12345678));

PHP Warning: PHP Startup: Unable to load dynamic library

Note that you can also get this error if your PHP library doesn't have the "other" directory opening permission. In my particular case, I noticed this when using php -l to syntax check a script in my text editor. This meant that since my account was called "volomike", that account didn't have permission to run the libraries that the php command relied upon.

For instance, on Ubuntu 14.04, I had PHP5 installed automatically into the path /usr/lib/php5/20121212+lfs. However, because I was working in C++ in building some shared objects, I messed around with the directory permissions and screwed things up such that non-root accounts did not have the directory execute (directory open) permissions to view /usr/lib/php5/20121212+lfs. So, I typed the following command to rectify that problem:

sudo chmod o+x /usr/lib/php5/20121212+lfs.

Now when I do php -l example.php as a non-root user, it never gives me this "Unabled to load dynamic library" problem anymore.

How do I remove the last comma from a string using PHP?

It is better to use implode for that purpose. Implode is easy and awesome:

    $array = ['name1', 'name2', 'name3'];
    $str = implode(', ', $array);

Output:

    name1, name2, name3

How to add jQuery code into HTML Page

Before the closing body tag add this (reference to jQuery library). Other hosted libraries can be found here

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

And this

<script>
  //paste your code here
</script>

It should look something like this

<body>
 ........
 ........
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script> Your code </script>
</body>

Ruby capitalize every word first letter

try this:

puts 'one TWO three foUR'.split.map(&:capitalize).join(' ')

#=> One Two Three Four

or

puts 'one TWO three foUR'.split.map(&:capitalize)*' '

Remove multiple objects with rm()

Or using regular expressions

"rmlike" <- function(...) {
  names <- sapply(
    match.call(expand.dots = FALSE)$..., as.character)
  names = paste(names,collapse="|")
  Vars <- ls(1)
  r <- Vars[grep(paste("^(",names,").*",sep=""),Vars)]
  rm(list=r,pos=1)
}

rmlike(temp)

SeekBar and media player in android

Code in Kotlin:

var updateSongTime = object : Runnable {
            override fun run() {
                val getCurrent = mediaPlayer?.currentPosition
                startTimeText?.setText(String.format("%d:%d",
                        TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong() as Long),
                        TimeUnit.MILLISECONDS.toSeconds(getCurrent?.toLong()) -
                                TimeUnit.MINUTES.toSeconds(
                                        TimeUnit.MILLISECONDS.toMinutes(getCurrent?.toLong()))))
                seekBar?.setProgress(getCurrent?.toInt() as Int)
                Handler().postDelayed(this, 1000)
            }
        }

For changing media player audio file every second

If user drags the seek bar then following code snippet can be use

Statified.seekBar?.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar, i: Int, b: Boolean) {
                if(b && Statified.mediaPlayer != null){
                    Statified.mediaPlayer?.seekTo(i)
                }

            }
            override fun onStartTrackingTouch(seekBar: SeekBar) {}
            override fun onStopTrackingTouch(seekBar: SeekBar) {}
        })

`ui-router` $stateParams vs. $state.params

An interesting observation I made while passing previous state params from one route to another is that $stateParams gets hoisted and overwrites the previous route's state params that were passed with the current state params, but using $state.params doesn't.

When using $stateParams:

var stateParams        = {};
stateParams.nextParams = $stateParams; //{item_id:123}
stateParams.next       = $state.current.name;

$state.go('app.login', stateParams);
//$stateParams.nextParams on app.login is now:
//{next:'app.details', nextParams:{next:'app.details'}}

When using $state.params:

var stateParams        = {};
stateParams.nextParams = $state.params; //{item_id:123}
stateParams.next       = $state.current.name;

$state.go('app.login', stateParams);
//$stateParams.nextParams on app.login is now:
//{next:'app.details', nextParams:{item_id:123}}

New Line Issue when copying data from SQL Server 2012 to Excel

Once Data is exported to excel, highlight the date column and format to fit your needs or use the custom field. Worked for me like a charm!

Splitting String and put it on int array

Something like this:

  public static void main(String[] args) {
   String N = "ABCD";
   char[] array = N.toCharArray();

   // and as you can see:
    System.out.println(array[0]);
    System.out.println(array[1]);
    System.out.println(array[2]);
  }

gcc error: wrong ELF class: ELFCLASS64

You can specify '-m32' or '-m64' to select the compilation mode.

When dealing with autoconf (configure) scripts, I usually set CC="gcc -m64" (or CC="gcc -m32") in the environment so that everything is compiled with the correct bittiness. At least, usually...people find endless ways to make that not quite work, but my batting average is very high (way over 95%) with it.

What difference does .AsNoTracking() make?

No Tracking LINQ to Entities queries

Usage of AsNoTracking() is recommended when your query is meant for read operations. In these scenarios, you get back your entities but they are not tracked by your context.This ensures minimal memory usage and optimal performance

Pros

  1. Improved performance over regular LINQ queries.
  2. Fully materialized objects.
  3. Simplest to write with syntax built into the programming language.

Cons

  1. Not suitable for CUD operations.
  2. Certain technical restrictions, such as: Patterns using DefaultIfEmpty for OUTER JOIN queries result in more complex queries than simple OUTER JOIN statements in Entity SQL.
  3. You still can’t use LIKE with general pattern matching.

More info available here:

Performance considerations for Entity Framework

Entity Framework and NoTracking

How do I trim a file extension from a String in Java?

 private String trimFileExtension(String fileName)
  {
     String[] splits = fileName.split( "\\." );
     return StringUtils.remove( fileName, "." + splits[splits.length - 1] );
  }

Unable to establish SSL connection upon wget on Ubuntu 14.04 LTS

... right now it happens only to the website I'm testing. I can't post it here because it's confidential.

Then I guess it is one of the sites which is incompatible with TLS1.2. The openssl as used in 12.04 does not use TLS1.2 on the client side while with 14.04 it uses TLS1.2 which might explain the difference. To work around try to explicitly use --secure-protocol=TLSv1. If this does not help check if you can access the site with openssl s_client -connect ... (probably not) and with openssl s_client -tls1 -no_tls1_1, -no_tls1_2 ....

Please note that it might be other causes, but this one is the most probable and without getting access to the site everything is just speculation anyway.

The assumed problem in detail: Usually clients use the most compatible handshake to access a server. This is the SSLv23 handshake which is compatible to older SSL versions but announces the best TLS version the client supports, so that the server can pick the best version. In this case wget would announce TLS1.2. But there are some broken servers which never assumed that one day there would be something like TLS1.2 and which refuse the handshake if the client announces support for this hot new version (from 2008!) instead of just responding with the best version the server supports. To access these broken servers the client has to lie and claim that it only supports TLS1.0 as the best version.

Is Ubuntu 14.04 or wget 1.15 not compatible with TLS 1.0 websites? Do I need to install/download any library/software to enable this connection?

The problem is the server, not the client. Most browsers work around these broken servers by retrying with a lower version. Most other applications fail permanently if the first connection attempt fails, i.e. they don't downgrade by itself and one has to enforce another version by some application specific settings.

What is the difference between Scrum and Agile Development?

Scrum is just one of the many iterative and incremental agile software development methods. You can find here a very detailed description of the process.

In the SCRUM methodology, a Sprint is the basic unit of development. Each Sprint starts with a planning meeting, where the tasks for the sprint are identified and an estimated commitment for the sprint goal is made. A Sprint ends with a review or retrospective meeting where the progress is reviewed and lessons for the next sprint are identified. During each Sprint, the team creates finished portions of a Product.

In the Agile methods each iteration involves a team working through a full software development cycle, including planning, requirements analysis, design, coding, unit testing, and acceptance testing when a working product is demonstrated to stakeholders.

So if in a SCRUM Sprint you perform all the software development phases (from requirement analysis to acceptance testing), and in my opinion you should, you can say SCRUM Sprints correspond to AGILE Iterations.

Create web service proxy in Visual Studio from a WSDL file

save the file on your disk and then use the following as URL:

file://your_path/your_file.wsdl

Transition of background-color

Another way of accomplishing this is using animation which provides more control.

#content #nav a {
    background-color: #FF0;
    
    /* only animation-duration here is required, rest are optional (also animation-name but it will be set on hover)*/
    animation-duration: 1s; /* same as transition duration */
    animation-timing-function: linear; /* kind of same as transition timing */
    animation-delay: 0ms; /* same as transition delay */
    animation-iteration-count: 1; /* set to 2 to make it run twice, or Infinite to run forever!*/
    animation-direction: normal; /* can be set to "alternate" to run animation, then run it backwards.*/
    animation-fill-mode: none; /* can be used to retain keyframe styling after animation, with "forwards" */
    animation-play-state: running; /* can be set dynamically to pause mid animation*/
    
    /* declaring the states of the animation to transition through */
    /* optionally add other properties that will change here, or new states (50% etc) */
    @keyframes onHoverAnimation {
    0% {
      background-color: #FF0;  
    }
    100% {
      background-color: #AD310B;
    }
  }
}

#content #nav a:hover {
    /* animation wont run unless the element is given the name of the animation. This is set on hover */
    animation-name: onHoverAnimation;
}

Remove android default action bar

I've noticed that if you set the theme in the AndroidManifest, it seems to get rid of that short time where you can see the action bar. So, try adding this to your manifest:

<android:theme="@android:style/Theme.NoTitleBar">

Just add it to your application tag to apply it app-wide.

What is the regex for "Any positive integer, excluding 0"

Try this:

^[1-9]\d*$

...and some padding to exceed 30 character SO answer limit :-).

Here is Demo

How to generate unique id in MySQL?

USE IT

    $info = random_bytes(16);
    $info[6] = chr(ord($info[6]) & 0x0f | 0x40); 
    $info[8] = chr(ord($info[8]) & 0x3f | 0x80); 
    $result =vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($info), 4));
    return $result;

How do I write a "tab" in Python?

You can use \t in a string literal:

"hello\talex"

How to make a copy of an object in C#

Properties in your object are value types and you can use the shallow copy in such situation like that:

obj myobj2 = (obj)myobj.MemberwiseClone();

But in other situations, like if any members are reference types, then you need Deep Copy. You can get a deep copy of an object using Serialization and Deserialization techniques with the help of BinaryFormatter class:

public static T DeepCopy<T>(T other)
{
    using (MemoryStream ms = new MemoryStream())
    {
        BinaryFormatter formatter = new BinaryFormatter();
        formatter.Context = new StreamingContext(StreamingContextStates.Clone);
        formatter.Serialize(ms, other);
        ms.Position = 0;
        return (T)formatter.Deserialize(ms);
    }
}

The purpose of setting StreamingContext: We can introduce special serialization and deserialization logic to our code with the help of either implementing ISerializable interface or using built-in attributes like OnDeserialized, OnDeserializing, OnSerializing, OnSerialized. In all cases StreamingContext will be passed as an argument to the methods(and to the special constructor in case of ISerializable interface). With setting ContextState to Clone, we are just giving hint to that method about the purpose of the serialization.

Additional Info: (you can also read this article from MSDN)

Shallow copying is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed; for a reference type, the reference is copied but the referred object is not; therefore the original object and its clone refer to the same object.

Deep copy is creating a new object and then copying the nonstatic fields of the current object to the new object. If a field is a value type, a bit-by-bit copy of the field is performed. If a field is a reference type, a new copy of the referred object is performed.

The openssl extension is required for SSL/TLS protection

enter image description here You are running Composer with SSL/TLS protection disabled.

 composer config --global disable-tls true
 composer config --global disable-tls false

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

I have this problem when update android studio from 3.2 to 3.3 and test every answers that i none of them was working. at the end i enabled Maven repository and its work.

enter image description here

All possible array initialization syntaxes

Just a note

The following arrays:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = { "A" , "B" };
string[] array4 = new[] { "A", "B" };

Will be compiled to:

string[] array = new string[2];
string[] array2 = new string[] { "A", "B" };
string[] array3 = new string[] { "A", "B" };
string[] array4 = new string[] { "A", "B" };

Get Substring between two characters using javascript

function substringBetween(s, a, b) {
    var p = s.indexOf(a) + a.length;
    return s.substring(p, s.indexOf(b, p));
}

// substringBetween('MyLongString:StringIWant;', ':', ';') -> StringIWant
// substringBetween('MyLongString:StringIWant;;', ':', ';') -> StringIWant
// substringBetween('MyLongString:StringIWant;:StringIDontWant;', ':', ';') -> StringIWant

iOS 11, 12, and 13 installed certificates not trusted automatically (self signed)

If you are not seeing the certificate under General->About->Certificate Trust Settings, then you probably do not have the ROOT CA installed. Very important -- needs to be a ROOT CA, not an intermediary CA.

I just answered a question here explaining how to obtain the ROOT CA and get things to show up: How to install self-signed certificates in iOS 11

Generate table relationship diagram from existing schema (SQL Server)

MySQL WorkBench is free software and is developed by Oracle, you can import an SQL File or specify a database and it will generate an SQL Diagram which you can move around to make it more visually appealing. It runs on GNU/Linux and Windows and it's free and has a professional look..

change <audio> src with javascript

If you are storing metadata in a tag use data attributes eg.

<li id="song1" data-value="song1.ogg"><button onclick="updateSource()">Item1</button></li>

Now use the attribute to get the name of the song

var audio = document.getElementById('audio');
audio.src='audio/ogg/' + document.getElementById('song1').getAttribute('data-value');
audio.load();

How do I set up a private Git repository on GitHub? Is it even possible?

Once you have a paid account on GitHub, it is not obvious how to create a private repository. To create a private repository for an organization with paid account, go to https://github.com/organizations/MYORGANIZATIONNAME.

The only way I've figured how to navigate there is:

  • Go to to your organization's home page: https://github.com/MYORGANIZATIONNAME
  • Click on the "Edit MYORGANIZATION's Profile" button at the top right
  • Click on the "GitHub" icon at the top left (non-obvious)
  • Click on the "News Feed" tab (non-obvious)
  • Click on the "New Repository" button at the right ...

Android/Java - Date Difference in days

The Correct Way from Sam Quest's answer only works if the first date is earlier than the second. Moreover, it will return 1 if the two dates are within a single day.

This is the solution that worked best for me. Just like most other solutions, it would still show incorrect results on two days in a year because of wrong day light saving offset.

private final static long MILLISECS_PER_DAY = 24 * 60 * 60 * 1000;

long calculateDeltaInDays(Calendar a, Calendar b) {

    // Optional: avoid cloning objects if it is the same day
    if(a.get(Calendar.ERA) == b.get(Calendar.ERA) 
            && a.get(Calendar.YEAR) == b.get(Calendar.YEAR)
            && a.get(Calendar.DAY_OF_YEAR) == b.get(Calendar.DAY_OF_YEAR)) {
        return 0;
    }
    Calendar a2 = (Calendar) a.clone();
    Calendar b2 = (Calendar) b.clone();
    a2.set(Calendar.HOUR_OF_DAY, 0);
    a2.set(Calendar.MINUTE, 0);
    a2.set(Calendar.SECOND, 0);
    a2.set(Calendar.MILLISECOND, 0);
    b2.set(Calendar.HOUR_OF_DAY, 0);
    b2.set(Calendar.MINUTE, 0);
    b2.set(Calendar.SECOND, 0);
    b2.set(Calendar.MILLISECOND, 0);
    long diff = a2.getTimeInMillis() - b2.getTimeInMillis();
    long days = diff / MILLISECS_PER_DAY;
    return Math.abs(days);
}

How to animate RecyclerView items when they appear

Made Simple with XML only

Visit Gist Link

res/anim/layout_animation.xml

<?xml version="1.0" encoding="utf-8"?>
    <layoutAnimation xmlns:android="http://schemas.android.com/apk/res/android"
        android:animation="@anim/item_animation_fall_down"
        android:animationOrder="normal"
        android:delay="15%" />

res/anim/item_animation_fall_down.xml

<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="500">

    <translate
        android:fromYDelta="-20%"
        android:toYDelta="0"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

    <alpha
        android:fromAlpha="0"
        android:toAlpha="1"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

    <scale
        android:fromXScale="105%"
        android:fromYScale="105%"
        android:toXScale="100%"
        android:toYScale="100%"
        android:pivotX="50%"
        android:pivotY="50%"
        android:interpolator="@android:anim/decelerate_interpolator"
        />

</set>

Use in layouts and recylcerview like:

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/recycler_view"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layoutAnimation="@anim/layout_animation"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

Combine :after with :hover

 #alertlist li:hover:after,#alertlist li.selected:after
{
    position:absolute;
    top: 0;
    right:-10px;
    bottom:0;

    border-top: 10px solid transparent;
    border-bottom: 10px solid transparent;
    border-left: 10px solid #303030;
    content: "";
}?

jsFiddle Link

How to convert date into this 'yyyy-MM-dd' format in angular 2

You can also use formatDate

let formattedDt = formatDate(new Date(), 'yyyy-MM-dd hh:mm:ssZZZZZ', 'en_US')

Converting XDocument to XmlDocument and vice versa

There is a discussion on http://blogs.msdn.com/marcelolr/archive/2009/03/13/fast-way-to-convert-xmldocument-into-xdocument.aspx

It seems that reading an XDocument via an XmlNodeReader is the fastest method. See the blog for more details.

Entity Framework code-first: migration fails with update-database, forces unneccessary(?) add-migration

Entity Framework does have some issues around identity fields.

You can't add GUID identity on existing table

Migrations: does not detect changes to DatabaseGeneratedOption

Reverse engineering does not mark GUID keys with default NEWSEQUENTIALID() as store generated identities

None of these describes your issue exactly and the Down() method in your extra migration is interesting because it appears to be attempting to remove IDENTITY from the column when your CREATE TABLE in the initial migration appears to set it!

Furthermore, if you use Update-Database -Script or Update-Database -Verbose to view the sql that is run from these AlterColumn methods you will see that the sql is identical in Up and Down, and actually does nothing. IDENTITY remains unchanged (for the current version - EF 6.0.2 and below) - as described in the first 2 issues I linked to.

I think you should delete the redundant code in your extra migration and live with an empty migration for now. And you could subscribe to/vote for the issues to be addressed.

References:

Change IDENTITY option does diddly squat

Switch Identity On/Off With A Custom Migration Operation

Deactivate or remove the scrollbar on HTML

In HTML

<div style="overflow: hidden;">

in CSS

overflow: hidden;

you can also end scrolling for x or y separately

overflow-y: hidden; /* Hide vertical scrollbar */
  overflow-x: hidden; /* Hide horizontal scrollbar */

Angular HttpClient "Http failure during parsing"

I was facing the same issue in my Angular application. I was using RocketChat REST API in my application and I was trying to use the rooms.createDiscussion, but as an error as below.

ERROR Error: Uncaught (in promise): HttpErrorResponse: {"headers":{"normalizedNames":{},"lazyUpdate":null},"status":200,"statusText":"OK","url":"myurl/rocketchat/api/v1/rooms.createDiscussion","ok":false,"name":"HttpErrorResponse","message":"Http failure during parsing for myrul/rocketchat/api/v1/rooms.createDiscussion","error":{"error":{},"text":"

I have tried couple of things like changing the responseType: 'text' but none of them worked. At the end I was able to find the issue was with my RocketChat installation. As mentioned in the RocketChat change log the API rooms.createDiscussion is been introduced in the version 1.0.0 unfortunately I was using a lower version.

My suggestion is to check the REST API is working fine or not before you spend time to fix the error in your Angular code. I used curl command to check that.

curl -H "X-Auth-Token: token" -H "X-User-Id: userid" -H "Content-Type: application/json" myurl/rocketchat/api/v1/rooms.createDiscussion -d '{ "prid": "GENERAL", "t_name": "Discussion Name"}'

There as well I was getting an invalid HTML as a response.

<!DOCTYPE html>
<html>
<head>
<meta name="referrer" content="origin-when-crossorigin">
<script>/* eslint-disable */

'use strict';
(function() {
        var debounce = function debounce(func, wait, immediate) {

Instead of a valid JSON response as follows.

{
    "discussion": {
        "rid": "cgk88DHLHexwMaFWh",
        "name": "WJNEAM7W45wRYitHo",
        "fname": "Discussion Name",
        "t": "p",
        "msgs": 0,
        "usersCount": 0,
        "u": {
            "_id": "rocketchat.internal.admin.test",
            "username": "rocketchat.internal.admin.test"
        },
        "topic": "general",
        "prid": "GENERAL",
        "ts": "2019-04-03T01:35:32.271Z",
        "ro": false,
        "sysMes": true,
        "default": false,
        "_updatedAt": "2019-04-03T01:35:32.280Z",
        "_id": "cgk88DHLHexwMaFWh"
    },
    "success": true
}

So after updating to the latest RocketChat I was able to use the mentioned REST API.

How to pass ArrayList<CustomeObject> from one activity to another?

you need implements Parcelable in your ContactBean class, I put one example for you:

public class ContactClass implements Parcelable {

private String id;
private String photo;
private String firstname;
private String lastname;

public ContactClass()
{

}

private ContactClass(Parcel in) {
    firstname = in.readString();
    lastname = in.readString();
    photo = in.readString();
    id = in.readString();

}

@Override
public int describeContents() {
    // TODO Auto-generated method stub
    return 0;
}

@Override
public void writeToParcel(Parcel dest, int flags) {

    dest.writeString(firstname);
    dest.writeString(lastname);
    dest.writeString(photo);
    dest.writeString(id);

}

 public static final Parcelable.Creator<ContactClass> CREATOR = new Parcelable.Creator<ContactClass>() {
        public ContactClass createFromParcel(Parcel in) {
            return new ContactClass(in);
        }

        public ContactClass[] newArray(int size) {
            return new ContactClass[size];

        }
    };

   // all get , set method 
 }

and this get and set for your code:

Intent intent = new Intent(this,DisplayContact.class);
intent.putExtra("Contact_list", ContactLis);
startActivity(intent);

second class:

ArrayList<ContactClass> myList = getIntent().getParcelableExtra("Contact_list");

Filling a List with all enum values in Java

Try this:

... = new ArrayList<Something>(EnumSet.allOf(Something.class));

as ArrayList has a constructor with Collection<? extends E>. But use this method only if you really want to use EnumSet.

All enums have access to the method values(). It returns an array of all enum values:

... = Arrays.asList(Something.values());

javax.net.ssl.SSLException: Received fatal alert: protocol_version

I was getting the same error. For Java version 7, following is working for me.

java.lang.System.setProperty("https.protocols", "TLSv1.2");

How to use localization in C#

  • Add a Resource file to your project (you can call it "strings.resx") by doing the following:
    Right-click Properties in the project, select Add -> New Item... in the context menu, then in the list of Visual C# Items pick "Resources file" and name it strings.resx.
  • Add a string resouce in the resx file and give it a good name (example: name it "Hello" with and give it the value "Hello")
  • Save the resource file (note: this will be the default resource file, since it does not have a two-letter language code)
  • Add references to your program: System.Threading and System.Globalization

Run this code:

Console.WriteLine(Properties.strings.Hello);

It should print "Hello".

Now, add a new resource file, named "strings.fr.resx" (note the "fr" part; this one will contain resources in French). Add a string resource with the same name as in strings.resx, but with the value in French (Name="Hello", Value="Salut"). Now, if you run the following code, it should print Salut:

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("fr-FR");
Console.WriteLine(Properties.strings.Hello);

What happens is that the system will look for a resource for "fr-FR". It will not find one (since we specified "fr" in your file"). It will then fall back to checking for "fr", which it finds (and uses).

The following code, will print "Hello":

Thread.CurrentThread.CurrentUICulture = CultureInfo.GetCultureInfo("en-US");
Console.WriteLine(Properties.strings.Hello);

That is because it does not find any "en-US" resource, and also no "en" resource, so it will fall back to the default, which is the one that we added from the start.

You can create files with more specific resources if needed (for instance strings.fr-FR.resx and strings.fr-CA.resx for French in France and Canada respectively). In each such file you will need to add the resources for those strings that differ from the resource that it would fall back to. So if a text is the same in France and Canada, you can put it in strings.fr.resx, while strings that are different in Canadian french could go into strings.fr-CA.resx.

Displaying output of a remote command with Ansible

If you pass the -v flag to the ansible-playbook command, then ansible will show the output on your terminal.

For your use case, you may want to try using the fetch module to copy the public key from the server to your local machine. That way, it will only show a "changed" status when the file changes.

What does ** (double star/asterisk) and * (star/asterisk) do for parameters?

*args and **kwargs: allow you to pass a variable number of arguments to a function.

*args: is used to send a non-keyworded variable length argument list to the function:

def args(normal_arg, *argv):
    print("normal argument:", normal_arg)

    for arg in argv:
        print("Argument in list of arguments from *argv:", arg)

args('animals', 'fish', 'duck', 'bird')

Will produce:

normal argument: animals
Argument in list of arguments from *argv: fish
Argument in list of arguments from *argv: duck
Argument in list of arguments from *argv: bird

**kwargs*

**kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function.

def who(**kwargs):
    if kwargs is not None:
        for key, value in kwargs.items():
            print("Your %s is %s." % (key, value))

who(name="Nikola", last_name="Tesla", birthday="7.10.1856", birthplace="Croatia")  

Will produce:

Your name is Nikola.
Your last_name is Tesla.
Your birthday is 7.10.1856.
Your birthplace is Croatia.

How to show google.com in an iframe?

This used to work because I used it to create custom Google searches with my own options. Google made changes on their end and broke my private customized search page :( No longer working sample below. It was very useful for complex search patterns.

<form method="get" action="http://www.google.com/search" target="main"><input name="q" value="" type="hidden"> <input name="q" size="40" maxlength="2000" value="" type="text">

web

I guess the better option is to just use Curl or similar.

How to create local notifications?

Here is sample code for LocalNotification that worked for my project.

Objective-C:

This code block in AppDelegate file :

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
        [launchOptions valueForKey:UIApplicationLaunchOptionsLocalNotificationKey];
        // Override point for customization after application launch.
        return YES;
    }

    // This code block is invoked when application is in foreground (active-mode) 
 -(void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {

        UIAlertView *notificationAlert = [[UIAlertView alloc] initWithTitle:@"Notification"    message:@"This local notification" 
        delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];

        [notificationAlert show];
       // NSLog(@"didReceiveLocalNotification");
    }

This code block in .m file of any ViewController:

-(IBAction)startLocalNotification {  // Bind this method to UIButton action
    NSLog(@"startLocalNotification");

    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate dateWithTimeIntervalSinceNow:7];
    notification.alertBody = @"This is local notification!";
    notification.timeZone = [NSTimeZone defaultTimeZone];
    notification.soundName = UILocalNotificationDefaultSoundName;
    notification.applicationIconBadgeNumber = 10;

    [[UIApplication sharedApplication] scheduleLocalNotification:notification];    
}

The above code display an AlertView after time interval of 7 seconds when pressed on button that binds startLocalNotification If application is in background then it displays BadgeNumber as 10 and with default notification sound.

This code works fine for iOS 7.x and below but for iOS 8 it will prompt following error on console:

Attempting to schedule a local notification with an alert but haven't received permission from the user to display alerts

This means you need register for local notification. This can be achieved using:

if ([UIApplication instancesRespondToSelector:@selector(registerUserNotificationSettings:)]){

    [application registerUserNotificationSettings [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound categories:nil]];
}

You can also refer blog for local notification.

Swift:

You AppDelegate.swift file should look like this:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {    
    // Override point for customization after application launch.
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: UIUserNotificationType.Sound | UIUserNotificationType.Badge | UIUserNotificationType.Alert, categories: nil))

    return true
}

The swift file (say ViewController.swift) in which you want to create local notification should contain below code:

//MARK: - Button functions
func buttonIsPressed(sender: UIButton) {
    println("buttonIsPressed function called \(UIButton.description())")

    var localNotification = UILocalNotification()
    localNotification.fireDate = NSDate(timeIntervalSinceNow: 3)
    localNotification.alertBody = "This is local notification from Swift 2.0"
    localNotification.timeZone = NSTimeZone.localTimeZone()
    localNotification.repeatInterval = NSCalendarUnit.CalendarUnitMinute
    localNotification.userInfo = ["Important":"Data"];
    localNotification.soundName = UILocalNotificationDefaultSoundName
    localNotification.applicationIconBadgeNumber = 5
    localNotification.category = "Message"

    UIApplication.sharedApplication().scheduleLocalNotification(localNotification)
}


//MARK: - viewDidLoad

class ViewController: UIViewController {

    var objButton : UIButton!
    . . .

    override func viewDidLoad() {
        super.viewDidLoad()

        . . .

        objButton = UIButton.buttonWithType(.Custom) as? UIButton
        objButton.frame = CGRectMake(30, 100, 150, 40)
        objButton.setTitle("Click Me", forState: .Normal)
        objButton.setTitle("Button pressed", forState: .Highlighted)

        objButton.addTarget(self, action: "buttonIsPressed:", forControlEvents: .TouchDown)

        . . .
    }

    . . .
}

The way you use to work with Local Notification in iOS 9 and below is completely different in iOS 10.

Below screen grab from Apple release notes depicts this.

Screenshot

You can refer apple reference document for UserNotification.

Below is code for local notification:

Objective-C:

  1. In App-delegate.h file use @import UserNotifications;

  2. App-delegate should conform to UNUserNotificationCenterDelegate protocol

  3. In didFinishLaunchingOptions use below code:

    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert)
           completionHandler:^(BOOL granted, NSError * _Nullable error) {
                  if (!error) {
                      NSLog(@"request authorization succeeded!");
                      [self showAlert];
                  }
    }];
    
    -(void)showAlert {
        UIAlertController *objAlertController = [UIAlertController alertControllerWithTitle:@"Alert" message:@"show an alert!" preferredStyle:UIAlertControllerStyleAlert];
    
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"OK"
          style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
            NSLog(@"Ok clicked!");
        }];
    
        [objAlertController addAction:cancelAction];
    
    
        [[[[[UIApplication sharedApplication] windows] objectAtIndex:0] rootViewController] presentViewController:objAlertController animated:YES completion:^{            
        }];
    
    }
    
  4. Now create a button in any view controller and in IBAction use below code :

    UNMutableNotificationContent *objNotificationContent = [[UNMutableNotificationContent alloc] init];
    
    objNotificationContent.title = [NSString localizedUserNotificationStringForKey:@“Notification!” arguments:nil];
    
    objNotificationContent.body = [NSString localizedUserNotificationStringForKey:@“This is local notification message!“arguments:nil];
    
    objNotificationContent.sound = [UNNotificationSound defaultSound];
    
    // 4. update application icon badge number
    objNotificationContent.badge = @([[UIApplication sharedApplication] applicationIconBadgeNumber] + 1);
    
    // Deliver the notification in five seconds.
    UNTimeIntervalNotificationTrigger *trigger =  [UNTimeIntervalNotificationTrigger                                             triggerWithTimeInterval:10.f repeats:NO];       
    
    UNNotificationRequest *request = [UNNotificationRequest requestWithIdentifier:@“ten”                                                                            content:objNotificationContent trigger:trigger];
    
    // 3. schedule localNotification
    UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
    
    [center addNotificationRequest:request withCompletionHandler:^(NSError * _Nullable error) {
        if (!error) {
            NSLog(@“Local Notification succeeded“);
        } else {
            NSLog(@“Local Notification failed“);
        }
    }];
    

Swift 3:

  1. In AppDelegate.swift file use import UserNotifications
  2. Appdelegate should conform to UNUserNotificationCenterDelegate protocol
  3. In didFinishLaunchingWithOptions use below code

    // Override point for customization after application launch.
    let center = UNUserNotificationCenter.current()
    center.requestAuthorization(options: [.alert, .sound]) { (granted, error) in
        // Enable or disable features based on authorization.
        if error != nil {
            print("Request authorization failed!")
        } else {
            print("Request authorization succeeded!")
            self.showAlert()
        }
    }
    
    
    func showAlert() {
        let objAlert = UIAlertController(title: "Alert", message: "Request authorization succeeded", preferredStyle: UIAlertControllerStyle.alert)
    
        objAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
        //self.presentViewController(objAlert, animated: true, completion: nil)
    
        UIApplication.shared().keyWindow?.rootViewController?.present(objAlert, animated: true, completion: nil)
    }
    
  4. Now create a button in any view controller and in IBAction use below code :

    let content = UNMutableNotificationContent()
    content.title = NSString.localizedUserNotificationString(forKey: "Hello!", arguments: nil)
    content.body = NSString.localizedUserNotificationString(forKey: "Hello_message_body", arguments: nil)
    content.sound = UNNotificationSound.default()
    content.categoryIdentifier = "notify-test"
    
    let trigger = UNTimeIntervalNotificationTrigger.init(timeInterval: 5, repeats: false)
    let request = UNNotificationRequest.init(identifier: "notify-test", content: content, trigger: trigger)
    
    let center = UNUserNotificationCenter.current()
    center.add(request)
    

C++ Array of pointers: delete or delete []?

To simplify the answare let's look on the following code:

#include "stdafx.h"
#include <iostream>
using namespace std;

class A
{
private:
    int m_id;
    static int count;
public:
    A() {count++; m_id = count;}
    A(int id) { m_id = id; }
    ~A() {cout<< "Destructor A "   <<m_id<<endl; }
};

int A::count = 0;

void f1()
{   
    A* arr = new A[10];
    //delete operate only one constructor, and crash!
    delete arr;
    //delete[] arr;
}

int main()
{
    f1();
    system("PAUSE");
    return 0;
}

The output is: Destructor A 1 and then it's crashing (Expression: _BLOCK_TYPE_IS_VALID(phead- nBlockUse)).

We need to use: delete[] arr; becuse it's delete the whole array and not just one cell!

try to use delete[] arr; the output is: Destructor A 10 Destructor A 9 Destructor A 8 Destructor A 7 Destructor A 6 Destructor A 5 Destructor A 4 Destructor A 3 Destructor A 2 Destructor A 1

The same principle is for an array of pointers:

void f2()
{
    A** arr = new A*[10];
    for(int i = 0; i < 10; i++)
    {
        arr[i] = new A(i);
    }
    for(int i = 0; i < 10; i++)
    {
        delete arr[i];//delete the A object allocations.
    }

    delete[] arr;//delete the array of pointers
}

if we'll use delete arr instead of delete[] arr. it will not delete the whole pointers in the array => memory leak of pointer objects!

Merging cells in Excel using Apache POI

You can use sheet.addMergedRegion(rowFrom,rowTo,colFrom,colTo);

example sheet.addMergedRegion(new CellRangeAddress(1,1,1,4)); will merge from B2 to E2. Remember it is zero based indexing (ex. POI version 3.12).

for detail refer BusyDeveloper's Guide

Remove rows with all or some NAs (missing values) in data.frame

If you want control over how many NAs are valid for each row, try this function. For many survey data sets, too many blank question responses can ruin the results. So they are deleted after a certain threshold. This function will allow you to choose how many NAs the row can have before it's deleted:

delete.na <- function(DF, n=0) {
  DF[rowSums(is.na(DF)) <= n,]
}

By default, it will eliminate all NAs:

delete.na(final)
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
6 ENSG00000221312    0    1    2    3    2

Or specify the maximum number of NAs allowed:

delete.na(final, 2)
             gene hsap mmul mmus rnor cfam
2 ENSG00000199674    0    2    2    2    2
4 ENSG00000207604    0   NA   NA    1    2
6 ENSG00000221312    0    1    2    3    2

jQuery AJAX file upload PHP

Use pure js

_x000D_
_x000D_
async function saveFile() _x000D_
{_x000D_
    let formData = new FormData();           _x000D_
    formData.append("file", sortpicture.files[0]);_x000D_
    await fetch('/uploads', {method: "POST", body: formData});    _x000D_
    alert('works');_x000D_
}
_x000D_
<input id="sortpicture" type="file" name="sortpic" />_x000D_
<button id="upload" onclick="saveFile()">Upload</button>_x000D_
<br>Before click upload look on chrome>console>network (in this snipped we will see 404)
_x000D_
_x000D_
_x000D_

The filename is automatically included to request and server can read it, the 'content-type' is automatically set to 'multipart/form-data'. Here is more developed example with error handling and additional json sending

_x000D_
_x000D_
async function saveFile(inp) _x000D_
{_x000D_
    let user = { name:'john', age:34 };_x000D_
    let formData = new FormData();_x000D_
    let photo = inp.files[0];      _x000D_
         _x000D_
    formData.append("photo", photo);_x000D_
    formData.append("user", JSON.stringify(user));  _x000D_
    _x000D_
    try {_x000D_
       let r = await fetch('/upload/image', {method: "POST", body: formData}); _x000D_
       console.log('HTTP response code:',r.status); _x000D_
       alert('success');_x000D_
    } catch(e) {_x000D_
       console.log('Huston we have problem...:', e);_x000D_
    }_x000D_
    _x000D_
}
_x000D_
<input type="file" onchange="saveFile(this)" >_x000D_
<br><br>_x000D_
Before selecting the file Open chrome console > network tab to see the request details._x000D_
<br><br>_x000D_
<small>Because in this example we send request to https://stacksnippets.net/upload/image the response code will be 404 ofcourse...</small>
_x000D_
_x000D_
_x000D_