Programs & Examples On #Webarchive

Webarchive is the format used by the Safari browser to package the HTML, CSS, JavaScript and image resources of a web page when saved as a complete offline archive.

rand() between 0 and 1

My guess is that RAND_MAX is equal to INT_MAX and so you're overflowing it to a negative.

Just do this:

r = ((double) rand() / (RAND_MAX)) + 1;

Or even better, use C++11's random number generators.

How can I select the row with the highest ID in MySQL?

SELECT MAX(id) FROM TABELNAME

This identifies the largest id and returns the value

onChange and onSelect in DropDownList

To make a robust form, have it load in a useful state and use script to enhance its behaviour. In the following, the select has been replaced by radio buttons (makes life much easier for the user).

The "yes" option is checked by default and the select is enabled. If the user checks either radio button, the select is enabled or disabled accordingly.

<form onclick="this.mySelect1.disabled = this.becomeMember[1].checked;" ... >
  <input type="radio" name="becomeMember" checked>Yes<br>
  <input type="radio" name="becomeMember">No<br>

  <select id="mySelect1">
    <option>Dep1
    <option>Dep2
    <option>Dep3
    <option>Dep4
  </select>
  ...
</form> 

Gson: How to exclude specific fields from Serialization without annotations

Any fields you don't want serialized in general you should use the "transient" modifier, and this also applies to json serializers (at least it does to a few that I have used, including gson).

If you don't want name to show up in the serialized json give it a transient keyword, eg:

private transient String name;

More details in the Gson documentation

Spring Boot: How can I set the logging level with application.properties?

Existing answers are greats. I just want to share with you a new spring boot feature allowing to group logs and set logging level on the whole group.

Exemple from the docs :

  • Create a logging group
logging.group.tomcat=org.apache.catalina, org.apache.coyote, org.apache.tomcat
  • Set the logging level for group
logging.level.tomcat=TRACE

It's nice feature which brings more flexibility.

AngularJs ReferenceError: angular is not defined

I faced similar issue due to local vs remote referencing

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.js"></script>
<script src="lib/js/ui-grid/3.0.7/ui-grid.js"></script>

As ui-grid.js is dependent on angular.js, ui-grid requires angular.js by the time its loaded. But in the above case, ui-grid.js [locally saved reference file] is loaded before angularjs was loaded [from internet],

The problem was solved if I had both angular.js and ui-grid referenced locally and as well declaring angular.js before ui-grid

<script src="lib/js/angularjs/1.4.3/angular.js"></script>
<script src="lib/js/ui-grid/3.0.7/ui-grid.js"></script>

How can I extract audio from video with ffmpeg?

If the audio wrapped into the avi is not mp3-format to start with, you may need to specify -acodec mp3 as an additional parameter. Or whatever your mp3 codec is (on Linux systems its probably -acodec libmp3lame). You may also get the same effect, platform-agnostic, by instead specifying -f mp3 to "force" the format to mp3, although not all versions of ffmpeg still support that switch. Your Mileage May Vary.

.NET unique object identifier

I know that this has been answered, but it's at least useful to note that you can use:

http://msdn.microsoft.com/en-us/library/system.object.referenceequals.aspx

Which will not give you a "unique id" directly, but combined with WeakReferences (and a hashset?) could give you a pretty easy way of tracking various instances.

How to increase heap size for jBoss server

Look in your JBoss bin folder for the file run.bat (run.sh on Unix)

look for the line set JAVA_OPTS, (or just JAVA_OPTS on Unix) at the end of that line add -Xmx512m. Change the number to the amount of memory you want to allocate to JBoss.

If you are using a custom script to start your jboss instance, you can add the set JAVA_OPTS option there as well.

Add Items to ListView - Android

ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);

Try it like this

public OnClickListener moreListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        adapter = null;
        myStringArray1.add("Andrea");
        adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
        myListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }       
};

How to convert seconds to HH:mm:ss in moment.js

This is similar to the answer mplungjan referenced from another post, but more concise:

_x000D_
_x000D_
const secs = 456;_x000D_
_x000D_
const formatted = moment.utc(secs*1000).format('HH:mm:ss');_x000D_
_x000D_
document.write(formatted);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

It suffers from the same caveats, e.g. if seconds exceed one day (86400), you'll not get what you expect.

iReport not starting using JRE 8

While ireport does not officially support java8, there is a fairly simple way to make ireport (tested with ireport 5.1) work with Java 8. The problem is actually in netbeans. There is a very simple patch, assuming you don't care about the improved security in Java 8:

http://hg.netbeans.org/jet-main/diff/3238e03c676f/openide.util/src/org/openide/util/WeakListenerImpl.java

I didn't even use the exact netbeans source used by ireport. I just downloaded the latest WeakListenerImpl.java in full from the above repository, and compiled it in the ireport directory with platform9/lib/org-openide-util.jar in the compiler classpath

cd blah/blah/iReport-5.1.0
wget http://hg.netbeans.org/jet-main/raw-file/3238e03c676f/openide.util/src/org/openide/util/WeakListenerImpl.java
javac -d . -cp platform9/lib/org-openide-util.jar WeakListenerImpl.java
zip -r platform9/lib/org-openide-util.jar org

I am avoiding running eclipse just to edit jasper reports as long as I can. The netbeans based ireport is so much lighter weight. Running Eclipse is like using emacs.

Deciding between HttpClient and WebClient

Unpopular opinion from 2020:

When it comes to ASP.NET apps I still prefer WebClient over HttpClient because:

  1. The modern implementation comes with async/awaitable task-based methods
  2. Has smaller memory footprint and 2x-5x faster (other answers already mention that)
  3. It's suggested to "reuse a single instance of HttpClient for the lifetime of your application". But ASP.NET has no "lifetime of application", only lifetime of a request.

Google Maps JS API v3 - Simple Multiple Marker Example

Asynchronous version :

<script type="text/javascript">
  function initialize() {
    var locations = [
      ['Bondi Beach', -33.890542, 151.274856, 4],
      ['Coogee Beach', -33.923036, 151.259052, 5],
      ['Cronulla Beach', -34.028249, 151.157507, 3],
      ['Manly Beach', -33.80010128657071, 151.28747820854187, 2],
      ['Maroubra Beach', -33.950198, 151.259302, 1]
    ];

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 10,
      center: new google.maps.LatLng(-33.92, 151.25),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var infowindow = new google.maps.InfoWindow();

    var marker, i;

    for (i = 0; i < locations.length; i++) {  
      marker = new google.maps.Marker({
        position: new google.maps.LatLng(locations[i][1], locations[i][2]),
        map: map
      });

      google.maps.event.addListener(marker, 'click', (function(marker, i) {
        return function() {
          infowindow.setContent(locations[i][0]);
          infowindow.open(map, marker);
        }
      })(marker, i));
    }
}

function loadScript() {
  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&' +
      'callback=initialize';
  document.body.appendChild(script);
}

window.onload = loadScript;
  </script>

Send data through routing paths in Angular

There is a new method what came with Angular 7.2.0

https://angular.io/api/router/NavigationExtras#state

Send:

this.router.navigate(['action-selection'], { state: { example: 'bar' } });

Receive:

constructor(private router: Router) {
  console.log(this.router.getCurrentNavigation().extras.state.example); // should log out 'bar'
}

You can find some additional info here:

https://github.com/angular/angular/pull/27198

The link above contains this example which can be useful: https://stackblitz.com/edit/angular-bupuzn

jQuery checkbox event handling

Acknowledging the fact that the asker specifically requested jQuery and that the answer selected is correct, it should be noted that this problem doesn't actually need jQuery per say. If one desires to solve this problem without it, one can simply set the onClick attribute of the checkboxes that he or she wants to add additional functionality to, like so:

HTML:

<form id="myform">
  <input type="checkbox" name="check1" value="check1" onClick="cbChanged(this);">
  <input type="checkbox" name="check2" value="check2" onClick="cbChanged(this);">
</form>

javascript:

function cbChanged(checkboxElem) {
  if (checkboxElem.checked) {
    // Do something special
  } else {
    // Do something else
  }
}

Fiddle: http://jsfiddle.net/Y9f66/1/

Get the current file name in gulp.src()

For my case gulp-ignore was perfect. As option you may pass a function there:

function condition(file) {
 // do whatever with file.path
 // return boolean true if needed to exclude file 
}

And the task would look like this:

var gulpIgnore = require('gulp-ignore');

gulp.task('task', function() {
  gulp.src('./**/*.js')
    .pipe(gulpIgnore.exclude(condition))
    .pipe(gulp.dest('./dist/'));
});

Better way to remove specific characters from a Perl string

With a character class this big it is easier to say what you want to keep. A caret in the first position of a character class inverts its sense, so you can write

$varTemp =~ s/[^"%'+\-0-9<=>a-z_{|}]+//gi

or, using the more efficient tr

$varTemp =~ tr/"%'+\-0-9<=>A-Z_a-z{|}//cd

tr docs

How to copy file from host to container using Dockerfile

If you want to copy the current dir's contents, you can run:

docker build  -t <imagename:tag> -f- ./ < Dockerfile

Testing javascript with Mocha - how can I use console.log to debug a test?

You may have also put your console.log after an expectation that fails and is uncaught, so your log line never gets executed.

What is the bower (and npm) version syntax?

In a nutshell, the syntax for Bower version numbers (and NPM's) is called SemVer, which is short for 'Semantic Versioning'. You can find documentation for the detailed syntax of SemVer as used in Bower and NPM on the API for the semver parser within Node/npm. You can learn more about the underlying spec (which does not mention ~ or other syntax details) at semver.org.

There's a super-handy visual semver calculator you can play with, making all of this much easier to grok and test.

SemVer isn't just a syntax! It has some pretty interesting things to say about the right ways to publish API's, which will help to understand what the syntax means. Crucially:

Once you identify your public API, you communicate changes to it with specific increments to your version number. Consider a version format of X.Y.Z (Major.Minor.Patch). Bug fixes not affecting the API increment the patch version, backwards compatible API additions/changes increment the minor version, and backwards incompatible API changes increment the major version.

So, your specific question about ~ relates to that Major.Minor.Patch schema. (As does the related caret operator ^.) You can use ~ to narrow the range of versions you're willing to accept to either:

  • subsequent patch-level changes to the same minor version ("bug fixes not affecting the API"), or:
  • subsequent minor-level changes to the same major version ("backwards compatible API additions/changes")

For example: to indicate you'll take any subsequent patch-level changes on the 1.2.x tree, starting with 1.2.0, but less than 1.3.0, you could use:

"angular": "~1.2"
  or:
"angular": "~1.2.0"

This also gets you the same results as using the .x syntax:

"angular": "1.2.x"

But, you can use the tilde/~ syntax to be even more specific: if you're only willing to accept patch-level changes starting with 1.2.4, but still less than 1.3.0, you'd use:

"angular": "~1.2.4"

Moving left, towards the major version, if you use...

"angular": "~1"

... it's the same as...

"angular": "1.x"
  or:
"angular": "^1.0.0"

...and matches any minor- or patch-level changes above 1.0.0, and less than 2.0:

Note that last variation above: it's called a 'caret range'. The caret looks an awful lot like a >, so you'd be excused for thinking it means "any version greater than 1.0.0". (I've certainly slipped on that.) Nope!

Caret ranges are basically used to say that you care only about the left-most significant digit - usually the major version - and that you'll permit any minor- or patch-level changes that don't affect that left-most digit. Yet, unlike a tilde range that specifies a major version, caret ranges let you specify a precise minor/patch starting point. So, while ^1.0.0 === ~1, a caret range such as ^1.2.3 lets you say you'll take any changes >=1.2.3 && <2.0.0. You couldn't do that with a tilde range.

That all seems confusing at first, when you look at it up-close. But zoom out for a sec, and think about it this way: the caret simply lets you say that you're most concerned about whatever significant digit is left-most. The tilde lets you say you're most concerned about whichever digit is right-most. The rest is detail.

It's the expressive power of the tilde and the caret that explains why people use them much more than the simpler .x syntax: they simply let you do more. That's why you'll see the tilde used often even where .x would serve. As an example, see npm itself: its own package.json file includes lots of dependencies in ~2.4.0 format, rather than the 2.4.x format it could use. By sticking to ~, the syntax is consistent all the way down a list of 70+ versioned dependencies, regardless of which beginning patch number is acceptable.

Anyway, there's still more to SemVer, but I won't try to detail it all here. Check it out on the node semver package's readme. And be sure to use the semantic versioning calculator while you're practicing and trying to get your head around how SemVer works.


RE: Non-Consecutive Version Numbers: OP's final question seems to be about specifying non-consecutive version numbers/ranges (if I have edited it fairly). Yes, you can do that, using the common double-pipe "or" operator: ||. Like so:

"angular": "1.2 <= 1.2.9 || >2.0.0"

Make Bootstrap 3 Tabs Responsive

enter image description here

There is a new one: http://hayatbiralem.com/blog/2015/05/15/responsive-bootstrap-tabs/

And also Codepen sample available here: http://codepen.io/hayatbiralem/pen/KpzjOL

No needs plugin. It uses just a little css and jquery.

Here's a sample tabs markup:

<ul class="nav nav-tabs nav-tabs-responsive">
    <li class="active">
        <a href="#tab1" data-toggle="tab">
            <span class="text">Tab 1</span>
        </a>
    </li>
    <li class="next">
        <a href="#tab2" data-toggle="tab">
            <span class="text">Tab 2</span>
        </a>
    </li>
    <li>
        <a href="#tab3" data-toggle="tab">
            <span class="text">Tab 3</span>
        </a>
    </li>
    ...
</ul>

.. and jQuery codes are also here:

(function($) {

  'use strict';

  $(document).on('show.bs.tab', '.nav-tabs-responsive [data-toggle="tab"]', function(e) {
    var $target = $(e.target);
    var $tabs = $target.closest('.nav-tabs-responsive');
    var $current = $target.closest('li');
    var $parent = $current.closest('li.dropdown');
        $current = $parent.length > 0 ? $parent : $current;
    var $next = $current.next();
    var $prev = $current.prev();
    var updateDropdownMenu = function($el, position){
      $el
        .find('.dropdown-menu')
        .removeClass('pull-xs-left pull-xs-center pull-xs-right')
        .addClass( 'pull-xs-' + position );
    };

    $tabs.find('>li').removeClass('next prev');
    $prev.addClass('prev');
    $next.addClass('next');

    updateDropdownMenu( $prev, 'left' );
    updateDropdownMenu( $current, 'center' );
    updateDropdownMenu( $next, 'right' );
  });

})(jQuery);

Copy file remotely with PowerShell

From PowerShell version 5 onwards (included in Windows Server 2016, downloadable as part of WMF 5 for earlier versions), this is possible with remoting. The benefit of this is that it works even if, for whatever reason, you can't access shares.

For this to work, the local session where copying is initiated must have PowerShell 5 or higher installed. The remote session does not need to have PowerShell 5 installed -- it works with PowerShell versions as low as 2, and Windows Server versions as low as 2008 R2.[1]

From server A, create a session to server B:

$b = New-PSSession B

And then, still from A:

Copy-Item -FromSession $b C:\Programs\temp\test.txt -Destination C:\Programs\temp\test.txt

Copying items to B is done with -ToSession. Note that local paths are used in both cases; you have to keep track of what server you're on.


[1]: when copying from or to a remote server that only has PowerShell 2, beware of this bug in PowerShell 5.1, which at the time of writing means recursive file copying doesn't work with -ToSession, an apparently copying doesn't work at all with -FromSession.

What is the difference between a cer, pvk, and pfx file?

Windows uses .cer extension for an X.509 certificate. These can be in "binary" (ASN.1 DER), or it can be encoded with Base-64 and have a header and footer applied (PEM); Windows will recognize either. To verify the integrity of a certificate, you have to check its signature using the issuer's public key... which is, in turn, another certificate.

Windows uses .pfx for a PKCS #12 file. This file can contain a variety of cryptographic information, including certificates, certificate chains, root authority certificates, and private keys. Its contents can be cryptographically protected (with passwords) to keep private keys private and preserve the integrity of root certificates.

Windows uses .pvk for a private key file. I'm not sure what standard (if any) Windows follows for these. Hopefully they are PKCS #8 encoded keys. Emmanuel Bourg reports that these are a proprietary format. Some documentation is available.

You should never disclose your private key. These are contained in .pfx and .pvk files.

Generally, you only exchange your certificate (.cer) and the certificates of any intermediate issuers (i.e., the certificates of all of your CAs, except the root CA) with other parties.

Can I call jQuery's click() to follow an <a> link if I haven't bound an event handler to it with bind or click already?

To open hyperlink in the same tab, use:

$(document).on('click', "a.classname", function() {
    var form = $("<form></form>");
    form.attr(
    {
        id     : "formid",
        action : $(this).attr("href"),
        method : "GET",
    });

    $("body").append(form);
    $("#formid").submit();
    $("#formid").remove();
    return false;
});

Transport endpoint is not connected

So interestingly enough this error "Transport endpoint is not connected" was caused by my having more than one Veracrypt device mounted. I closed the extra device and suddenly I had access to the drive. Hmm..

Calling ASP.NET MVC Action Methods from JavaScript

You can set up your element with

value="@model.productId"

and

onclick= addToWishList(this.value);

How to replace text in a column of a Pandas dataframe?

If you only need to replace characters in one specific column, somehow regex=True and in place=True all failed, I think this way will work:

data["column_name"] = data["column_name"].apply(lambda x: x.replace("characters_need_to_replace", "new_characters"))

lambda is more like a function that works like a for loop in this scenario. x here represents every one of the entries in the current column.

The only thing you need to do is to change the "column_name", "characters_need_to_replace" and "new_characters".

How to use cURL in Java?

Curl is a non-java program and must be provided outside your Java program.

You can easily get much of the functionality using Jakarta Commons Net, unless there is some specific functionality like "resume transfer" you need (which is tedious to code on your own)

Oracle: is there a tool to trace queries, like Profiler for sql server?

Oracle, along with other databases, analyzes a given query to create an execution plan. This plan is the most efficient way of retrieving the data.

Oracle provides the 'explain plan' statement which analyzes the query but doesn't run it, instead populating a special table that you can query (the plan table).

The syntax (simple version, there are other options such as to mark the rows in the plan table with a special ID, or use a different plan table) is:

explain plan for <sql query>

The analysis of that data is left for another question, or your further research.

Getter and Setter?

In addition to the already great and respected answers in here, I would like to expand on PHP having no setters/getters.

PHP does not have getter and setter syntax. It provides subclassed or magic methods to allow "hooking" and overriding the property lookup process, as pointed out by Dave.

Magic allows us lazy programmers to do more with less code at a time at which we are actively engaged in a project and know it intimately, but usually at the expense of readability.

Performance Every unnecessary function, that results from forcing a getter/setter-like code-architecture in PHP, involves its own memory stack-frame upon invocation and is wasting CPU cycles.

Readability: The codebase incurs bloating code-lines, which impacts code-navigation as more LOC mean more scrolling,.

Preference: Personally, as my rule of thumb, I take the failure of static code analysis as a sign to avoid going down the magical road as long as obvious long-term benefits elude me at that time.

Fallacies:

A common argument is readability. For instance that $someobject->width is easier to read than $someobject->width(). However unlike a planet's circumference or width, which can be assumed to be static, an object's instance such as $someobject, which requires a width function, likely takes a measurement of the object's instance width.
Therefore readability increases mainly because of assertive naming-schemes and not by hiding the function away that outputs a given property-value.

__get / __set uses:

  • pre-validation and pre-sanitation of property values

  • strings e.g.

    "
    some {mathsobj1->generatelatex} multi
    line text {mathsobj1->latexoutput}
    with lots of variables for {mathsobj1->generatelatex}
     some reason
    "
    

    In this case generatelatex would adhere to a naming scheme of actionname + methodname

  • special, obvious cases

    $dnastringobj->homeobox($one_rememberable_parameter)->gattaca->findrelated()
    $dnastringobj->homeobox($one_rememberable_parameter)->gttccaatttga->findrelated()
    

Note: PHP chose not to implement getter/setter syntax. I am not claiming that getters/setter are generally bad.

Virtual member call in a constructor

In order to answer your question, consider this question: what will the below code print out when the Child object is instantiated?

class Parent
{
    public Parent()
    {
        DoSomething();
    }

    protected virtual void DoSomething() 
    {
    }
}

class Child : Parent
{
    private string foo;

    public Child() 
    { 
        foo = "HELLO"; 
    }

    protected override void DoSomething()
    {
        Console.WriteLine(foo.ToLower()); //NullReferenceException!?!
    }
}

The answer is that in fact a NullReferenceException will be thrown, because foo is null. An object's base constructor is called before its own constructor. By having a virtual call in an object's constructor you are introducing the possibility that inheriting objects will execute code before they have been fully initialized.

Can I call curl_setopt with CURLOPT_HTTPHEADER multiple times to set multiple headers?

Following what curl does internally for the request (via the method outlined in this answer to "Php - Debugging Curl") answers the question: No, it is not possible to use the curl_setopt call with CURLOPT_HTTPHEADER. The second call will overwrite the headers of the first call.

Instead the function needs to be called once with all headers:

$headers = array(
    'Content-type: application/xml',
    'Authorization: gfhjui',
);
curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $headers);

Related (but different) questions are:

Capturing a single image from my webcam in Java or Python

@thebjorn has given a good answer. But if you want more options, you can try OpenCV, SimpleCV.

using SimpleCV (not supported in python3.x):

from SimpleCV import Image, Camera

cam = Camera()
img = cam.getImage()
img.save("filename.jpg")

using OpenCV:

from cv2 import *
# initialize the camera
cam = VideoCapture(0)   # 0 -> index of camera
s, img = cam.read()
if s:    # frame captured without any errors
    namedWindow("cam-test",CV_WINDOW_AUTOSIZE)
    imshow("cam-test",img)
    waitKey(0)
    destroyWindow("cam-test")
    imwrite("filename.jpg",img) #save image

using pygame:

import pygame
import pygame.camera

pygame.camera.init()
pygame.camera.list_cameras() #Camera detected or not
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
img = cam.get_image()
pygame.image.save(img,"filename.jpg")

Install OpenCV:

install python-opencv bindings, numpy

Install SimpleCV:

install python-opencv, pygame, numpy, scipy, simplecv

get latest version of SimpleCV

Install pygame:

install pygame

How to get SLF4J "Hello World" working with log4j?

I had the same problem. I called my own custom logger in the log4j.properties file from code when using log4j api directly. If you are using the slf4j api calls, you are probably using the default root logger so you must configure that to be associated with an appender in the log4j.properties:


    # Set root logger level to DEBUG and its only appender to A1.
    log4j.rootLogger=DEBUG, A1

    # A1 is set to be a ConsoleAppender.
    log4j.appender.A1=org.apache.log4j.ConsoleAppender

Vlookup referring to table data in a different sheet

There might be something wrong with your formula if you are looking from another sheet maybe you have to change Sheet1 to Sheet2 ---> =VLOOKUP(M3,Sheet2!$A$2:$Q$47,13,FALSE) --- Where Sheet2 is your table array

How to create a inset box-shadow only on one side?

try it, maybe useful...

box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 3px #cbc9c9;
                    -webkit-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;
                    -o-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;
                    -moz-box-shadow: 0 0 0 3px rgb(255,255,255), 0 7px 5px #cbc9c9;  

above CSS cause you have a box shadow in bottom.
you can red more Here

How to open a web server port on EC2 instance

You need to configure the security group as stated by cyraxjoe. Along with that you also need to open System port. Steps to open port in windows :-

  1. On the Start menu, click Run, type WF.msc, and then click OK.
  2. In the Windows Firewall with Advanced Security, in the left pane, right-click Inbound Rules, and then click New Rule in the action pane.
  3. In the Rule Type dialog box, select Port, and then click Next.
  4. In the Protocol and Ports dialog box, select TCP. Select Specific local ports, and then type the port number , such as 8787 for the default instance. Click Next.
  5. In the Action dialog box, select Allow the connection, and then click Next.
  6. In the Profile dialog box, select any profiles that describe the computer connection environment when you want to connect , and then click Next.
  7. In the Name dialog box, type a name and description for this rule, and then click Finish.

Ref:- Microsoft Docs for port Opening

How do I control how Emacs makes backup files?

Another way of configuring backup options is via the Customize interface. Enter:

M-x customize-group

And then at the Customize group: prompt enter backup.

If you scroll to the bottom of the buffer you'll see Backup Directory Alist. Click Show Value and set the first entry of the list as follows:

Regexp matching filename: .*
Backup directory name: /path/to/your/backup/dir

Alternatively, you can turn backups off my setting Make Backup Files to off.

If you don't want Emacs to automatically edit your .emacs file you'll want to set up a customisations file.

How to set focus on an input field after rendering?

Read almost all the answer but didnt see a getRenderedComponent().props.input

Set your text input refs

this.refs.username.getRenderedComponent().props.input.onChange('');

How to get DATE from DATETIME Column in SQL?

Use Getdate()

 select sum(transaction_amount) from TransactionMaster
 where Card_No=' 123' and transaction_date =convert(varchar(10), getdate(), 102)

Open a Web Page in a Windows Batch FIle

You can use the start command to do much the same thing as ShellExecute. For example

 start "" http://www.stackoverflow.com

This will launch whatever browser is the default browser, so won't necessarily launch Internet Explorer.

jQuery load first 3 elements, click "load more" to display next 5 elements

WARNING: size() was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length instead

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
    });
});


New JS to show or hide load more and show less

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
         $('#showLess').show();
        if(x == size_li){
            $('#loadMore').hide();
        }
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
        $('#loadMore').show();
         $('#showLess').show();
        if(x == 3){
            $('#showLess').hide();
        }
    });
});

CSS

#showLess {
    color:red;
    cursor:pointer;
    display:none;
}

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/

fatal: could not create work tree dir 'kivy'

This does happened also when you are cloning a repo without selecting any working directory. just make sure you did cd into your working directory and i believe it will work just fine.

How to check if a character is upper-case in Python?

You can use this code:

def is_valid(string):
    words = string.split('_')
    for word in words:
        if not word.istitle():
            return False, word
    return True, words
x="Alpha_beta_Gamma"
assert is_valid(x)==(False,'beta')
x="Alpha_Beta_Gamma"
assert is_valid(x)==(True,['Alpha', 'Beta', 'Gamma'])

This way you know if is valid and what word is wrong

Java: How to access methods from another class

I have another solution. If Alpha and Beta are your only extra class then why not make a static variable with the image of the class.

Like in Alpha class :

public class Alpha{
        public static Alpha alpha;
        public Alpha(){
                this.alpha = this;
}

Now you you can call the function in Beta class by just using these lines :

new Alpha();
Alpha.alpha.DoSomethingAlpha();

How to include duplicate keys in HashMap?

Map does not supports duplicate keys. you can use collection as value against same key.

Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value.

Documentation

you can use any kind of List or Set implementation according to your requirement.

If your values might be also duplicate you can go with ArrayList or LinkedList, in case values are unique you can use HashSet or TreeSet etc.


Also In google guava collection library Multimap is available, it is a collection that maps keys to values, similar to Map, but in which each key may be associated with multiple values. You can visualize the contents of a multimap either as a map from keys to nonempty collections of values:

a ? 1, 2
b ? 3  

Example -

ListMultimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("a", "1");
multimap.put("a", "2");
multimap.put("c", "3");

TOMCAT - HTTP Status 404

You don't have to use Tomcat installation as a server location. It is much easier just to copy the files in the ROOT folder.

Eclipse forgets to copy the default apps (ROOT, examples, etc.) when it creates a Tomcat folder inside the Eclipse workspace. Go to C:\apache-tomcat-7.0.8\webapps, R-click on the ROOT folder and copy it. Then go to your Eclipse workspace, go to the .metadata folder, and search for "wtpwebapps". You should find something like your-eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps (or ../tmp1/wtpwebapps if you already had another server registered in Eclipse). Go to the wtpwebapps folder, R-click, and paste ROOT (say "yes" if asked if you want to merge/replace folders/files). Then reload http://localhost/ to see the Tomcat welcome page.

Source: HTTP Status 404 error in tomcat

d3 add text to circle

Here is an example showing some text in circles with data from a json file: http://bl.ocks.org/4474971. Which gives the following:

enter image description here

The main idea behind this is to encapsulate the text and the circle in the same "div" as you would do in html to have the logo and the name of the company in the same div in a page header.

The main code is:

var width = 960,
    height = 500;

var svg = d3.select("body").append("svg")
    .attr("width", width)
    .attr("height", height)

d3.json("data.json", function(json) {
    /* Define the data for the circles */
    var elem = svg.selectAll("g")
        .data(json.nodes)

    /*Create and place the "blocks" containing the circle and the text */  
    var elemEnter = elem.enter()
        .append("g")
        .attr("transform", function(d){return "translate("+d.x+",80)"})

    /*Create the circle for each block */
    var circle = elemEnter.append("circle")
        .attr("r", function(d){return d.r} )
        .attr("stroke","black")
        .attr("fill", "white")

    /* Create the text for each block */
    elemEnter.append("text")
        .attr("dx", function(d){return -20})
        .text(function(d){return d.label})
})

and the json file is:

{"nodes":[
  {"x":80, "r":40, "label":"Node 1"}, 
  {"x":200, "r":60, "label":"Node 2"}, 
  {"x":380, "r":80, "label":"Node 3"}
]}

The resulting html code shows the encapsulation you want:

<svg width="960" height="500">
    <g transform="translate(80,80)">
        <circle r="40" stroke="black" fill="white"></circle>
        <text dx="-20">Node 1</text>
    </g>
    <g transform="translate(200,80)">
        <circle r="60" stroke="black" fill="white"></circle>
        <text dx="-20">Node 2</text>
    </g>
    <g transform="translate(380,80)">
        <circle r="80" stroke="black" fill="white"></circle>
        <text dx="-20">Node 3</text>
    </g>
</svg>

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

Doh! In case anyone else gets this error when trying to attach to an IIS Website.

Triple check that your hostname is correct, I had forgotten a '/' in (e.g.) http://my.testsite.com

Try this before re-installing Visual Studio like I did.. Terrible error message..

java.lang.NoClassDefFoundError: org/json/JSONObject

Add json jar to your classpath

or use java -classpath json.jar ClassName

refer this

C non-blocking keyboard input

You probably want kbhit();

//Example will loop until a key is pressed
#include <conio.h>
#include <iostream>

using namespace std;

int main()
{
    while(1)
    {
        if(kbhit())
        {
            break;
        }
    }
}

this may not work on all environments. A portable way would be to create a monitoring thread and set some flag on getch();

Eclipse: Enable autocomplete / content assist

For anyone having this problem with newer versions of Eclipse, head over to Window->Preferences->Java->Editor->Content assist->Advanced and mark Java Proposals and Chain Template Proposals as active.

Java string replace and the NUL (NULL, ASCII 0) character?

Does replacing a character in a String with a null character even work in Java? I know that '\0' will terminate a c-string.

That depends on how you define what is working. Does it replace all occurrences of the target character with '\0'? Absolutely!

String s = "food".replace('o', '\0');
System.out.println(s.indexOf('\0')); // "1"
System.out.println(s.indexOf('d')); // "3"
System.out.println(s.length()); // "4"
System.out.println(s.hashCode() == 'f'*31*31*31 + 'd'); // "true"

Everything seems to work fine to me! indexOf can find it, it counts as part of the length, and its value for hash code calculation is 0; everything is as specified by the JLS/API.

It DOESN'T work if you expect replacing a character with the null character would somehow remove that character from the string. Of course it doesn't work like that. A null character is still a character!

String s = Character.toString('\0');
System.out.println(s.length()); // "1"
assert s.charAt(0) == 0;

It also DOESN'T work if you expect the null character to terminate a string. It's evident from the snippets above, but it's also clearly specified in JLS (10.9. An Array of Characters is Not a String):

In the Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NUL character).


Would this be the culprit to the funky characters?

Now we're talking about an entirely different thing, i.e. how the string is rendered on screen. Truth is, even "Hello world!" will look funky if you use dingbats font. A unicode string may look funky in one locale but not the other. Even a properly rendered unicode string containing, say, Chinese characters, may still look funky to someone from, say, Greenland.

That said, the null character probably will look funky regardless; usually it's not a character that you want to display. That said, since null character is not the string terminator, Java is more than capable of handling it one way or another.


Now to address what we assume is the intended effect, i.e. remove all period from a string, the simplest solution is to use the replace(CharSequence, CharSequence) overload.

System.out.println("A.E.I.O.U".replace(".", "")); // AEIOU

The replaceAll solution is mentioned here too, but that works with regular expression, which is why you need to escape the dot meta character, and is likely to be slower.

How can I extract a predetermined range of lines from a text file on Unix?

sed -n '16224,16482p;16483q' filename > newfile

From the sed manual:

p - Print out the pattern space (to the standard output). This command is usually only used in conjunction with the -n command-line option.

n - If auto-print is not disabled, print the pattern space, then, regardless, replace the pattern space with the next line of input. If there is no more input then sed exits without processing any more commands.

q - Exit sed without processing any more commands or input. Note that the current pattern space is printed if auto-print is not disabled with the -n option.

and

Addresses in a sed script can be in any of the following forms:

number Specifying a line number will match only that line in the input.

An address range can be specified by specifying two addresses separated by a comma (,). An address range matches lines starting from where the first address matches, and continues until the second address matches (inclusively).

Inserting image into IPython notebook markdown

[Obsolete]

IPython/Jupyter now has support for an extension modules that can insert images via copy and paste or drag & drop.

https://github.com/ipython-contrib/IPython-notebook-extensions

The drag & drop extension seems to work in most browsers

https://github.com/ipython-contrib/IPython-notebook-extensions/tree/master/nbextensions/usability/dragdrop

But copy and paste only works in Chrome.

No tests found with test runner 'JUnit 4'

There is another chance, you might have changed Junit Test from lower version(e.g. Junit 3) to Junit 4 . Is so follow below steps:-

1. Right Click on class
2. Select Run as >> "Run Configurations"
3. Check your "Test Runner" option in new window
4. If it not same as maven change it for example change it as Junit 4.

Calculate average in java

int values[] = { 23, 1, 5, 78, 22, 4};

int sum = 0;
for (int i = 0; i < values.length; i++)
    sum += values[i];

double average = ((double) sum) / values.length;

bower proxy configuration

For info, in your .bowerrc file you can add a no-proxy attribute. I don't know since when it is supported but it works on bower 1.7.4

.bowerrc :

{
  "directory": "bower_components", 
  "proxy": "http://yourProxy:yourPort",
  "https-proxy":"http://yourProxy:yourPort",
  "no-proxy":"myserver.mydomain.com"
}

.bowerrc should be located in the root folder of your Javascript project, the folder in which you launch the bower command. You can also have it in your home folder (~/.bowerrc).

Generating a SHA-256 hash from the Linux command line

For the sha256 hash in base64, use:

echo -n foo | openssl dgst -binary -sha1 | openssl base64

Example

echo -n foo | openssl dgst -binary -sha1 | openssl base64
C+7Hteo/D9vJXQ3UfzxbwnXaijM=

Windows path in Python

Use PowerShell

In Windows, you can use / in your path just like Linux or macOS in all places as long as you use PowerShell as your command-line interface. It comes pre-installed on Windows and it supports many Linux commands like ls command.

If you use Windows Command Prompt (the one that appears when you type cmd in Windows Start Menu), you need to specify paths with \ just inside it. You can use / paths in all other places (code editor, Python interactive mode, etc.).

Graphical DIFF programs for linux

Emacs comes with Ediff.

Here is what Ediff looks like EdiffScreenshot

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

I had a similar error with Tomcat 8.0 / MySQL . Changing the jdbc url value from localhost to 127.0.0.1 resolved the issue.

Why am I getting error CS0246: The type or namespace name could not be found?

I had a similar problem after first pulling and starting a new solution. It was fixed in visual studio by first cleaning the project. Then restoring the packages. When I built again, there were no more type or namespace errors.

How to instantiate a File object in JavaScript?

Now it's possible and supported by all major browsers: https://developer.mozilla.org/en-US/docs/Web/API/File/File

var file = new File(["foo"], "foo.txt", {
  type: "text/plain",
});

I can not find my.cnf on my windows computer

To answer your question, on Windows, the my.cnf file may be called my.ini. MySQL looks for it in the following locations (in this order):

  • %PROGRAMDATA%\MySQL\MySQL Server 5.7\my.ini, %PROGRAMDATA%\MySQL\MySQL Server 5.7\my.cnf
  • %WINDIR%\my.ini, %WINDIR%\my.cnf
  • C:\my.ini, C:\my.cnf
  • INSTALLDIR\my.ini, INSTALLDIR\my.cnf

See also http://dev.mysql.com/doc/refman/5.7/en/option-files.html

Then you can edit the config file and add an entry like this:

[mysqld]
skip-grant-tables

Then restart the MySQL Service and you can log in and do what you need to do. Of course you want to disable that entry in the config file as soon as possible!

See also http://dev.mysql.com/doc/refman/5.7/en/resetting-permissions.html

Check if string is upper, lower, or mixed case in Python

I want to give a shoutout for using re module for this. Specially in the case of case sensitivity.

We use the option re.IGNORECASE while compiling the regex for use of in production environments with large amounts of data.

>>> import re
>>> m = ['isalnum','isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'ISALNUM', 'ISALPHA', 'ISDIGIT', 'ISLOWER', 'ISSPACE', 'ISTITLE', 'ISUPPER']
>>>
>>>
>>> pattern = re.compile('is')
>>>
>>> [word for word in m if pattern.match(word)]
['isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper']

However try to always use the in operator for string comparison as detailed in this post

faster-operation-re-match-or-str

Also detailed in the one of the best books to start learning python with

idiomatic-python

Is there a way to represent a directory tree in a Github README.md?

I made a node module to automate this task: mddir

Usage

node mddir "../relative/path/"

To install: npm install mddir -g

To generate markdown for current directory: mddir

To generate for any absolute path: mddir /absolute/path

To generate for a relative path: mddir ~/Documents/whatever.

The md file gets generated in your working directory.

Currently ignores node_modules, and .git folders.

Troubleshooting

If you receive the error 'node\r: No such file or directory', the issue is that your operating system uses different line endings and mddir can't parse them without you explicitly setting the line ending style to Unix. This usually affects Windows, but also some versions of Linux. Setting line endings to Unix style has to be performed within the mddir npm global bin folder.

Line endings fix

Get npm bin folder path with:

npm config get prefix

Cd into that folder

brew install dos2unix

dos2unix lib/node_modules/mddir/src/mddir.js

This converts line endings to Unix instead of Dos

Then run as normal with: node mddir "../relative/path/".

Example generated markdown file structure 'directoryList.md'

    |-- .bowerrc
    |-- .jshintrc
    |-- .jshintrc2
    |-- Gruntfile.js
    |-- README.md
    |-- bower.json
    |-- karma.conf.js
    |-- package.json
    |-- app
        |-- app.js
        |-- db.js
        |-- directoryList.md
        |-- index.html
        |-- mddir.js
        |-- routing.js
        |-- server.js
        |-- _api
            |-- api.groups.js
            |-- api.posts.js
            |-- api.users.js
            |-- api.widgets.js
        |-- _components
            |-- directives
                |-- directives.module.js
                |-- vendor
                    |-- directive.draganddrop.js
            |-- helpers
                |-- helpers.module.js
                |-- proprietary
                    |-- factory.actionDispatcher.js
            |-- services
                |-- services.cardTemplates.js
                |-- services.cards.js
                |-- services.groups.js
                |-- services.posts.js
                |-- services.users.js
                |-- services.widgets.js
        |-- _mocks
            |-- mocks.groups.js
            |-- mocks.posts.js
            |-- mocks.users.js
            |-- mocks.widgets.js

C++ Convert string (or char*) to wstring (or wchar_t*)

If you have QT and if you are lazy to implement a function and stuff you can use

std::string str;
QString(str).toStdWString()

AngularJS - pass function to directive

use dash and lower case for attribute name ( like other answers said ) :

 <test color1="color1" update-fn="updateFn()"></test>

And use "=" instead of "&" in directive scope:

 scope: { updateFn: '='}

Then you can use updateFn like any other function:

 <button ng-click='updateFn()'>Click</button>

There you go!

how to play video from url

Try Exoplayer2

https://github.com/google/ExoPlayer

It is highly customisable

    private void initializePlayer() {
         player = ExoPlayerFactory.newSimpleInstance(
             new DefaultRenderersFactory(this),
             new DefaultTrackSelector(), new DefaultLoadControl());

         playerView.setPlayer(player);

         player.setPlayWhenReady(playWhenReady);
         player.seekTo(currentWindow, playbackPosition);

Uri uri = Uri.parse(getString(R.string.media_url_mp3));
     MediaSource mediaSource = buildMediaSource(uri);
     player.prepare(mediaSource, true, false);
    }

private MediaSource buildMediaSource(Uri uri) {
  return new ExtractorMediaSource.Factory(
      new DefaultHttpDataSourceFactory("exoplayer-codelab")).
      createMediaSource(uri);
}

@Override
public void onStart() {
 super.onStart();
 if (Util.SDK_INT > 23) {
   initializePlayer();
 }
}

Check this url for more details

https://codelabs.developers.google.com/codelabs/exoplayer-intro/#2

Convert string to decimal number with 2 decimal places in Java

This line is your problem:

litersOfPetrol = Float.parseFloat(df.format(litersOfPetrol));

There you formatted your float to string as you wanted, but but then that string got transformed again to a float, and then what you printed in stdout was your float that got a standard formatting. Take a look at this code

import java.text.DecimalFormat;

String stringLitersOfPetrol = "123.00";
System.out.println("string liters of petrol putting in preferences is "+stringLitersOfPetrol);
Float litersOfPetrol=Float.parseFloat(stringLitersOfPetrol);
DecimalFormat df = new DecimalFormat("0.00");
df.setMaximumFractionDigits(2);
stringLitersOfPetrol = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : "+stringLitersOfPetrol);

And by the way, when you want to use decimals, forget the existence of double and float as others suggested and just use BigDecimal object, it will save you a lot of headache.

MVC Razor view nested foreach's model

Another much simpler possibility is that one of your property names is wrong (probably one you just changed in the class). This is what it was for me in RazorPages .NET Core 3.

Split a large pandas dataframe

you can use list comprehensions to do this in a single line

n = 4
chunks = [df[i:i+n] for i in range(0,df.shape[0],n)]

Visual Studio 2012 Web Publish doesn't copy files

Check your current project that whether you have made back copy with same class name and different page name (Class name will inherit copied file). Ultimately that will confuse the compiler!!!

CodeFile="Consolidated.aspx.vb" Inherits="Consolidated

error: Error parsing XML: not well-formed (invalid token) ...?

I tried everything on my end and ended up with the following.

I had the first line as:

<?xmlversion="1.0"encoding="utf-8"?>

And I was missing two spaces there, and it should be:

<?xml version="1.0" encoding="utf-8"?>

Before the version and before the encoding there should be a space.

Are there pointers in php?

To answer the second part of your question - there are no pointers in PHP.

When working with objects, you generally pass by reference rather than by value - so in some ways this operates like a pointer, but is generally completely transparent.

This does depend on the version of PHP you are using.

Reload content in modal (twitter bootstrap)

var $table = $('#myTable2');
$table.bootstrapTable('destroy');

Worked for me

Convert java.util.Date to java.time.LocalDate

What's wrong with this 1 simple line?

new LocalDateTime(new Date().getTime()).toLocalDate();

How to recover corrupted Eclipse workspace?

None of the above worked for me. But what actually worked was deleting all *.snap files from my workspace. This also preserves almost all settings including imported projects. Make sure to back up the workspace before trying it though!!!

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

Returning pointer from a function

To my knowledge the use of the keyword new, does relatively the same thing as malloc(sizeof identifier). The code below demonstrates how to use the keyword new.

    void main(void){
        int* test;
        test = tester();
        printf("%d",*test);
        system("pause");
    return;
}
    int* tester(void){
        int *retMe;
        retMe = new int;//<----Here retMe is getting malloc for integer type
        *retMe = 12;<---- Initializes retMe... Note * dereferences retMe 
    return retMe;
}

How to get MD5 sum of a string using python?

You can Try with

#python3
import hashlib
rawdata = "put your data here"
sha = hashlib.sha256(str(rawdata).encode("utf-8")).hexdigest() #For Sha256 hash
print(sha)
mdpass = hashlib.md5(str(sha).encode("utf-8")).hexdigest() #For MD5 hash
print(mdpass)

opening html from google drive

  1. Create a new folder in Drive and share it as "Public on the web."
  2. Upload your HTML, JS & CSS files to this folder.
  3. Open the HTML file & you will see "Preview" button in the toolbar.
  4. Share the URL that looks like www.googledrive.com/host/... from the preview window and anyone can view your web page.

Moment.js - tomorrow, today and yesterday

You can use .add() and .subtract() method to get yesterday and tomorrow date. Then use format method to get only date .format("D/M/Y"), D stand for Day, M for Month, Y for Year. Check in Moment Docs

 let currentMilli = Date.now()
 let today = Moment(currentMilli).format("D/M/Y");
 let tomorrow = Moment(currentMilli).add(1, 'days').format("D/M/Y");
 let yesterday = Moment(currentMilli).subtract(1, 'days').format("D/M/Y");

Result will be:

Current Milli - 1576693800000
today - 19/12/2019
tomorrow - 18/12/2019
yesterday - 18/12/2019

SQL Server: Examples of PIVOTing String data

If you specifically want to use the SQL Server PIVOT function, then this should work, assuming your two original columns are called act and cmd. (Not that pretty to look at though.)

SELECT act AS 'Action', [View] as 'View', [Edit] as 'Edit'
FROM (
    SELECT act, cmd FROM data
) AS src
PIVOT (
    MAX(cmd) FOR cmd IN ([View], [Edit])
) AS pvt

The target ... overrides the `OTHER_LDFLAGS` build setting defined in `Pods/Pods.xcconfig

I've seen these 3 errors for pod command in terminal

pod install

[!] The MY_APP [Debug/Release] target overrides the HEADER_SEARCH_PATHS ...
[!] The MY_APP [Debug/Release] target overrides the OTHER_LDFLAGS ...
[!] The MY_APP [Debug/Release] target overrides the GCC_PREPROCESSOR_DEFINITIONS ...

All these 3 errors would be gone by adding $(inherited) to

  1. Header Search Paths
  2. Other Linker Flags
  3. Preprocessor Macros

in Project -> Target -> Build Settings

And now the command would run without giving any errors

pod install

How can I replace text with CSS?

This isn't really possible without tricks. Here is a way that works by replacing the text with an image of text.

.pvw-title{
    text-indent: -9999px;
    background-image: url(text_image.png)
}

This type of thing is typically done with JavaScript. Here is how it can be done with jQuery:

$('.pvw-title').text('new text');

Highest Salary in each department

Here is a way to get maximum values and names on any version of SQL.

Test Data:

CREATE TABLE EmpDetails(DeptID VARCHAR(10), EmpName VARCHAR(10), Salary DECIMAL(8,2))
INSERT INTO EmpDetails VALUES('Engg','Sam',1000)
INSERT INTO EmpDetails VALUES('Engg','Smith',2000)
INSERT INTO EmpDetails VALUES('HR','Denis',1500)
INSERT INTO EmpDetails VALUES('HR','Danny',3000)
INSERT INTO EmpDetails VALUES('IT','David',2000)
INSERT INTO EmpDetails VALUES('IT','John',3000)

Example:

SELECT ed.DeptID
      ,ed.EmpName
      ,ed.Salary
FROM (SELECT DeptID, MAX(Salary) MaxSal
      FROM EmpDetails
      GROUP BY DeptID)AS empmaxsal
INNER JOIN EmpDetails ed
  ON empmaxsal.DeptID = ed.DeptID
 AND empmaxsal.MaxSal = ed.Salary

Not the most elegant, but it works.

Command to delete all pods in all kubernetes namespaces

kubectl delete daemonsets,replicasets,services,deployments,pods,rc --all

to get rid of them pesky replication controllers too.

Regex number between 1 and 100

There are many options how to write a regex pattern for that

  • ^(?:(?!0)\d{1,2}|100)$
  • ^(?:[1-9]\d?|100)$
  • ^(?!0)(?=100$|..$|.$)\d+$

How to copy an object in Objective-C

As always with reference types, there are two notions of "copy". I'm sure you know them, but for completeness.

  1. A bitwise copy. In this, we just copy the memory bit for bit - this is what NSCopyObject does. Nearly always, it's not what you want. Objects have internal state, other objects, etc, and often make assumptions that they're the only ones holding references to that data. Bitwise copies break this assumption.
  2. A deep, logical copy. In this, we make a copy of the object, but without actually doing it bit by bit - we want an object that behaves the same for all intents and purposes, but isn't (necessarily) a memory-identical clone of the original - the Objective C manual calls such an object "functionally independent" from it's original. Because the mechanisms for making these "intelligent" copies varies from class to class, we ask the objects themselves to perform them. This is the NSCopying protocol.

You want the latter. If this is one of your own objects, you need simply adopt the protocol NSCopying and implement -(id)copyWithZone:(NSZone *)zone. You're free to do whatever you want; though the idea is you make a real copy of yourself and return it. You call copyWithZone on all your fields, to make a deep copy. A simple example is

@interface YourClass : NSObject <NSCopying> 
{
   SomeOtherObject *obj;
}

// In the implementation
-(id)copyWithZone:(NSZone *)zone
{
  // We'll ignore the zone for now
  YourClass *another = [[YourClass alloc] init];
  another.obj = [obj copyWithZone: zone];

  return another;
}

How to make modal dialog in WPF?

Window.Show will show the window, and continue execution -- it's a non-blocking call.

Window.ShowDialog will block the calling thread (kinda [1]), and show the dialog. It will also block interaction with the parent/owning window. When the dialog is dismissed (for whatever reason), ShowDialog will return to the caller, and will allow you to access DialogResult (if you want it).

[1] It will keep the dispatcher pumping by pushing a dispatcher frame onto the WPF dispatcher. This will cause the message pump to keep pumping.

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

@NamedQuery(
  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

How to add additional libraries to Visual Studio project?

Without knowing your compiler, no one can give you specific, step by step instructions, but the basic procedure is as follows:

  1. Specify the path which should be searched in order to find the actual library (usually under Library Search Paths, Library Directories, etc. in the properties page)

  2. Under linker options, specify the actual name of the library. In VS, you would write Allegro.lib (or whatever it is), on Linux you usually just write Allegro (prefixes/suffixes are added automatically in most cases). This is usually under "Libraries->Input", just "Libraries", or something similar.

  3. Ensure that you have included the headers for the library and make sure that they can be found (similar process to that listed in step #1 and #2). If it is a static library, you should be good; if it's a DLL, you need to copy it in your project.

  4. Mash the build button.

How to find array / dictionary value using key?

It looks like you're writing PHP, in which case you want:

<?
$arr=array('us'=>'United', 'ca'=>'canada');
$key='ca';
echo $arr[$key];
?>

Notice that the ('us'=>'United', 'ca'=>'canada') needs to be a parameter to the array function in PHP.

Most programming languages that support associative arrays or dictionaries use arr['key'] to retrieve the item specified by 'key'

For instance:

Ruby

ruby-1.9.1-p378 > h = {'us' => 'USA', 'ca' => 'Canada' }
 => {"us"=>"USA", "ca"=>"Canada"} 
ruby-1.9.1-p378 > h['ca']
 => "Canada" 

Python

>>> h = {'us':'USA', 'ca':'Canada'}
>>> h['ca']
'Canada'

C#

class P
{
    static void Main()
    {
        var d = new System.Collections.Generic.Dictionary<string, string> { {"us", "USA"}, {"ca", "Canada"}};
        System.Console.WriteLine(d["ca"]);
    }
}

Lua

t = {us='USA', ca='Canada'}
print(t['ca'])
print(t.ca) -- Lua's a little different with tables

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

You have a view model to which your view is strongly typed => use strongly typed helpers:

<%= Html.DropDownListFor(
    x => x.SelectedAccountId, 
    new SelectList(Model.Accounts, "Value", "Text")
) %>

Also notice that I use a SelectList for the second argument.

And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:

public ActionResult AccountTransaction()
{
    var accounts = Services.AccountServices.GetAccounts(false);
    var viewModel = new AccountTransactionView
    {
        Accounts = accounts.Select(a => new SelectListItem
        {
            Text = a.Description,
            Value = a.AccountId.ToString()
        })
    };
    return View(viewModel);
}

7-zip commandline

In this 7-zip forum thread, in which many people express their desire for this feature, 7-zip's developer Igor points to the FAQ question titled "How can I store full path of file in archive?" to achieve a similar outcome.

In short:

  • separate files by volume (one list for files on C:\, one for D:\, etc)
  • then for each volume's list of files,
    1. chdir to the root directory of the appropriate volume (eg, cd /d C:\)
    2. create a file listing with paths relative to the volume's root directory (eg, C:\Foo\Bar becomes Foo\Bar)
    3. perform 7z a archive.7z @filelist as before with this new file list
    4. when extracting with full paths, make sure to chdir to the appropriate volume's root directory first

T-test in Pandas

I simplify the code a little bit.

from scipy.stats import ttest_ind
ttest_ind(*my_data.groupby('Category')['value'].apply(lambda x:list(x)))

CSS Classes & SubClasses

do you want to force only children to be selected? http://css.maxdesign.com.au/selectutorial/selectors_child.htm

.area1
{
        border:1px solid black;
}
.area1>.item
{
    color:red;
}
.area2
{
    border:1px solid blue;
}
.area2>.item
{
    color:blue;
}

Sending Windows key using SendKeys

SetForegroundWindow( /* window to gain focus */ );
SendKeys.SendWait("^{ESC}"); // ^{ESC} is code for ctrl + esc which mimics the windows key.

C++ error: undefined reference to 'clock_gettime' and 'clock_settime'

example:

c++ -Wall filefork.cpp -lrt -O2

For gcc version 4.6.1, -lrt must be after filefork.cpp otherwise you get a link error.

Some older gcc version doesn't care about the position.

How to extract the decimal part from a floating point number in C?

Suppose A is your integer then (int)A, means casting the number to an integer and will be the integer part, the other is (A - (int)A)*10^n, here n is the number of decimals to keep.

How to list only the file names that changed between two commits?

It seems that no one has mentioned the switch --stat:

$ git diff --stat HEAD~5 HEAD
 .../java/org/apache/calcite/rex/RexSimplify.java   | 50 +++++++++++++++++-----
 .../apache/calcite/sql/fun/SqlTrimFunction.java    |  2 +-
 .../apache/calcite/sql2rel/SqlToRelConverter.java  | 16 +++++++
 .../org/apache/calcite/util/SaffronProperties.java | 19 ++++----
 .../org/apache/calcite/test/RexProgramTest.java    | 24 +++++++++++
 .../apache/calcite/test/SqlToRelConverterTest.java |  8 ++++
 .../apache/calcite/test/SqlToRelConverterTest.xml  | 15 +++++++
 pom.xml                                            |  2 +-
 .../apache/calcite/adapter/spark/SparkRules.java   |  7 +--
 9 files changed, 117 insertions(+), 26 deletions(-)

There are also --numstat

$ git diff --numstat HEAD~5 HEAD
40      10      core/src/main/java/org/apache/calcite/rex/RexSimplify.java
1       1       core/src/main/java/org/apache/calcite/sql/fun/SqlTrimFunction.java
16      0       core/src/main/java/org/apache/calcite/sql2rel/SqlToRelConverter.java
8       11      core/src/main/java/org/apache/calcite/util/SaffronProperties.java
24      0       core/src/test/java/org/apache/calcite/test/RexProgramTest.java
8       0       core/src/test/java/org/apache/calcite/test/SqlToRelConverterTest.java
15      0       core/src/test/resources/org/apache/calcite/test/SqlToRelConverterTest.xml
1       1       pom.xml
4       3       spark/src/main/java/org/apache/calcite/adapter/spark/SparkRules.java

and --shortstat

$ git diff --shortstat HEAD~5 HEAD
9 files changed, 117 insertions(+), 26 deletions(-)

How to read a value from the Windows registry

Here is some pseudo-code to retrieve the following:

  1. If a registry key exists
  2. What the default value is for that registry key
  3. What a string value is
  4. What a DWORD value is

Example code:

Include the library dependency: Advapi32.lib

HKEY hKey;
LONG lRes = RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Perl", 0, KEY_READ, &hKey);
bool bExistsAndSuccess (lRes == ERROR_SUCCESS);
bool bDoesNotExistsSpecifically (lRes == ERROR_FILE_NOT_FOUND);
std::wstring strValueOfBinDir;
std::wstring strKeyDefaultValue;
GetStringRegKey(hKey, L"BinDir", strValueOfBinDir, L"bad");
GetStringRegKey(hKey, L"", strKeyDefaultValue, L"bad");

LONG GetDWORDRegKey(HKEY hKey, const std::wstring &strValueName, DWORD &nValue, DWORD nDefaultValue)
{
    nValue = nDefaultValue;
    DWORD dwBufferSize(sizeof(DWORD));
    DWORD nResult(0);
    LONG nError = ::RegQueryValueExW(hKey,
        strValueName.c_str(),
        0,
        NULL,
        reinterpret_cast<LPBYTE>(&nResult),
        &dwBufferSize);
    if (ERROR_SUCCESS == nError)
    {
        nValue = nResult;
    }
    return nError;
}


LONG GetBoolRegKey(HKEY hKey, const std::wstring &strValueName, bool &bValue, bool bDefaultValue)
{
    DWORD nDefValue((bDefaultValue) ? 1 : 0);
    DWORD nResult(nDefValue);
    LONG nError = GetDWORDRegKey(hKey, strValueName.c_str(), nResult, nDefValue);
    if (ERROR_SUCCESS == nError)
    {
        bValue = (nResult != 0) ? true : false;
    }
    return nError;
}


LONG GetStringRegKey(HKEY hKey, const std::wstring &strValueName, std::wstring &strValue, const std::wstring &strDefaultValue)
{
    strValue = strDefaultValue;
    WCHAR szBuffer[512];
    DWORD dwBufferSize = sizeof(szBuffer);
    ULONG nError;
    nError = RegQueryValueExW(hKey, strValueName.c_str(), 0, NULL, (LPBYTE)szBuffer, &dwBufferSize);
    if (ERROR_SUCCESS == nError)
    {
        strValue = szBuffer;
    }
    return nError;
}

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

Detect Scroll Up & Scroll down in ListView

            ListView listView = getListView();
            listView.setOnScrollListener(new OnScrollListener() {

                @Override
                public void onScrollStateChanged(AbsListView view, int scrollState) {

                    view.setOnTouchListener(new OnTouchListener() {
                        private float mInitialX;
                        private float mInitialY;

                        @Override
                        public boolean onTouch(View v, MotionEvent event) {
                            switch (event.getAction()) {
                                case MotionEvent.ACTION_DOWN:
                                    mInitialX = event.getX();
                                    mInitialY = event.getY();
                                    return true;
                                case MotionEvent.ACTION_MOVE:
                                    final float x = event.getX();
                                    final float y = event.getY();
                                    final float yDiff = y - mInitialY;
                                    if (yDiff > 0.0) {
                                        Log.d(tag, "SCROLL DOWN");
                                        scrollDown = true;
                                        break;

                                    } else if (yDiff < 0.0) {
                                        Log.d(tag, "SCROLL up");
                                        scrollDown = true;
                                        break;

                                    }
                                    break;
                            }
                            return false;
                        }
                    });

Converting a double to an int in Javascript without rounding

I find the "parseInt" suggestions to be pretty curious, because "parseInt" operates on strings by design. That's why its name has the word "parse" in it.

A trick that avoids a function call entirely is

var truncated = ~~number;

The double application of the "~" unary operator will leave you with a truncated version of a double-precision value. However, the value is limited to 32 bit precision, as with all the other JavaScript operations that implicitly involve considering numbers to be integers (like array indexing and the bitwise operators).

edit — In an update quite a while later, another alternative to the ~~ trick is to bitwise-OR the value with zero:

var truncated = number|0;

How can I hide a TD tag using inline JavaScript or CSS?

.hide{

visibility: hidden

}

<td class="hide"/>

Edit- Just for you

The difference between display and visibility is this.

"display": has many properties or values, but the ones you're focused on are "none" and "block". "none" is like a hide value, and "block" is like show. If you use the "none" value you will totally hide what ever html tag you have applied this css style. If you use "block" you will see the html tag and it's content. very simple.

"visibility": has many values, but we want to know more about the "hidden" and "visible" values. "hidden" will work in the same way as the "block" value for display, but this will hide tag and it's content, but it will not hide the phisical space of that tag. For example, if you have a couple of text lines, then and image (picture) and then a table with three columns and two rows with icons and text. Now if you apply the visibility css with the hidden value to the image, the image will disappear but the space the image was using will remaing in it's place, in other words, you will end with a big space (hole) between the text and the table. Now if you use the "visible" value your target tag and it's elements will be visible again.

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

Since it sounds like you've tried many different potentional solutions, you'll probably have to do this the long methodical way now.

Create a new blank workbook. Then piece by piece copy your old workbook into it. Add a reference, write a little bit of code to test it. Ensure it compiles, ensure it runs. Add a sub or function, again, write a little test sub to run it, also ensure it compiles. Repeat this process slowly adding and testing everything.

You can speed this up a bit by first trying larger chunks, then when you find one that triggers the problem, remove it and break it into smaller peices for testing.

Either you will find the offender, or you'll have a new workbook that magically does not have the problem. The latter would be due to some sort of hidden corruption in the workbook file, probably in the binary vbproject part.

Welcome to the world of debugging without debuggers or other helpful tools to do the heavy lifting for you!

How to override equals method in Java

@Override
public boolean equals(Object that){
  if(this == that) return true;//if both of them points the same address in memory

  if(!(that instanceof People)) return false; // if "that" is not a People or a childclass

  People thatPeople = (People)that; // than we can cast it to People safely

  return this.name.equals(thatPeople.name) && this.age == thatPeople.age;// if they have the same name and same age, then the 2 objects are equal unless they're pointing to different memory adresses
}

Why use Redux over Facebook Flux?

According to this article: https://medium.freecodecamp.org/a-realworld-comparison-of-front-end-frameworks-with-benchmarks-2019-update-4be0d3c78075

You better use MobX to manage the data in your app to get better performance, not Redux.

How to continue a Docker container which has exited

If you want to continue exactly one Docker container with a known name:

docker start  `docker ps -a -q --filter "name=elas"`

How do I make an image smaller with CSS?

You can resize images using CSS just fine if you're modifying an image tag:

<img src="example.png" style="width:2em; height:3em;" />

You cannot scale a background-image property using CSS2, although you can try the CSS3 property background-size.

What you can do, on the other hand, is to nest an image inside a span. See the answer to this question: Stretch and scale CSS background

How do I make XAML DataGridColumns fill the entire DataGrid?

Make sure your DataGrid has Width set to something like {Binding Path=ActualWidth, RelativeSource={RelativeSource Mode=FindAncestor,AncestorType=Window,AncestorLevel=1}}.

Like that, your setting of Width="*" attribute on DataGrid.Columns/DataGridXXXXColumn elements should work.

How to validate date with format "mm/dd/yyyy" in JavaScript?

var date = new Date(date_string)

returns the literal 'Invalid Date' for any invalid date_string.

Note: Please see the comment's below.

How to know the git username and email saved during configuration?

Add my two cents here. If you want to get user.name or user.email only without verbose output.

On liunx, type git config --list | grep user.name.

On windows, type git config --list | findstr user.name.

This will give you user.name only.

Using setImageDrawable dynamically to set image in an ImageView

Try this,

int id = getResources().getIdentifier("yourpackagename:drawable/" + StringGenerated, null, null);

This will return the id of the drawable you want to access... then you can set the image in the imageview by doing the following

imageview.setImageResource(id);

How to create RecyclerView with multiple view type?

following Anton's solution, come up with this ViewHolder which holds/handles/delegates different type of layouts. But not sure if the replacing new layout would work when the recycling view's ViewHolder is not type of the data roll in.

So basically, onCreateViewHolder(ViewGroup parent, int viewType) is only called when new view layout is needed;

getItemViewType(int position) will be called for the viewType;

onBindViewHolder(ViewHolder holder, int position) is always called when recycling the view (new data is brought in and try to display with that ViewHolder).

So when onBindViewHolder is called it needs to put in the right view layout and update the ViewHolder.

Is the way correct to replacing the view layout for that ViewHolder to be brought in, or any problem? Appreciate any comment!

public int getItemViewType(int position) {
    TypedData data = mDataSource.get(position);
    return data.type;
}

public ViewHolder onCreateViewHolder(ViewGroup parent, 
    int viewType) {
    return ViewHolder.makeViewHolder(parent, viewType);
}

public void onBindViewHolder(ViewHolder holder, 
    int position) {
    TypedData data = mDataSource.get(position);
    holder.updateData(data);
}

///
public static class ViewHolder extends 
    RecyclerView.ViewHolder {

    ViewGroup mParentViewGroup;
    View mCurrentViewThisViewHolderIsFor;
    int mDataType;

    public TypeOneViewHolder mTypeOneViewHolder;
    public TypeTwoViewHolder mTypeTwoViewHolder;

    static ViewHolder makeViewHolder(ViewGroup vwGrp, 
        int dataType) {
        View v = getLayoutView(vwGrp, dataType);
        return new ViewHolder(vwGrp, v, viewType);
    }

    static View getLayoutView(ViewGroup vwGrp, 
        int dataType) {
        int layoutId = getLayoutId(dataType);
        return LayoutInflater.from(vwGrp.getContext())
                             .inflate(layoutId, null);
    }

    static int getLayoutId(int dataType) {
        if (dataType == TYPE_ONE) {
            return R.layout.type_one_layout;
        } else if (dataType == TYPE_TWO) {
            return R.layout.type_two_layout;
        }
    }

    public ViewHolder(ViewGroup vwGrp, View v, 
        int dataType) {
        super(v);
        mDataType = dataType;
        mParentViewGroup = vwGrp;
        mCurrentViewThisViewHolderIsFor = v;

        if (data.type == TYPE_ONE) {
            mTypeOneViewHolder = new TypeOneViewHolder(v);
        } else if (data.type == TYPE_TWO) {
            mTypeTwoViewHolder = new TypeTwoViewHolder(v);
        }
    }

    public void updateData(TypeData data) {
        mDataType = data.type;
        if (data.type == TYPE_ONE) {
            mTypeTwoViewHolder = null;
            if (mTypeOneViewHolder == null) {
                View newView = getLayoutView(mParentViewGroup,
                               data.type);

                /**
                 *  how to replace new view with 
                    the view in the parent 
                    view container ???
                 */
                replaceView(mCurrentViewThisViewHolderIsFor, 
                            newView);
                mCurrentViewThisViewHolderIsFor = newView;

                mTypeOneViewHolder = 
                    new TypeOneViewHolder(newView);
            }
            mTypeOneViewHolder.updateDataTypeOne(data);

        } else if (data.type == TYPE_TWO){
            mTypeOneViewHolder = null;
            if (mTypeTwoViewHolder == null) {
                View newView = getLayoutView(mParentViewGroup, 
                               data.type);

                /**
                 *  how to replace new view with 
                    the view in the parent view 
                    container ???
                 */
                replaceView(mCurrentViewThisViewHolderIsFor, 
                            newView);
                mCurrentViewThisViewHolderIsFor = newView;

                mTypeTwoViewHolder = 
                    new TypeTwoViewHolder(newView);
            }
            mTypeTwoViewHolder.updateDataTypeOne(data);
        }
    }
}

public static void replaceView(View currentView, 
    View newView) {
    ViewGroup parent = (ViewGroup)currentView.getParent();
    if(parent == null) {
        return;
    }
    final int index = parent.indexOfChild(currentView);
    parent.removeView(currentView);
    parent.addView(newView, index);
}

Edit: ViewHolder has member mItemViewType to hold the view

Edit: looks like in onBindViewHolder(ViewHolder holder, int position) the ViewHolder passed in has been picked up (or created) by looked at getItemViewType(int position) to make sure it is a match, so may not need to worry there that ViewHolder's type does not match the data[position]'s type. Does anyone knows more how the ViewHolder in the onBindViewHolder() is picked up?

Edit: Looks like The recycle ViewHolder is picked by type, so no warrior there.

Edit: http://wiresareobsolete.com/2014/09/building-a-recyclerview-layoutmanager-part-1/ answers this question.

It gets the recycle ViewHolder like:

holder = getRecycledViewPool().getRecycledView(mAdapter.getItemViewType(offsetPosition));

or create new one if not find recycle ViewHolder of right type.

public ViewHolder getRecycledView(int viewType) {
        final ArrayList<ViewHolder> scrapHeap = mScrap.get(viewType);
        if (scrapHeap != null && !scrapHeap.isEmpty()) {
            final int index = scrapHeap.size() - 1;
            final ViewHolder scrap = scrapHeap.get(index);
            scrapHeap.remove(index);
            return scrap;
        }
        return null;
    }

View getViewForPosition(int position, boolean dryRun) {
    ......

    if (holder == null) {
            final int offsetPosition = mAdapterHelper.findPositionOffset(position);
            if (offsetPosition < 0 || offsetPosition >= mAdapter.getItemCount()) {
                throw new IndexOutOfBoundsException("Inconsistency detected. Invalid item "
                        + "position " + position + "(offset:" + offsetPosition + ")."
                        + "state:" + mState.getItemCount());
            }

            final int type = mAdapter.getItemViewType(offsetPosition);
            // 2) Find from scrap via stable ids, if exists
            if (mAdapter.hasStableIds()) {
                holder = getScrapViewForId(mAdapter.getItemId(offsetPosition), type, dryRun);
                if (holder != null) {
                    // update position
                    holder.mPosition = offsetPosition;
                    fromScrap = true;
                }
            }
            if (holder == null && mViewCacheExtension != null) {
                // We are NOT sending the offsetPosition because LayoutManager does not
                // know it.
                final View view = mViewCacheExtension
                        .getViewForPositionAndType(this, position, type);
                if (view != null) {
                    holder = getChildViewHolder(view);
                    if (holder == null) {
                        throw new IllegalArgumentException("getViewForPositionAndType returned"
                                + " a view which does not have a ViewHolder");
                    } else if (holder.shouldIgnore()) {
                        throw new IllegalArgumentException("getViewForPositionAndType returned"
                                + " a view that is ignored. You must call stopIgnoring before"
                                + " returning this view.");
                    }
                }
            }
            if (holder == null) { // fallback to recycler
                // try recycler.
                // Head to the shared pool.
                if (DEBUG) {
                    Log.d(TAG, "getViewForPosition(" + position + ") fetching from shared "
                            + "pool");
                }
                holder = getRecycledViewPool()
                        .getRecycledView(mAdapter.getItemViewType(offsetPosition));
                if (holder != null) {
                    holder.resetInternal();
                    if (FORCE_INVALIDATE_DISPLAY_LIST) {
                        invalidateDisplayListInt(holder);
                    }
                }
            }
            if (holder == null) {
                holder = mAdapter.createViewHolder(RecyclerView.this,
                        mAdapter.getItemViewType(offsetPosition));
                if (DEBUG) {
                    Log.d(TAG, "getViewForPosition created new ViewHolder");
                }
            }
        }
        boolean bound = false;
        if (mState.isPreLayout() && holder.isBound()) {
            // do not update unless we absolutely have to.
            holder.mPreLayoutPosition = position;
        } else if (!holder.isBound() || holder.needsUpdate() || holder.isInvalid()) {
            if (DEBUG && holder.isRemoved()) {
                throw new IllegalStateException("Removed holder should be bound and it should"
                        + " come here only in pre-layout. Holder: " + holder);
            }
            final int offsetPosition = mAdapterHelper.findPositionOffset(position);
            mAdapter.bindViewHolder(holder, offsetPosition);
            attachAccessibilityDelegate(holder.itemView);
            bound = true;
            if (mState.isPreLayout()) {
                holder.mPreLayoutPosition = position;
            }
        }

        final ViewGroup.LayoutParams lp = holder.itemView.getLayoutParams();
        final LayoutParams rvLayoutParams;
        if (lp == null) {
            rvLayoutParams = (LayoutParams) generateDefaultLayoutParams();
            holder.itemView.setLayoutParams(rvLayoutParams);
        } else if (!checkLayoutParams(lp)) {
            rvLayoutParams = (LayoutParams) generateLayoutParams(lp);
            holder.itemView.setLayoutParams(rvLayoutParams);
        } else {
            rvLayoutParams = (LayoutParams) lp;
        }
        rvLayoutParams.mViewHolder = holder;
        rvLayoutParams.mPendingInvalidate = fromScrap && bound;
        return holder.itemView;
}

How to hide a status bar in iOS?

add this key key from dropdownlist in "info.plist" and voila you will no more see top bar that includes elements something like GSM,wifi icon etc.
enter image description here

JavaScript - Get Browser Height

var winWidth = window.screen.width;
var winHeight = window.screen.height;

document.write(winWidth, winHeight);

How can I backup a Docker-container with its data-volumes?

This is a volume-folder-backup way.
If you have docker registry infra, This method is very helpful.
This uses docker registry for moving the zip file easily.

#volume folder backup script. !/bin/bash

#common bash variables. set these variable before running scripts
REPO=harbor.otcysk.org:20443/levee
VFOLDER=/data/mariadb
TAG=mariadb1

#zip local folder for volume files
tar cvfz volume-backup.tar.gz $VFOLDER

#copy the zip file to volume-backup container.
#zip file must be in current folder.
docker run -d -v $(pwd):/temp --name volume-backup ubuntu \
       bash -c "cd / && cp /temp/volume-backup.tar.gz ."


#commit for pushing into REPO
docker commit volume-backup $REPO/volume-backup:$TAG

#check gz files in this container
#docker run --rm -it --entrypoint bash --name check-volume-backup \
        $REPO/volume-backup:$TAG

#push into REPO
docker push $REPO/volume-backup:$TAG

In another server

#pull the image in another server
docker pull $REPO/volume-backup:$TAG

#restore files in another server filesystem
docker run --rm -v $VFOLDER:$VFOLDER --name volume-backup $REPO/volume-backup:$TAG \
       bash -c "cd / && tar xvfz volume-backup.tar.gz"

Run your image which uses this volume folder.
You can make a image which has both one run-image and one volume zip file easily.
But I do not recommened for various reasons(image size, entry command, ..).

Selecting Folder Destination in Java?

I found a good example of what you need in this link.

import javax.swing.JFileChooser;

public class Main {
  public static void main(String s[]) {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("choosertitle");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
      System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
    } else {
      System.out.println("No Selection ");
    }
  }
}

Group by & count function in sqlalchemy

The documentation on counting says that for group_by queries it is better to use func.count():

from sqlalchemy import func
session.query(Table.column, func.count(Table.column)).group_by(Table.column).all()

Can you use @Autowired with static fields?

Disclaimer This is by no means standard and there could very well be a better spring way of doing this. None of the above answers address the issues of wiring a public static field.

I wanted to accomplish three things.

  1. Use spring to "Autowire" (Im using @Value)
  2. Expose a public static value
  3. Prevent modification

My object looks like this

private static String BRANCH = "testBranch";

@Value("${content.client.branch}")
public void finalSetBranch(String branch) {
    BRANCH = branch;
}

public static String BRANCH() {
    return BRANCH;
}

We have checked off 1 & 2 already now how do we prevent calls to the setter, since we cannot hide it.

@Component
@Aspect
public class FinalAutowiredHelper {

@Before("finalMethods()")
public void beforeFinal(JoinPoint joinPoint) {
    throw new FinalAutowiredHelper().new ModifySudoFinalError("");
}

@Pointcut("execution(* com.free.content.client..*.finalSetBranch(..))")
public void finalMethods() {}


public class ModifySudoFinalError extends Error {
    private String msg;

    public ModifySudoFinalError(String msg) {
        this.msg = msg;
    }

    @Override
    public String getMessage() {
        return "Attempted modification of a final property: " + msg;
    }
}

This aspect will wrap all methods beginning with final and throw an error if they are called.

I dont think this is particularly useful, but if you are ocd and like to keep you peas and carrots separated this is one way to do it safely.

Important Spring does not call your aspects when it calls a function. Made this easier, to bad I worked out the logic before figuring that out.

Create Directory if it doesn't exist with Ruby

Simple way:

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

How to use ? : if statements with Razor and inline code blocks

In most cases the solution of CD.. will work perfectly fine. However I had a bit more twisted situation:

 @(String.IsNullOrEmpty(Model.MaidenName) ? "&nbsp;" : Model.MaidenName)

This would print me "&nbsp;" in my page, respectively generate the source &amp;nbsp;. Now there is a function Html.Raw("&nbsp;") which is supposed to let you write source code, except in this constellation it throws a compiler error:

Compiler Error Message: CS0173: Type of conditional expression cannot be determined because there is no implicit conversion between 'System.Web.IHtmlString' and 'string'

So I ended up writing a statement like the following, which is less nice but works even in my case:

@if (String.IsNullOrEmpty(Model.MaidenName)) { @Html.Raw("&nbsp;") } else { @Model.MaidenName } 

Note: interesting thing is, once you are inside the curly brace, you have to restart a Razor block.

How do you redirect to a page using the POST verb?

For your particular example, I would just do this, since you obviously don't care about actually having the browser get the redirect anyway (by virtue of accepting the answer you have already accepted):

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index() {
   // obviously these values might come from somewhere non-trivial
   return Index(2, "text");
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(int someValue, string anotherValue) {
   // would probably do something non-trivial here with the param values
   return View();
}

That works easily and there is no funny business really going on - this allows you to maintain the fact that the second one really only accepts HTTP POST requests (except in this instance, which is under your control anyway) and you don't have to use TempData either, which is what the link you posted in your answer is suggesting.

I would love to know what is "wrong" with this, if there is anything. Obviously, if you want to really have sent to the browser a redirect, this isn't going to work, but then you should ask why you would be trying to convert that regardless, since it seems odd to me.

Hope that helps.

How to get list of dates between two dates in mysql select query

Try:

select * from 
(select adddate('1970-01-01',t4.i*10000 + t3.i*1000 + t2.i*100 + t1.i*10 + t0.i) selected_date from
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t0,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t1,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t2,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t3,
 (select 0 i union select 1 union select 2 union select 3 union select 4 union select 5 union select 6 union select 7 union select 8 union select 9) t4) v
where selected_date between '2012-02-10' and '2012-02-15'

-for date ranges up to nearly 300 years in the future.

[Corrected following a suggested edit by UrvishAtSynapse.]

Make an image follow mouse pointer

by using jquery to register .mousemove to document to change the image .css left and top to event.pageX and event.pageY.

example as below http://jsfiddle.net/BfLAh/1/

_x000D_
_x000D_
$(document).mousemove(function(e) {
  $("#follow").css({
    left: e.pageX,
    top: e.pageY
  });
});
_x000D_
#follow {
  position: absolute;
  text-align: center;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="follow"><img src="https://placekitten.com/96/140" /><br>Kitteh</br>
</div>
_x000D_
_x000D_
_x000D_

updated to follow slowly

http://jsfiddle.net/BfLAh/3/

for the orientation , you need to get the current css left and css top and compare with event.pageX and event.pageY , then set the image orientation with

-webkit-transform: rotate(-90deg); 
-moz-transform: rotate(-90deg); 

for the speed , you can set the jquery .animation duration to certain amount.

how to set start page in webconfig file in asp.net c#

If your project contains a RouteConfig.cs file, then you probably need to ignore the route to the root by adding routes.IgnoreRoute(""); in this file.

If it doen't solve your problem, try this :

void Application_BeginRequest(object sender, EventArgs e)
{
    if (Request.AppRelativeCurrentExecutionFilePath == "~/")
        Response.Redirect("~/index.aspx");
}

Is it possible to use Visual Studio on macOS?

No. Neither Visual Studio or the .NET framework will run on Mac OSX (although the latter is changing). However, if you want to write an application in a similar framework, you could use Mono and MonoDevelop.

Create request with POST, which response codes 200 or 201 and content

Check out HTTP: Method Definitions: POST.

The action performed by the POST method might not result in a resource that can be identified by a URI. In this case, either 200 (OK) or 204 (No Content) is the appropriate response status, depending on whether or not the response includes an entity that describes the result.

If a resource has been created on the origin server, the response SHOULD be 201 (Created) and contain an entity which describes the status of the request and refers to the new resource, and a Location header (see section 14.30).

How to get all elements inside "div" that starts with a known text

Option 1: Likely fastest (but not supported by some browsers if used on Document or SVGElement) :

var elements = document.getElementById('parentContainer').children;

Option 2: Likely slowest :

var elements = document.getElementById('parentContainer').getElementsByTagName('*');

Option 3: Requires change to code (wrap a form instead of a div around it) :

// Since what you're doing looks like it should be in a form...
var elements = document.forms['parentContainer'].elements;

var matches = [];

for (var i = 0; i < elements.length; i++)
    if (elements[i].value.indexOf('q17_') == 0)
        matches.push(elements[i]);

Dynamically display a CSV file as an HTML table on a web page

The previously linked solution is a horrible piece of code; nearly every line contains a bug. Use fgetcsv instead:

<?php
echo "<html><body><table>\n\n";
$f = fopen("so-csv.csv", "r");
while (($line = fgetcsv($f)) !== false) {
        echo "<tr>";
        foreach ($line as $cell) {
                echo "<td>" . htmlspecialchars($cell) . "</td>";
        }
        echo "</tr>\n";
}
fclose($f);
echo "\n</table></body></html>";

How to prevent buttons from submitting forms

Set the type on your buttons:

<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>

...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your removeItem() function so that it doesn't trigger an exception:

function removeItem() {
  var rows = $('form tr');
  if ( rows.length > 2 ) {
    // change: work on filtered jQuery object
    rows.filter(":last").html('');
    $('form :hidden:last').val('');
  } else {
    alert('Cannot remove any more rows');
  }
}

Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.

FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:

$(function() // execute once the DOM has loaded
{

  // wire up Add Item button click event
  $("#AddItem").click(function(event)
  {
    event.preventDefault(); // cancel default behavior

    //... rest of add logic
  });

  // wire up Remove Last Item button click event
  $("RemoveLastItem").click(function(event)
  {
    event.preventDefault(); // cancel default behavior

    //... rest of remove last logic
  });

});

...

<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>

This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type on the buttons back to submit and handling the event server-side - this is known as unobtrusive JavaScript.

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

fix json values, it's add \ before u{xxx} to all +" "

  $item = preg_replace_callback('/"(.+?)":"(u.+?)",/', function ($matches) {
        $matches[2] = preg_replace('/(u)/', '\u', $matches[2]);
            $matches[2] = preg_replace('/(")/', '&quot;', $matches[2]); 
            $matches[2] = json_decode('"' . $matches[2] . '"'); 
            return '"' . $matches[1] . '":"' . $matches[2] . '",';
        }, $item);

How do I do a simple 'Find and Replace" in MsSQL?

The following query replace each and every a character with a b character.

UPDATE 
    YourTable
SET 
    Column1 = REPLACE(Column1,'a','b')
WHERE 
    Column1 LIKE '%a%'

This will not work on SQL server 2003.

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

How do I update an entity using spring-data-jpa?

Since the answer by @axtavt focuses on JPA not spring-data-jpa

To update an entity by querying then saving is not efficient because it requires two queries and possibly the query can be quite expensive since it may join other tables and load any collections that have fetchType=FetchType.EAGER

Spring-data-jpa supports update operation.
You have to define the method in Repository interface.and annotated it with @Query and @Modifying.

@Modifying
@Query("update User u set u.firstname = ?1, u.lastname = ?2 where u.id = ?3")
void setUserInfoById(String firstname, String lastname, Integer userId);

@Query is for defining custom query and @Modifying is for telling spring-data-jpa that this query is an update operation and it requires executeUpdate() not executeQuery().

You can specify other return types:
int - the number of records being updated.
boolean - true if there is a record being updated. Otherwise, false.


Note: Run this code in a Transaction.

Sort divs in jQuery based on attribute 'data-sort'?

I made this into a jQuery function:

jQuery.fn.sortDivs = function sortDivs() {
    $("> div", this[0]).sort(dec_sort).appendTo(this[0]);
    function dec_sort(a, b){ return ($(b).data("sort")) < ($(a).data("sort")) ? 1 : -1; }
}

So you have a big div like "#boo" and all your little divs inside of there:

$("#boo").sortDivs();

You need the "? 1 : -1" because of a bug in Chrome, without this it won't sort more than 10 divs! http://blog.rodneyrehm.de/archives/14-Sorting-Were-Doing-It-Wrong.html

Find an object in array?

Swift 4,

Another way to achieve this using filter function,

if let object = elements.filter({ $0.title == "title" }).first {
    print("found")
} else {
    print("not found")
}

Is there Selected Tab Changed Event in the standard WPF Tab Control

I tied this in the handler to make it work:

void TabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    if (e.Source is TabControl)
    {
      //do work when tab is changed
    }
}

Get ASCII value at input word

char (with a lower-case c) is a numeric type. It already holds the ascii value of the char. Just cast it to an integer to display it as a numeric value rather than a textual value:

System.out.println("char " + ch + " has the following value : " + (int) ch);

Join two data frames, select all columns from one and some columns from the other

I got an error: 'a not found' using the suggested code:

from pyspark.sql.functions import col df1.alias('a').join(df2.alias('b'),col('b.id') == col('a.id')).select([col('a.'+xx) for xx in a.columns] + [col('b.other1'),col('b.other2')])

I changed a.columns to df1.columns and it worked out.

How to save the output of a console.log(object) to a file?

Right click on object and saving was not available for me.

The working solution for me is given below

Log as pretty string shown in this answer

console.log('jsonListBeauty', JSON.stringify(jsonList, null, 2));

in Chrome DevTools, Log shows as below

saveJsonlog

Just press Copy, It will be copied to clipboard with desired spacing level

Paste it on your favorite text editor and save it


image took on 15/02/2021, Google Chrome Version 88.0.4324.150

Changing java platform on which netbeans runs

Fix this by moving my jdk folder to other disk

Node.js quick file server (static files over HTTP)

You also asked why requests are dropping - not sure what's the specific reason on your case, but in overall you better server static content using dedicated middleware (nginx, S3, CDN) because Node is really not optimized for this networking pattern. See further explanation here (bullet 13): http://goldbergyoni.com/checklist-best-practice-of-node-js-in-production/

HTTP status code 0 - Error Domain=NSURLErrorDomain?

In iOS SDK When your API call time-outs, you get status 0 for that.

HTML form with two submit buttons and two "target" attributes

Example:

<input 
  type="submit" 
  onclick="this.form.action='new_target.php?do=alternative_submit'" 
  value="Alternative Save"
/>

Voila. Very "fancy", three word JavaScript!

Converting an OpenCV Image to Black and White

Here's a two line code I found online that might be helpful for a beginner

# Absolute value of the 32/64
abs_image_in32_64 = np.absolute(image_in32_64)

image_8U = np.uint8(abs_image_in32_64)

How to edit log message already committed in Subversion?

svnadmin setlog /path/to/repository -r revision_number --bypass-hooks message_file.txt

Eclipse can't find / load main class

I have solved the issue following way:

Go to Run Configuration (Right Click on Java File->Run->Run Configuration).

Go to ClassPath Tab: Click on Advanced -> Add Folders -> Add bin directory (which has class file in it for Java source code)

Re run the code, now it will solve the issue. It worked for me

How do I get a list of all the duplicate items using pandas in python?

This may not be a solution to the question, but to illustrate examples:

import pandas as pd

df = pd.DataFrame({
    'A': [1,1,3,4],
    'B': [2,2,5,6],
    'C': [3,4,7,6],
})

print(df)
df.duplicated(keep=False)
df.duplicated(['A','B'], keep=False)

The outputs:

   A  B  C
0  1  2  3
1  1  2  4
2  3  5  7
3  4  6  6

0    False
1    False
2    False
3    False
dtype: bool

0     True
1     True
2    False
3    False
dtype: bool

How to convert an address into a Google Maps Link (NOT MAP)

I know I'm very late to the game, but thought I'd contribute for posterity's sake.

I wrote a short jQuery function that will automatically turn any <address> tags into Google maps links.

See a demo here.

$(document).ready(function () {
   //Convert address tags to google map links - Michael Jasper 2012
   $('address').each(function () {
      var link = "<a href='http://maps.google.com/maps?q=" + encodeURIComponent( $(this).text() ) + "' target='_blank'>" + $(this).text() + "</a>";
      $(this).html(link);
   });
});

Bonus:

I also came across a situation that called for generating embedded maps from the links, and though I'd share with future travelers:

View a full demo

$(document).ready(function(){
    $("address").each(function(){                         
        var embed ="<iframe width='425' height='350' frameborder='0' scrolling='no'  marginheight='0' marginwidth='0' src='https://maps.google.com/maps?&amp;q="+ encodeURIComponent( $(this).text() ) +"&amp;output=embed'></iframe>";
        $(this).html(embed);             
    });
});

SQL Server String Concatenation with Null

Use

SET CONCAT_NULL_YIELDS_NULL  OFF 

and concatenation of null values to a string will not result in null.

Please note that this is a deprecated option, avoid using. See the documentation for more details.

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

How to change the button text of <input type="file" />?

if you using rails and have problem apply it, I would like to add some tips from original answer posted by @Fernando Kosh

  • Download file zip and copy file bootstrap-filestyle.min.js ke folder app/assets/javascripts/
  • open your application.js and add this line below

    //= require bootstrap-filestyle.min

  • open your coffee and add this line

    $(":file").filestyle({buttonName: "btn-primary",buttonBefore: true,buttonText: " Your text here",icon: false});

How do I fix "Expected to return a value at the end of arrow function" warning?

The problem seems to be that you are not returning something in the event that your first if-case is false.

The error you are getting states that your arrow function (comment) => { doesn't have a return statement. While it does for when your if-case is true, it does not return anything for when it's false.

return this.props.comments.map((comment) => {
  if (comment.hasComments === true) {
    return (
      <div key={comment.id}>
        <CommentItem className="MainComment" />
        {this.props.comments.map(commentReply => {
          if (commentReply.replyTo === comment.id) { 
            return (
              <CommentItem className="SubComment"/>
            )
          }
        })
        }
      </div>
    )
  } else {
     //return something here.
  }
});

edit you should take a look at Kris' answer for how to better implement what you are trying to do.

SQLite UPSERT / UPDATE OR INSERT

You can also just add an ON CONFLICT REPLACE clause to your user_name unique constraint and then just INSERT away, leaving it to SQLite to figure out what to do in case of a conflict. See:https://sqlite.org/lang_conflict.html.

Also note the sentence regarding delete triggers: When the REPLACE conflict resolution strategy deletes rows in order to satisfy a constraint, delete triggers fire if and only if recursive triggers are enabled.

How to display text in pygame?

This is slighly more OS independent way:

# do this init somewhere
import pygame
pygame.init()
screen = pygame.display.set_mode((640, 480))
font = pygame.font.Font(pygame.font.get_default_font(), 36)

# now print the text
text_surface = font.render('Hello world', antialias=True, color=(0, 0, 0))
screen.blit(text_surface, dest=(0,0))

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

BTW: The correct way to do this is to use TryGetValue

obj item;
if(!dict.TryGetValue(name, out item))
    return null;
return item;

This accesses the dictionary only once instead of twice.
If you really want to just return null if the key doesn't exist, the above code can be simplified further:

obj item;
dict.TryGetValue(name, out item);
return item;

This works, because TryGetValue sets item to null if no key with name exists.

Regular vs Context Free Grammars

Regular Expressions

  • Basis of lexical analysis
  • Represent regular languages

Context Free Grammars

  • Basis of parsing
  • Represent language constructs

enter image description here

Select all elements with a "data-xxx" attribute without using jQuery

document.querySelectorAll("[data-foo]")

will get you all elements with that attribute.

document.querySelectorAll("[data-foo='1']")

will only get you ones with a value of 1.

What is the Linux equivalent to DOS pause?

Try this:

function pause(){
   read -p "$*"
}

Auto-indent in Notepad++

Try to save the file before, then it will indent.

iTunes Connect: How to choose a good SKU?

As others have noted, "SKU" stands for stock keeping unit. Here's what I find currently (3 February 2017) in the Apple documentation regarding the "SKU Number:"

SKU Number

A unique ID for your app in the Apple system that is not seen by users. You can use letters, numbers, hyphens, periods, and underscores. The SKU can’t
start with a hyphen, period, or underscore. Use a value that is meaningful to your organization. Can’t be edited after saving the iTunes Connect record.

(internet archive link:) iTunes Connect Properties

Select2 open dropdown on focus

I tried a number of these and finally came up with the following that works for me with Select2 4.0.1. element is the <select> element.

$.data(element).select2.on("focus", function (e) {
    $(element).select2("open");
});

How can I change the default width of a Twitter Bootstrap modal box?

If you want something that does not break the relative design try this:

body .modal {
  width: 90%; /* desired relative width */
  left: 5%; /* (100%-width)/2 */
  /* place center */
  margin-left:auto;
  margin-right:auto; 
}

As, @Marco Johannesen says, the "body" before the selector is so that it takes a higher priority than the default.

Get class name of object as string in Swift

Swift 5.1 :-

You can also use generic function for get class name of object as string

struct GenericFunctions {
 static func className<T>(_ name: T) -> String {
        return "\(name)"
    }

}

Call this function by using following:-

let name = GenericFunctions.className(ViewController.self)

Happy Coding :)

how to access parent window object using jquery?

Here is a more literal answer (parent window as opposed to opener) to the original question that can be used within an iframe, assuming the domain name in the iframe matches that of the parent window:

window.parent.$("#serverMsg")

Facebook API: Get fans of / people who like a page

Use this.

https://www.facebook.com/browse/?type=page_fans&page_id=<your page id>

It will return up to 500 of the most recent likes.

http://www.facebook.com/browse/?type=page_fans&page_id=<your page id>&start=400

Each page will give you 100 fans. Change start value to (0, 100, 200, 300, 400) to get the first 500. If start is >= 401, the page will be blank :(

How can I make git show a list of the files that are being tracked?

The files managed by git are shown by git ls-files. Check out its manual page.

What is the best way to get all the divisors of a number?

Old question, but here is my take:

def divs(n, m):
    if m == 1: return [1]
    if n % m == 0: return [m] + divs(n, m - 1)
    return divs(n, m - 1)

You can proxy with:

def divisorGenerator(n):
    for x in reversed(divs(n, n)):
        yield x

NOTE: For languages that support, this could be tail recursive.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

Follow easy steps to resolved the below issue: Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved: Failed to read artifact description for org.apache.maven.plugins:maven-ar-plugin:ar:2.4 in eclipse

enter image description here

Solution: Step1: enter image description here

Step2:

enter image description here

Issue solved ?

enter image description here

Default passwords of Oracle 11g?

Login into the machine as oracle login user id( where oracle is installed)..

  1. Add ORACLE_HOME = <Oracle installation Directory> in Environment variable

  2. Open a command prompt

  3. Change the directory to %ORACLE_HOME%\bin

  4. type the command sqlplus /nolog

  5. SQL> connect /as sysdba

  6. SQL> alter user SYS identified by "newpassword";

One more check, while oracle installation and database confiuration assistant setup, if you configure any database then you might have given password and checked the same password for all other accounts.. If so, then you try with the password which you have given in your database configuration assistant setup.

Hope this will work for you..

remove script tag from HTML content

Shorter:

$html = preg_replace("/<script.*?\/script>/s", "", $html);

When doing regex things might go wrong, so it's safer to do like this:

$html = preg_replace("/<script.*?\/script>/s", "", $html) ? : $html;

So that when the "accident" happen, we get the original $html instead of empty string.

C# Switch-case string starting with

Short answer: No.

The switch statement takes an expression that is only evaluated once. Based on the result, another piece of code is executed.

So what? => String.StartsWith is a function. Together with a given parameter, it is an expression. However, for your case you need to pass a different parameter for each case, so it cannot be evaluated only once.

Long answer #1 has been given by others.

Long answer #2:

Depending on what you're trying to achieve, you might be interested in the Command Pattern/Chain-of-responsibility pattern. Applied to your case, each piece of code would be represented by an implementation of a Command. In addition to the execute method, the command can provide a boolean Accept method, which checks whether the given string starts with the respective parameter.

Advantage: Instead of your hardcoded switch statement, hardcoded StartsWith evaluations and hardcoded strings, you'd have lot more flexibility.

The example you gave in your question would then look like this:

var commandList = new List<Command>() { new MyABCCommand() };

foreach (Command c in commandList)
{
    if (c.Accept(mystring))
    {
        c.Execute(mystring);
        break;
    }
}

class MyABCCommand : Command
{
    override bool Accept(string mystring)
    {
        return mystring.StartsWith("abc");
    }
}    

How to delete all files and folders in a directory?

 foreach (string file in System.IO.Directory.GetFiles(path))
 {
    System.IO.File.Delete(file);
 }

 foreach (string subDirectory in System.IO.Directory.GetDirectories(path))
 {
     System.IO.Directory.Delete(subDirectory,true); 
 } 

"E: Unable to locate package python-pip" on Ubuntu 18.04

You might have python 3 pip installed already. Instead of pip install you can use pip3 install.

Amazon S3 upload file and get URL

Similarly if you want link through s3Client you can use below.

System.out.println("filelink: " + s3Client.getUrl("your_bucket_name", "your_file_key"));

IE8 support for CSS Media Query

IE didn't add media query support until IE9. So with IE8 you're out of luck.

How to implement endless list with RecyclerView?

Here is another approach. It will work with any layout manager.

  1. Make Adapter class abstract
  2. Then create an abstract method in adapter class (eg. load())
  3. In onBindViewHolder check the position if last and call load()
  4. Override the load() function while creating the adapter object in your activity or fragment.
  5. In the overided load function implement your loadmore call

For a detail understanding I wrote a blog post and example project get it here http://sab99r.com/blog/recyclerview-endless-load-more/

MyAdapter.java

public abstract class MyAdapter extends RecyclerView.Adapter<ViewHolder>{

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            //check for last item
            if ((position >= getItemCount() - 1))
                load();
        }

        public abstract void load();
}

MyActivity.java

public class MainActivity extends AppCompatActivity {
    List<Items> items;
    MyAdapter adapter;

   @Override
    protected void onCreate(Bundle savedInstanceState) {
    ...
    adapter=new MyAdapter(items){
            @Override
            public void load() {
                //implement your load more here
                Item lastItem=items.get(items.size()-1);
                loadMore();
            }
        };
   }
}

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

Pardon my ignorance, but why are you using $('.salesperson') instead of $('#salesperson') when dealing with an ID?

Vector of structs initialization

Create vector, push_back element, then modify it as so:

struct subject {
    string name;
    int marks;
    int credits;
};


int main() {
    vector<subject> sub;

    //Push back new subject created with default constructor.
    sub.push_back(subject());

    //Vector now has 1 element @ index 0, so modify it.
    sub[0].name = "english";

    //Add a new element if you want another:
    sub.push_back(subject());

    //Modify its name and marks.
    sub[1].name = "math";
    sub[1].marks = 90;
}

You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.

Recursively add the entire folder to a repository

I just needed to do this, and I found that you can easily add files in subdirectories. You only need to be on the "top directory" of the repo, and then run something like:

$ git add ./subdir/file_in_subdir.txt

Limit on the WHERE col IN (...) condition

For MS SQL 2016, passing ints into the in, it looks like it can handle close to 38,000 records.

select * from user where userId in (1,2,3,etc)

What are type hints in Python 3.5?

The newly released PyCharm 5 supports type hinting. In their blog post about it (see Python 3.5 type hinting in PyCharm 5) they offer a great explanation of what type hints are and aren't along with several examples and illustrations for how to use them in your code.

Additionally, it is supported in Python 2.7, as explained in this comment:

PyCharm supports the typing module from PyPI for Python 2.7, Python 3.2-3.4. For 2.7 you have to put type hints in *.pyi stub files since function annotations were added in Python 3.0.

Bulk Insert to Oracle using .NET

I guess that OracleBulkCopy is one of the fastest ways. I had some trouble to learn, that I needed a new ODAC version. Cf. Where is type [Oracle.DataAccess.Client.OracleBulkCopy] ?

Here is the complete PowerShell code to copy from a query into a suited existing Oracle table. I tried Sql-Server a datasource, but other valid OLE-DB sources will go to.

if ($ora_dll -eq $null)
{
    "Load Oracle dll"
    $ora_dll = [System.Reflection.Assembly]::LoadWithPartialName("Oracle.DataAccess") 
    $ora_dll
}

# sql-server or Oracle source example is sql-server
$ConnectionString ="server=localhost;database=myDatabase;trusted_connection=yes;Provider=SQLNCLI10;"

# Oracle destination
$oraClientConnString = "Data Source=myTNS;User ID=myUser;Password=myPassword"

$tableName = "mytable"
$sql = "select * from $tableName"

$OLEDBConn = New-Object System.Data.OleDb.OleDbConnection($ConnectionString)
$OLEDBConn.open()
$readcmd = New-Object system.Data.OleDb.OleDbCommand($sql,$OLEDBConn)
$readcmd.CommandTimeout = '300'
$da = New-Object system.Data.OleDb.OleDbDataAdapter($readcmd)
$dt = New-Object system.Data.datatable
[void]$da.fill($dt)
$OLEDBConn.close()
#Write-Output $dt

if ($dt)
{
    try
    {
        $bulkCopy = new-object ("Oracle.DataAccess.Client.OracleBulkCopy") $oraClientConnString
        $bulkCopy.DestinationTableName = $tableName
        $bulkCopy.BatchSize = 5000
        $bulkCopy.BulkCopyTimeout = 10000
        $bulkCopy.WriteToServer($dt)
        $bulkcopy.close()
        $bulkcopy.Dispose()
    }
    catch
    {
        $ex = $_.Exception
        Write-Error "Write-DataTable$($connectionName):$ex.Message"
        continue
    }
}

BTW: I use this to copy table with CLOB columns. I didn't get that to work using linked servers cf. question on dba. I didn't retry linked serves with the new ODAC.

How to move columns in a MySQL table?

If empName is a VARCHAR(50) column:

ALTER TABLE Employees MODIFY COLUMN empName VARCHAR(50) AFTER department;

EDIT

Per the comments, you can also do this:

ALTER TABLE Employees CHANGE COLUMN empName empName VARCHAR(50) AFTER department;

Note that the repetition of empName is deliberate. You have to tell MySQL that you want to keep the same column name.

You should be aware that both syntax versions are specific to MySQL. They won't work, for example, in PostgreSQL or many other DBMSs.

Another edit: As pointed out by @Luis Rossi in a comment, you need to completely specify the altered column definition just before the AFTER modifier. The above examples just have VARCHAR(50), but if you need other characteristics (such as NOT NULL or a default value) you need to include those as well. Consult the docs on ALTER TABLE for more info.

Detect & Record Audio in Python

You might want to look at csounds, also. It has several API's, including Python. It might be able to interact with an A-D interface and gather sound samples.

Moment.js - two dates difference in number of days

From the moment.js docs: format('E') stands for day of week. thus your diff is being computed on which day of the week, which has to be between 1 and 7.

From the moment.js docs again, here is what they suggest:

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
a.diff(b, 'days') // 1

Here is a JSFiddle for your particular case:

_x000D_
_x000D_
$('#test').click(function() {_x000D_
  var startDate = moment("13.04.2016", "DD.MM.YYYY");_x000D_
  var endDate = moment("28.04.2016", "DD.MM.YYYY");_x000D_
_x000D_
  var result = 'Diff: ' + endDate.diff(startDate, 'days');_x000D_
_x000D_
  $('#result').html(result);_x000D_
});
_x000D_
#test {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background: #ffb;_x000D_
  padding: 10px;_x000D_
  border: 2px solid #999;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.12.0/moment.js"></script>_x000D_
_x000D_
<div id='test'>Click Me!!!</div>_x000D_
<div id='result'></div>
_x000D_
_x000D_
_x000D_

How can I make Bootstrap columns all the same height?

You only show one row so your use case may be limited to just that. Just in case you have multiple rows, this plugin - github Javascript-grids - works perfectly! It makes each panel expand to the tallest panel, giving each row potentially a different height based on the tallest panel in that row. It's a jquery solution vs. css, but wanted to recommend it as an alternative approach.

jQuery How to Get Element's Margin and Padding?

According to the jQuery documentation, shorthand CSS properties are not supported.

Depending on what you mean by "total padding", you may be able to do something like this:

var $img = $('img');
var paddT = $img.css('padding-top') + ' ' + $img.css('padding-right') + ' ' + $img.css('padding-bottom') + ' ' + $img.css('padding-left');

Change x axes scale in matplotlib

I find the simple solution

pylab.ticklabel_format(axis='y',style='sci',scilimits=(1,4))

Tracing XML request/responses with JAX-WS

// This solution provides a way programatically add a handler to the web service clien w/o the XML config

// See full doc here: http://docs.oracle.com/cd/E17904_01//web.1111/e13734/handlers.htm#i222476

// Create new class that implements SOAPHandler

public class LogMessageHandler implements SOAPHandler<SOAPMessageContext> {

@Override
public Set<QName> getHeaders() {
    return Collections.EMPTY_SET;
}

@Override
public boolean handleMessage(SOAPMessageContext context) {
    SOAPMessage msg = context.getMessage(); //Line 1
    try {
        msg.writeTo(System.out);  //Line 3
    } catch (Exception ex) {
        Logger.getLogger(LogMessageHandler.class.getName()).log(Level.SEVERE, null, ex);
    } 
    return true;
}

@Override
public boolean handleFault(SOAPMessageContext context) {
    return true;
}

@Override
public void close(MessageContext context) {
}
}

// Programatically add your LogMessageHandler

   com.csd.Service service = null;
    URL url = new URL("https://service.demo.com/ResService.svc?wsdl");

    service = new com.csd.Service(url);

    com.csd.IService port = service.getBasicHttpBindingIService();
    BindingProvider bindingProvider = (BindingProvider)port;
    Binding binding = bindingProvider.getBinding();
    List<Handler> handlerChain = binding.getHandlerChain();
    handlerChain.add(new LogMessageHandler());
    binding.setHandlerChain(handlerChain);

bootstrap button shows blue outline when clicked

Change the Border Color back to Grey

.btn:focus,
.btn:active{
 border: 1px solid #ced4da !important;
}

Monitor network activity in Android Phones

For Android Phones(Without Root):- you can use this application tPacketCapture this will capture the network trafic for your device when you enable the capture. See this url for more details about network sniffing without rooting your device.

Once you have the file which is in .pcap format you can use this file and analyze the traffic using any traffic analyzer like Wireshark.

Also see this post for further ideas on Capturing mobile phone traffic on wireshark

How to do a for loop in windows command line?

The commandline interpreter does indeed have a FOR construct that you can use from the command prompt or from within a batch file.

For your purpose, you probably want something like:

FOR %i IN (*.ext) DO my-function %i

Which will result in the name of each file with extension *.ext in the current directory being passed to my-function (which could, for example, be another .bat file).

The (*.ext) part is the "filespec", and is pretty flexible with how you specify sets of files. For example, you could do:

FOR %i IN (C:\Some\Other\Dir\*.ext) DO my-function %i

To perform an operation in a different directory.

There are scores of options for the filespec and FOR in general. See

HELP FOR

from the command prompt for more information.