Programs & Examples On #Alert

An alert is usually a notification message to draw one's attention.

How to edit a JavaScript alert box title?

Override the javascript window.alert() function.

window.alert = function(title, message){
    var myElementToShow = document.getElementById("someElementId");
    myElementToShow.innerHTML = title + "</br>" + message; 
}

With this you can create your own alert() function. Create a new 'cool' looking dialog (from some div elements).

Tested working in chrome and webkit, not sure of others.

How to change theme for AlertDialog

Anyone trying to do this within a Fragment (using the support library i.e. pre API 11) should go with this:

public class LoadingDialogFragment extends DialogFragment {
    public static final String ID = "loadingDialog";

    public static LoadingDialogFragment newInstance() {
        LoadingDialogFragment f = new LoadingDialogFragment();

        return f;
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        StyleAlertDialog adb = new StyleAlertDialog(getActivity(), R.style.Your_Style);
        adb.setView(getActivity().getLayoutInflater().inflate(R.layout.fragment_dialog_layout, null));
        return adb;
    }

    private class StyleAlertDialog extends AlertDialog {
        protected StyleAlertDialog(Context context, int theme) {
            super(context, theme);
        }
    }
}

@Rflexor gave me the nudge to extend AlertDialog and expose the constructor thanks

Twitter Bootstrap alert message close and open again

There's a very simple way to do this using JQuery

If you delete data-dismiss="alert" from the alert div, you can just hide the alert using the x button, by adding a click events and interacting with the display css attribute of the alert.

$(".close").click(function(){
   $(this).parent().css("display", "none");
});

Then, whenever you need it again, you can toggle the display attribute again.

Full Example:

<div class="alert alert-danger" role="alert" id="my_alert" style="display: none;">
   Uh Oh... Something went wrong
  <button type="button" class="close" aria-label="Close">
     <span aria-hidden="true">&times;</span>
  </button>
</div>

<script>
   $(".close").click(function(){
      $(this).parent().css("display", "none");
   });

   //Use whatever event you like
   $("#show_alert").click(function(){
      $("#my_alert).css("display", "inherit");
   });
<script>

Javascript close alert box

Try boot box plugin.

var alert = bootbox.alert('Massage')
alert.show();
setTimeout(function(){alert.modal('hide'); }, 4000);

console.log showing contents of array object

Json stands for JavaScript Object Notation really all json is are javascript objects so your array is in json form already. To write it out in a div you could do a bunch of things one of the easiest I think would be:

 objectDiv.innerHTML = filter;

where objectDiv is the div you want selected from the DOM using jquery. If you wanted to list parts of the array out you could access them since it is a javascript object like so:

 objectDiv.innerHTML = filter.dvals.valueToDisplay; //brand or count depending.

edit: anything you want to be a string but is not currently (which is rare javascript treats almost everything as a string) just use the toString() function built in. so line above if you needed it would be filter.dvals.valueToDisplay.toString();

second edit to clarify: this answer is in response to the OP's comments and not completely to his original question.

How to get Text BOLD in Alert or Confirm box?

The alert() dialog is not rendered in HTML, and thus the HTML you have embedded is meaningless.

You'd need to use a custom modal to achieve that.

How to check if an alert exists using WebDriver?

The following (C# implementation, but similar in Java) allows you to determine if there is an alert without exceptions and without creating the WebDriverWait object.

boolean isDialogPresent(WebDriver driver) {
    IAlert alert = ExpectedConditions.AlertIsPresent().Invoke(driver);
    return (alert != null);
}

Animate a custom Dialog

First, you have to create two animation resources in res/anim dir

slide_up.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate
    android:duration="@android:integer/config_mediumAnimTime"
    android:fromYDelta="100%"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toXDelta="0">
</translate>
</set>

slide_bottom.xml

<set xmlns:android="http://schemas.android.com/apk/res/android">
<translate 
    android:duration="@android:integer/config_mediumAnimTime" 
    android:fromYDelta="0%p" 
    android:interpolator="@android:anim/accelerate_interpolator" 
    android:toYDelta="100%p">
</translate>
</set>

then you have to create a style

<style name="DialogAnimation">
    <item name="android:windowEnterAnimation">@anim/slide_up</item>
    <item name="android:windowExitAnimation">@anim/slide_bottom</item>
</style>

and add this line to your class

dialog.getWindow().getAttributes().windowAnimations = R.style.DialogAnimation; //style id

Based in http://www.devexchanges.info/2015/10/showing-dialog-with-animation-in-android.html

Bootstrap Alert Auto Close

C# Controller:

var result = await _roleManager.CreateAsync(identityRole);
   if (result.Succeeded == true)
       TempData["roleCreateAlert"] = "Added record successfully";

Razor Page:

@if (TempData["roleCreateAlert"] != null)
{
    <div class="alert alert-success">
        <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
        <p>@TempData["roleCreateAlert"]</p>
    </div>
}

Any Alert Auto Close:

<script type="text/javascript">
    $(".alert").delay(5000).slideUp(200, function () {
        $(this).alert('close');
    });
</script>

How to display an alert box from C# in ASP.NET?

After insertion code,

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);

How do I make a Mac Terminal pop-up/alert? Applescript?

If you're using any Mac OS X version which has Notification Center, you can use the terminal-notifier gem. First install it (you may need sudo):

gem install terminal-notifier

and then simply:

terminal-notifier -message "Hello, this is my message" -title "Message Title"

See also this OS X Daily post.

How to show an alert box in PHP?

When I just run this as a page

<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
exit;

it works fine.

What version of PHP are you running?

Could you try echoing something else after: $testObject->split_for_sms($Chat);

Maybe it doesn't get to that part of the code? You could also try these with the other function calls to check where your program stops/is getting to.

Hope you get a bit further with this.

jQuery UI Alert Dialog as a replacement for alert()

There is an issue that if you close the dialog it will execute the onCloseCallback function. This is a better design.

function jAlert2(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": onCloseCallback,
            "Cancel": function() {
          $( this ).dialog( "destroy" );
            }

        },
    });

How to Automatically Close Alerts using Twitter Bootstrap

Calling window.setTimeout(function, delay) will allow you to accomplish this. Here's an example that will automatically close the alert 2 seconds (or 2000 milliseconds) after it is displayed.

$(".alert-message").alert();
window.setTimeout(function() { $(".alert-message").alert('close'); }, 2000);

If you want to wrap it in a nifty function you could do this.

function createAutoClosingAlert(selector, delay) {
   var alert = $(selector).alert();
   window.setTimeout(function() { alert.alert('close') }, delay);
}

Then you could use it like so...

createAutoClosingAlert(".alert-message", 2000);

I am certain there are more elegant ways to accomplish this.

javascript popup alert on link click

You can use the onclick attribute, just return false if you don't want continue;

<script type="text/javascript">
function confirm_alert(node) {
    return confirm("Please click on OK to continue.");
}
</script>
<a href="http://www.google.com" onclick="return confirm_alert(this);">Click Me</a>

alert() not working in Chrome

I had the same issue recently on my test server. After searching for reasons this might be happening and testing the solutions I found here, I recalled that I had clicked the "Stop this page from creating pop-ups" option a few hours before when the script I was working on was wildly popping up alerts.

The solution was as simple as closing the tab and opening a fresh one!

Swift alert view with OK and Cancel: which button tapped?

Updated for swift 3:

// function defination:

@IBAction func showAlertDialog(_ sender: UIButton) {
        // Declare Alert
        let dialogMessage = UIAlertController(title: "Confirm", message: "Are you sure you want to Logout?", preferredStyle: .alert)

        // Create OK button with action handler
        let ok = UIAlertAction(title: "OK", style: .default, handler: { (action) -> Void in
             print("Ok button click...")
             self.logoutFun()
        })

        // Create Cancel button with action handlder
        let cancel = UIAlertAction(title: "Cancel", style: .cancel) { (action) -> Void in
            print("Cancel button click...")
        }

        //Add OK and Cancel button to dialog message
        dialogMessage.addAction(ok)
        dialogMessage.addAction(cancel)

        // Present dialog message to user
        self.present(dialogMessage, animated: true, completion: nil)
    }

// logoutFun() function definaiton :

func logoutFun()
{
    print("Logout Successfully...!")
}

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

How to reload a page after the OK click on the Alert Page

Try this:

alert("Successful Message");
location.reload();

Click in OK button inside an Alert (Selenium IDE)

This is an answer from 2012, the question if from 2009, but people still look at it and there's only one correct (use WebDriver) and one almost useful (but not good enough) answer.


If you're using Selenium RC and can actually see an alert dialog, then it can't be done. Selenium should handle it for you. But, as stated in Selenium documentation:

Selenium tries to conceal those dialogs from you (by replacing window.alert, window.confirm and window.prompt) so they won’t stop the execution of your page. If you’re seeing an alert pop-up, it’s probably because it fired during the page load process, which is usually too early for us to protect the page.

It is a known limitation of Selenium RC (and, therefore, Selenium IDE, too) and one of the reasons why Selenium 2 (WebDriver) was developed. If you want to handle onload JS alerts, you need to use WebDriver alert handling.

That said, you can use Robot or selenium.keyPressNative() to fill in any text and press Enter and confirm the dialog blindly. It's not the cleanest way, but it could work. You won't be able to get the alert message, however.

Robot has all the useful keys mapped to constants, so that will be easy. With keyPressNative(), you want to use 10 as value for pressing Enter or 27 for Esc since it works with ASCII codes.

How to handle login pop up window using Selenium WebDriver?

Now in 2020 Selenium 4 supports authenticating using Basic and Digest auth . Its using the CDP and currently only supports chromium-derived browsers

Example :

Java Example :

    Webdriver driver = new ChromeDriver();
    
    ((HasAuthentication) driver).register(UsernameAndPassword.of("username", "pass"));

    driver.get("http://sitewithauth");
    
 

Note : In Alpha-7 there is bug where it send username for both user/password. Need to wait for next release of selenium version as fix is available in trunk https://github.com/SeleniumHQ/selenium/commit/4917444886ba16a033a81a2a9676c9267c472894

HTML - Alert Box when loading page

you need a tiny bit of Javascript.

<script type="text/javascript">
window.onload = function(){ 
                alert("Hi there");
                }
</script>

This is only slightly different from Adam's answer. The effective difference is that this one alerts when the browser considers the page fully loaded, while Adam's alerts when the browser scans part the <script> tag in the text. The difference is with, for example, images, which may continue loading in parallel for a while.

chrome undo the action of "prevent this page from creating additional dialogs"

If you wish dialog box to be re-activated for the page you set as prevent dialog box to show.

Chrome: select settings, a google page for chrome will open with all your settings for chrome.

At the very bottom, go to advance settings and at the bottom of the advance settings you may click on Resset Browser Settings... this will make dialog box appear as they should.

Alert handling in Selenium WebDriver (selenium 2) with Java

This is what worked for me using Explicit Wait from here WebDriver: Advanced Usage

public void checkAlert() {
    try {
        WebDriverWait wait = new WebDriverWait(driver, 2);
        wait.until(ExpectedConditions.alertIsPresent());
        Alert alert = driver.switchTo().alert();
        alert.accept();
    } catch (Exception e) {
        //exception handling
    }
}

Java integer list

To insert a sleep command you can use Thread.sleep(2000). So the code would be:

List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
Iterator<Integer> myListIterator = someList.iterator(); 
while (myListIterator.hasNext()) {
    Integer coord = myListIterator.next();    
    System.out.println(coord);
    Thread.Sleep(2000);
}

This would output: 10 20 30 40 50

If you want the numbers after each other you could use: System.out.print(coord +" " ); and if you want to repeat the section you can put it in another while loop.

List<Integer> myCoords = new ArrayList<Integer>();
myCoords.add(10);
myCoords.add(20);
myCoords.add(30);
myCoords.add(40);
myCoords.add(50);
while(true)
    Iterator<Integer> myListIterator = someList.iterator(); 
    while (myListIterator.hasNext()) {
        Integer coord = myListIterator.next();    
        System.out.print(coord + " ");
        Thread.Sleep(2000);
    }
}

This would output: 10 20 30 40 50 10 20 30 40 50 ... and never stop until you kill the program.

Edit: You do have to put the sleep command in a try catch block

How can I programmatically get the MAC address of an iphone

There are vary solutions about this, but I couldn't find a whole thing. So I made my own solution for :

nicinfo

How to use :

NICInfoSummary* summary = [[[NICInfoSummary alloc] init] autorelease];

// en0 is for WiFi 
NICInfo* wifi_info = [summary findNICInfo:@"en0"];

// you can get mac address in 'XX-XX-XX-XX-XX-XX' form
NSString* mac_address = [wifi_info getMacAddressWithSeparator:@"-"];

// ip can be multiple
if(wifi_info.nicIPInfos.count > 0)
{
    NICIPInfo* ip_info = [wifi_info.nicIPInfos objectAtIndex:0];
    NSString* ip = ip_info.ip;
    NSString* netmask = ip_info.netmask;
    NSString* broadcast_ip = ip_info.broadcastIP;
}
else
{
    NSLog(@"WiFi not connected!");
}

What is the maximum length of a table name in Oracle?

Teach a man to fish

Notice the data-type and size

>describe all_tab_columns

VIEW all_tab_columns

Name                                      Null?    Type                        
 ----------------------------------------- -------- ----------------------------
 OWNER                                     NOT NULL VARCHAR2(30)                
 TABLE_NAME                                NOT NULL VARCHAR2(30)                
 COLUMN_NAME                               NOT NULL VARCHAR2(30)                
 DATA_TYPE                                          VARCHAR2(106)               
 DATA_TYPE_MOD                                      VARCHAR2(3)                 
 DATA_TYPE_OWNER                                    VARCHAR2(30)                
 DATA_LENGTH                               NOT NULL NUMBER                      
 DATA_PRECISION                                     NUMBER                      
 DATA_SCALE                                         NUMBER                      
 NULLABLE                                           VARCHAR2(1)                 
 COLUMN_ID                                          NUMBER                      
 DEFAULT_LENGTH                                     NUMBER                      
 DATA_DEFAULT                                       LONG                        
 NUM_DISTINCT                                       NUMBER                      
 LOW_VALUE                                          RAW(32)                     
 HIGH_VALUE                                         RAW(32)                     
 DENSITY                                            NUMBER                      
 NUM_NULLS                                          NUMBER                      
 NUM_BUCKETS                                        NUMBER                      
 LAST_ANALYZED                                      DATE                        
 SAMPLE_SIZE                                        NUMBER                      
 CHARACTER_SET_NAME                                 VARCHAR2(44)                
 CHAR_COL_DECL_LENGTH                               NUMBER                      
 GLOBAL_STATS                                       VARCHAR2(3)                 
 USER_STATS                                         VARCHAR2(3)                 
 AVG_COL_LEN                                        NUMBER                      
 CHAR_LENGTH                                        NUMBER                      
 CHAR_USED                                          VARCHAR2(1)                 
 V80_FMT_IMAGE                                      VARCHAR2(3)                 
 DATA_UPGRADED                                      VARCHAR2(3)                 
 HISTOGRAM                                          VARCHAR2(15)                

jQuery - Appending a div to body, the body is the object?

Using jQuery appendTo try this:

var holdyDiv = $('<div></div>').attr('id', 'holdy');
holdyDiv.appendTo('body');

How to check 'undefined' value in jQuery

Note that typeof always returns a string, and doesn't generate an error if the variable doesn't exist at all.

function A(val){
  if(typeof(val)  === "undefined") 
    //do this
  else
   //do this
}

Finding an elements XPath using IE Developer tool

If your goal is to find CSS selectors you can use MRI (once MRI is open, click any element to see various selectors for the element):

http://westciv.com/mri/

For Xpath:

http://functionaltestautomation.blogspot.com/2008/12/xpath-in-internet-explorer.html

Selenium using Python - Geckodriver executable needs to be in PATH

If you use a virtual environment and Windows 10 (maybe it's the same for other systems), you just need to put geckodriver.exe into the following folder in your virtual environment directory:

...\my_virtual_env_directory\Scripts\geckodriver.exe

How to programmatically send a 404 response with Express/Node?

According to the site I'll post below, it's all how you set up your server. One example they show is this:

var http = require("http");
var url = require("url");

function start(route, handle) {
  function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    console.log("Request for " + pathname + " received.");

    route(handle, pathname, response);
  }

  http.createServer(onRequest).listen(8888);
  console.log("Server has started.");
}

exports.start = start;

and their route function:

function route(handle, pathname, response) {
  console.log("About to route a request for " + pathname);
  if (typeof handle[pathname] === 'function') {
    handle[pathname](response);
  } else {
    console.log("No request handler found for " + pathname);
    response.writeHead(404, {"Content-Type": "text/plain"});
    response.write("404 Not found");
    response.end();
  }
}

exports.route = route;

This is one way. http://www.nodebeginner.org/

From another site, they create a page and then load it. This might be more of what you're looking for.

fs.readFile('www/404.html', function(error2, data) {
            response.writeHead(404, {'content-type': 'text/html'});
            response.end(data);
        });

http://blog.poweredbyalt.net/?p=81

Android - how to make a scrollable constraintlayout?

It seems that it is working, I don't know what dependency you were working with but in this one

compile 'com.android.support.constraint:constraint-layout:1.0.2'

Is working, this is what I did

<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.design.widget.TextInputLayout
            android:id="@+id/til_input"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="Escriba el contenido del archivo"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@+id/btn_save"
            app:layout_constraintTop_toTopOf="@id/btn_save"
            app:layout_constraintVertical_chainStyle="spread">

            <EditText
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </android.support.design.widget.TextInputLayout>

        <Button
            android:id="@+id/btn_save"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:onClick="onClickButtonSave"
            android:text="Guardar"
            app:layout_constraintLeft_toRightOf="@+id/til_input"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/txt_content"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_marginTop="0dp"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/til_input"
            app:layout_constraintVertical_chainStyle="spread"
            app:layout_constraintVertical_weight="1" />

        <Button
            android:id="@+id/btn_delete"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:onClick="onClickButtonDelete"
            android:text="Eliminar"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toBottomOf="@id/txt_content"
            app:layout_constraintVertical_chainStyle="spread" />

    </android.support.constraint.ConstraintLayout>

</ScrollView>

Scroll Topenter image description here

Scroll Bottomenter image description here

Converting Epoch time into the datetime

First a bit of info in epoch from man gmtime

The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar  time.   When  inter-
       preted  as  an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal
       Time (UTC).

to understand how epoch should be.

>>> time.time()
1347517171.6514659
>>> time.gmtime(time.time())
(2012, 9, 13, 6, 19, 34, 3, 257, 0)

just ensure the arg you are passing to time.gmtime() is integer.

How do I install cygwin components from the command line?

First, download installer at: https://cygwin.com/setup-x86_64.exe (Windows 64bit), then:

# move installer to cygwin folder
mv C:/Users/<you>/Downloads/setup-x86_64.exe C:/cygwin64/

# add alias to bash_aliases
echo "alias cygwin='C:/cygwin64/setup-x86_64.exe -q -P'" >> ~/.bash_aliases
source ~/.bash_aliases

# add bash_aliases to bashrc if missing
echo "source ~/.bash_aliases" >> ~/.profile

e.g.

# install vim
cygwin vim

# see other options
cygwin --help

Is there a way to list open transactions on SQL Server 2000 database?

DBCC OPENTRAN helps to identify active transactions that may be preventing log truncation. DBCC OPENTRAN displays information about the oldest active transaction and the oldest distributed and nondistributed replicated transactions, if any, within the transaction log of the specified database. Results are displayed only if there is an active transaction that exists in the log or if the database contains replication information.

An informational message is displayed if there are no active transactions in the log.

DBCC OPENTRAN

hadoop No FileSystem for scheme: file

For maven, just add the maven dependency for hadoop-hdfs (refer to the link below) will solve the issue.

http://mvnrepository.com/artifact/org.apache.hadoop/hadoop-hdfs/2.7.1

Closure in Java 7

According to Tom Hawtin

A closure is a block of code that can be referenced (and passed around) with access to the variables of the enclosing scope.

Now I'm trying to emulate the JavaScript closure example on Wikipedia, with a "straigth" translation to Java, in the hope to be useful:

//ECMAScript
var f, g;
function foo() {
  var x = 0;
  f = function() { return ++x; };
  g = function() { return --x; };
  x = 1;
  print('inside foo, call to f(): ' + f()); // "2"  
}
foo();
print('call to g(): ' + g()); // "1"
print('call to f(): ' + f()); // "2"

Now the java part: Function1 is "Functor" interface with arity 1 (one argument). Closure is the class implementing the Function1, a concrete Functor that acts as function (int -> int). In the main() method I just instantiate foo as a Closure object, replicating the calls from the JavaScript example. The IntBox class is just a simple container, it behave like an array of 1 int:

int a[1] = {0}

interface Function1   {
    public final IntBag value = new IntBag();
    public int apply();
}

class Closure implements Function1 {
   private IntBag x = value;
   Function1 f;
   Function1 g;

   @Override
   public int apply()  {
    // print('inside foo, call to f(): ' + f()); // "2"
    // inside apply, call to f.apply()
       System.out.println("inside foo, call to f.apply(): " + f.apply());
       return 0;
   }

   public Closure() {
       f = new Function1() {
           @Override
           public int apply()  {
               x.add(1);
                return x.get();
           }
       };
       g = new Function1() {
           @Override
           public int apply()  {
               x.add(-1);
               return x.get();
           }
       };
    // x = 1;
       x.set(1);
   }
}
public class ClosureTest {
    public static void main(String[] args) {
        // foo()
        Closure foo = new Closure();
        foo.apply();
        // print('call to g(): ' + g()); // "1"
        System.out.println("call to foo.g.apply(): " + foo.g.apply());
        // print('call to f(): ' + f()); // "2"
        System.out.println("call to foo.f.apply(): " + foo.f.apply());

    }
}

It prints:

inside foo, call to f.apply(): 2
call to foo.g.apply(): 1
call to foo.f.apply(): 2 

Retrieving a Foreign Key value with django-rest-framework serializers

This solution is better because of no need to define the source model. But the name of the serializer field should be the same as the foreign key field name

class ItemSerializer(serializers.ModelSerializer):
    category = serializers.SlugRelatedField(read_only=True, slug_field='title')

    class Meta:
        model = Item
        fields = ('id', 'name', 'category')

The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6

I solve my problem by passing nil permission while login.

[FBSession openActiveSessionWithReadPermissions:nil
                                       allowLoginUI:YES
                                  completionHandler:

Retrieving a property of a JSON object by index?

I know this is an old question but I found a way to get the fields by index. You can do it by using the Object.keys method.

When you call the Object.keys method it returns the keys in the order they were assigned (See the example below). I tested the method below in the following browsers:

  • Google Chrome version 43.0
  • Firefox version 33.1
  • Internet Explorer version 11

I also wrote a small extension to the object class so you can call the nth key of the object using getByIndex.

_x000D_
_x000D_
// Function to get the nth key from the object_x000D_
Object.prototype.getByIndex = function(index) {_x000D_
  return this[Object.keys(this)[index]];_x000D_
};_x000D_
_x000D_
var obj1 = {_x000D_
  "set1": [1, 2, 3],_x000D_
  "set2": [4, 5, 6, 7, 8],_x000D_
  "set3": [9, 10, 11, 12]_x000D_
};_x000D_
_x000D_
var obj2 = {_x000D_
  "set2": [4, 5, 6, 7, 8],_x000D_
  "set1": [1, 2, 3],_x000D_
  "set3": [9, 10, 11, 12]_x000D_
};_x000D_
_x000D_
log('-- Obj1 --');_x000D_
log(obj1);_x000D_
log(Object.keys(obj1));_x000D_
log(obj1.getByIndex(0));_x000D_
_x000D_
_x000D_
log('-- Obj2 --');_x000D_
log(obj2);_x000D_
log(Object.keys(obj2));_x000D_
log(obj2.getByIndex(0));_x000D_
_x000D_
_x000D_
// Log function to make the snippet possible_x000D_
function log(x) {_x000D_
  var d = document.createElement("div");_x000D_
  if (typeof x === "object") {_x000D_
    x = JSON.stringify(x, null, 4);_x000D_
  }_x000D_
  d.textContent= x;_x000D_
  document.body.appendChild(d);_x000D_
}
_x000D_
_x000D_
_x000D_

How to Replace dot (.) in a string in Java

You need two backslashes before the dot, one to escape the slash so it gets through, and the other to escape the dot so it becomes literal. Forward slashes and asterisk are treated literal.

str=xpath.replaceAll("\\.", "/*/");          //replaces a literal . with /*/

http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replaceAll(java.lang.String,%20java.lang.String)

How do I find the location of my Python site-packages directory?

This works for me. It will get you both dist-packages and site-packages folders. If the folder is not on Python's path, it won't be doing you much good anyway.

import sys; 
print [f for f in sys.path if f.endswith('packages')]

Output (Ubuntu installation):

['/home/username/.local/lib/python2.7/site-packages',
 '/usr/local/lib/python2.7/dist-packages',
 '/usr/lib/python2.7/dist-packages']

Spring Hibernate - Could not obtain transaction-synchronized Session for current thread

In your xyz.DAOImpl.java

Do the following steps:

//Step-1: Set session factory

@Resource(name="sessionFactory")
private SessionFactory sessionFactory;

public void setSessionFactory(SessionFactory sf)
{
    this.sessionFactory = sf;
}

//Step-2: Try to get the current session, and catch the HibernateException exception.


//Step-3: If there are any HibernateException exception, then true to get openSession.

try 
{
    //Step-2: Implementation
    session = sessionFactory.getCurrentSession();
} 
catch (HibernateException e) 
{
    //Step-3: Implementation
    session = sessionFactory.openSession();
}

How to schedule a stored procedure in MySQL

You can use mysql scheduler to run it each 5 seconds. You can find samples at http://dev.mysql.com/doc/refman/5.1/en/create-event.html

Never used it but I hope this would work:

CREATE EVENT myevent
    ON SCHEDULE EVERY 5 SECOND
    DO
      CALL delete_rows_links();

MySQL match() against() - order by relevance and column?

I was just playing around with this, too. One way you can add extra weight is in the ORDER BY area of the code.

For example, if you were matching 3 different columns and wanted to more heavily weight certain columns:

SELECT search.*,
MATCH (name) AGAINST ('black' IN BOOLEAN MODE) AS name_match,
MATCH (keywords) AGAINST ('black' IN BOOLEAN MODE) AS keyword_match,
MATCH (description) AGAINST ('black' IN BOOLEAN MODE) AS description_match
FROM search
WHERE MATCH (name, keywords, description) AGAINST ('black' IN BOOLEAN MODE)
ORDER BY (name_match * 3  + keyword_match * 2  + description_match) DESC LIMIT 0,100;

scp via java

I wrapped Jsch with some utility methods to make it a bit friendlier and called it

Jscp

Available here: https://github.com/willwarren/jscp

SCP utility to tar a folder, zip it, and scp it somewhere, then unzip it.

Usage:

// create secure context
SecureContext context = new SecureContext("userName", "localhost");

// set optional security configurations.
context.setTrustAllHosts(true);
context.setPrivateKeyFile(new File("private/key"));

// Console requires JDK 1.7
// System.out.println("enter password:");
// context.setPassword(System.console().readPassword());

Jscp.exec(context, 
           "src/dir",
           "destination/path",
           // regex ignore list 
           Arrays.asList("logs/log[0-9]*.txt",
           "backups") 
           );

Also includes useful classes - Scp and Exec, and a TarAndGzip, which work in pretty much the same way.

What is the Python equivalent of Matlab's tic and toc functions?

Apart from timeit which ThiefMaster mentioned, a simple way to do it is just (after importing time):

t = time.time()
# do stuff
elapsed = time.time() - t

I have a helper class I like to use:

class Timer(object):
    def __init__(self, name=None):
        self.name = name

    def __enter__(self):
        self.tstart = time.time()

    def __exit__(self, type, value, traceback):
        if self.name:
            print('[%s]' % self.name,)
        print('Elapsed: %s' % (time.time() - self.tstart))

It can be used as a context manager:

with Timer('foo_stuff'):
   # do some foo
   # do some stuff

Sometimes I find this technique more convenient than timeit - it all depends on what you want to measure.

How to use UIPanGestureRecognizer to move object? iPhone/iPad

swift 2 version of the @MS AppTech answer

func handlePan(panGest : UIPanGestureRecognizer) {
let velocity : CGPoint = panGest.velocityInView(self.view);
        let magnitude : CGFloat = CGFloat(sqrtf((Float(velocity.x) * Float(velocity.x)) + (Float(velocity.y) * Float(velocity.y))));
        let slideMult :CGFloat = magnitude / 200;
        //NSLog(@"magnitude: %f, slideMult: %f", magnitude, slideMult);

        let slideFactor : CGFloat = 0.1 * slideMult; // Increase for more of a slide
        var finalPoint : CGPoint = CGPointMake(panGest.view!.center.x + (velocity.x * slideFactor),
                                         panGest.view!.center.y + (velocity.y * slideFactor));
        finalPoint.x = min(max(finalPoint.x, 0), self.view.bounds.size.width);
        finalPoint.y = min(max(finalPoint.y, 0), self.view.bounds.size.height);

        UIView.animateWithDuration(Double(slideFactor*2), delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
            panGest.view!.center = finalPoint;
            }, completion: nil)
}

Using multiple IF statements in a batch file

is there a special guideline that should be followed

There is no "standard" way to do batch files, because the vast majority of their authors and maintainers either don't understand programming concepts, or they think they don't apply to batch files.

But I am a programmer. I'm used to compiling, and I'm used to debuggers. Batch files aren't compiled, and you can't run them through a debugger, so they make me nervous. I suggest you be extra strict on what you write, so you can be very sure it will do what you think it does.

There are some coding standards that say: If you write an if statement, you must use braces, even if you don't have an else clause. This saves you from subtle, hard-to-debug problems, and is unambiguously readable. I see no reason you couldn't apply this reasoning to batch files.

Let's take a look at your code.

IF EXIST somefile.txt IF EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt

And the IF syntax, from the command, HELP IF:

IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXISTS filename command

...

IF EXIST filename (
  command
) ELSE (
  other command
)

So you are chaining IF's as commands.

If you use the common coding-standard rule I mentioned above, you would always want to use parens. Here is how you would do so for your example code:

IF EXIST "somefile.txt" (
  IF EXIST "someotherfile.txt" (
    SET var="somefile.txt,someotherfile.txt"
  )
)

Make sure you cleanly format, and do some form of indentation. You do it in code, and you should do it in your batch scripts.

Also, you should also get in the habit of always quoting your file names, and getting the quoting right. There is some verbiage under HELP FOR and HELP SET that will help you with removing extra quotes when re-quoting strings.

Edit

From your comments, and re-reading your original question, it seems like you want to build a comma separated list of files that exist. For this case, you could simply use a bunch of if/else statements, but that would result in a bunch of duplicated logic, and would not be at all clean if you had more than two files.

A better way is to write a sub-routine that checks for a single file's existence, and appends to a variable if the file specified exists. Then just call that subroutine for each file you want to check for:

@ECHO OFF
SETLOCAL

REM Todo: Set global script variables here
CALL :MainScript
GOTO :EOF

REM MainScript()
:MainScript
  SETLOCAL

  CALL :AddIfExists "somefile.txt" "%files%" "files"
  CALL :AddIfExists "someotherfile.txt" "%files%" "files"

  ECHO.Files: %files%

  ENDLOCAL
GOTO :EOF

REM AddIfExists(filename, existingFilenames, returnVariableName)
:AddIfExists
  SETLOCAL

  IF EXIST "%~1" (
    SET "result=%~1"
  ) ELSE (
    SET "result="
  )

  (
    REM Cleanup, and return result - concatenate if necessary
    ENDLOCAL

    IF "%~2"=="" (
      SET "%~3=%result%"
    ) ELSE (
      SET "%~3=%~2,%result%"
    )
  )
GOTO :EOF

Finding the type of an object in C++

Probably embed into your objects an ID "tag" and use it to distinguish between objects of class A and objects of class B.

This however shows a flaw in the design. Ideally those methods in B which A doesn't have, should be part of A but left empty, and B overwrites them. This does away with the class-specific code and is more in the spirit of OOP.

No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here

I resolved this by adding @Transactional to the base/generic Hibernate DAO implementation class (the parent class which implements the saveOrUpdate() method inherited by the DAO I use in the main program), i.e. the @Transactional needs to be specified on the actual class which implements the method. My assumption was instead that if I declared @Transactional on the child class then it included all of the methods that were inherited by the child class. However it seems that the @Transactional annotation only applies to methods implemented within a class and not to methods inherited by a class.

Parsing huge logfiles in Node.js - read in line-by-line

I have made a node module to read large file asynchronously text or JSON. Tested on large files.

var fs = require('fs')
, util = require('util')
, stream = require('stream')
, es = require('event-stream');

module.exports = FileReader;

function FileReader(){

}

FileReader.prototype.read = function(pathToFile, callback){
    var returnTxt = '';
    var s = fs.createReadStream(pathToFile)
    .pipe(es.split())
    .pipe(es.mapSync(function(line){

        // pause the readstream
        s.pause();

        //console.log('reading line: '+line);
        returnTxt += line;        

        // resume the readstream, possibly from a callback
        s.resume();
    })
    .on('error', function(){
        console.log('Error while reading file.');
    })
    .on('end', function(){
        console.log('Read entire file.');
        callback(returnTxt);
    })
);
};

FileReader.prototype.readJSON = function(pathToFile, callback){
    try{
        this.read(pathToFile, function(txt){callback(JSON.parse(txt));});
    }
    catch(err){
        throw new Error('json file is not valid! '+err.stack);
    }
};

Just save the file as file-reader.js, and use it like this:

var FileReader = require('./file-reader');
var fileReader = new FileReader();
fileReader.readJSON(__dirname + '/largeFile.json', function(jsonObj){/*callback logic here*/});

Transport security has blocked a cleartext HTTP

Apple Document 1

Apple Document 2

There are two solutions for this :

Solutions 1 :

  1. In Info.plist file add a dictionary with key 'NSAppTransportSecurity'
  2. Add another element inside dictionary with key 'Allow Arbitrary Loads'

Plist structure should appear as shown in below image.

Solution 1

Solution 2 :

  1. In Info.plist file add a dictionary with key 'NSAppTransportSecurity'
  2. Add another element inside dictionary with key 'NSExceptionDomains'
  3. Add element with key 'MyDomainName.com' of type NSDictionary
  4. Add element with key 'NSIncludesSubdomains' of type Boolean and value set as YES
  5. Add element with key 'NSTemporaryExceptionAllowsInsecureHTTPLoads' of type Boolean and value set as YES

Plist structure should appear as shown in below image.

Solution 2

Solution 2 is preferred since it allows only selected domain whereas solution 1 allows all insecure HTTP connections.

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

I know that PHPMailer library can handle that kind of SMTP transactions.

Also, a fake sendmail with sendmail-SSL library should do the job.

Convert RGB values to Integer

I think the code is something like:

int rgb = red;
rgb = (rgb << 8) + green;
rgb = (rgb << 8) + blue;

Also, I believe you can get the individual values using:

int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;

How to work with progress indicator in flutter?

I took the following approach, which uses a simple modal progress indicator widget that wraps whatever you want to make modal during an async call.

The example in the package also addresses how to handle form validation while making async calls to validate the form (see flutter/issues/9688 for details of this problem). For example, without leaving the form, this async form validation method can be used to validate a new user name against existing names in a database while signing up.

https://pub.dartlang.org/packages/modal_progress_hud

Here is the demo of the example provided with the package (with source code):

async form validation with modal progress indicator

Example could be adapted to other modal progress indicator behaviour (like different animations, additional text in modal, etc..).

how we add or remove readonly attribute from textbox on clicking radion button in cakephp using jquery?

In your Case you can write the following jquery code:

$(document).ready(function(){

   $('.staff_on_site').click(function(){

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

     if(rBtnVal == "yes"){
         $("#no_of_staff").attr("readonly", false); 
     }
     else{ 
         $("#no_of_staff").attr("readonly", true); 
     }
   });
});

Here is the Fiddle: http://jsfiddle.net/P4QWx/3/

Capturing count from an SQL query

Complementing in C# with SQL:

SqlConnection conn = new SqlConnection("ConnectionString");
conn.Open();
SqlCommand comm = new SqlCommand("SELECT COUNT(*) FROM table_name", conn);
Int32 count = Convert.ToInt32(comm.ExecuteScalar());
if (count > 0)
{
    lblCount.Text = Convert.ToString(count.ToString()); //For example a Label
}
else
{
    lblCount.Text = "0";
}
conn.Close(); //Remember close the connection

Is there a wikipedia API just for retrieve content summary?

There's a way to get the entire "intro section" without any html parsing! Similar to AnthonyS's answer with an additional explaintext param, you can get the intro section text in plain text.

Query

Getting Stack Overflow's intro in plain text:

Using page title:

https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&titles=Stack%20Overflow

or use pageids

https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&exintro&explaintext&redirects=1&pageids=21721040

JSON Response

(warnings stripped)

{
    "query": {
        "pages": {
            "21721040": {
                "pageid": 21721040,
                "ns": 0,
                "title": "Stack Overflow",
                "extract": "Stack Overflow is a privately held website, the flagship site of the Stack Exchange Network, created in 2008 by Jeff Atwood and Joel Spolsky, as a more open alternative to earlier Q&A sites such as Experts Exchange. The name for the website was chosen by voting in April 2008 by readers of Coding Horror, Atwood's popular programming blog.\nIt features questions and answers on a wide range of topics in computer programming. The website serves as a platform for users to ask and answer questions, and, through membership and active participation, to vote questions and answers up or down and edit questions and answers in a fashion similar to a wiki or Digg. Users of Stack Overflow can earn reputation points and \"badges\"; for example, a person is awarded 10 reputation points for receiving an \"up\" vote on an answer given to a question, and can receive badges for their valued contributions, which represents a kind of gamification of the traditional Q&A site or forum. All user-generated content is licensed under a Creative Commons Attribute-ShareAlike license. Questions are closed in order to allow low quality questions to improve. Jeff Atwood stated in 2010 that duplicate questions are not seen as a problem but rather they constitute an advantage if such additional questions drive extra traffic to the site by multiplying relevant keyword hits in search engines.\nAs of April 2014, Stack Overflow has over 2,700,000 registered users and more than 7,100,000 questions. Based on the type of tags assigned to questions, the top eight most discussed topics on the site are: Java, JavaScript, C#, PHP, Android, jQuery, Python and HTML."
            }
        }
    }
}

Documentation: API: query/prop=extracts


Edit: Added &redirects=1 as recommended in comments. Edit: Added pageids example

How to filter multiple values (OR operation) in angularJS

You can use a controller function to filter.

function MoviesCtrl($scope) {

    $scope.movies = [{name:'Shrek', genre:'Comedy'},
                     {name:'Die Hard', genre:'Action'},
                     {name:'The Godfather', genre:'Drama'}];

    $scope.selectedGenres = ['Action','Drama'];

    $scope.filterByGenres = function(movie) {
        return ($scope.selectedGenres.indexOf(movie.genre) !== -1);
    };

}

HTML:

<div ng-controller="MoviesCtrl">
    <ul>
        <li ng-repeat="movie in movies | filter:filterByGenres">
            {{ movie.name }} {{ movie.genre }}
        </li>
    </ul>
</div>

How to send a html email with the bash command "sendmail"?

To follow up on the previous answer using mail :

Often times one's html output is interpreted by the client mailer, which may not format things using a fixed-width font. Thus your nicely formatted ascii alignment gets all messed up. To send old-fashioned fixed-width the way the God intended, try this:

{ echo -e "<pre>"
echo "Descriptive text here."
shell_command_1_here
another_shell_command
cat <<EOF

This is the ending text.
</pre><br>
</div>
EOF
} | mail -s "$(echo -e 'Your subject.\nContent-Type: text/html')" [email protected]

You don't necessarily need the "Descriptive text here." line, but I have found that sometimes the first line may, depending on its contents, cause the mail program to interpret the rest of the file in ways you did not intend. Try the script with simple descriptive text first, before fine tuning the output in the way that you want.

Redirect in Spring MVC

It is possible to define a urlBasedViewResolver in your properties file:

excel.(class)=fi.utu.seurantaraporttisuodatin.service.Raportti  
index.(class)=org.springframework.web.servlet.view.urlBasedView  
index.viewClass =org.springframework.web.servlet.view.JstlView  
index.prefix = /WEB-INF/jsp/  
index.suffix =.jsp

How to add new line in Markdown presentation?

How to add new line in Markdown presentation?

Check the following resource Line Return

To force a line return, place two empty spaces at the end of a line.

How do I list all tables in a schema in Oracle SQL?

select * from user_tables;

(showing all tables)

How to print VARCHAR(MAX) using Print Statement?

My PrintMax version for prevent bad line breaks on output:


    CREATE PROCEDURE [dbo].[PrintMax](@iInput NVARCHAR(MAX))
    AS
    BEGIN
      Declare @i int;
      Declare @NEWLINE char(1) = CHAR(13) + CHAR(10);
      While LEN(@iInput)>0 BEGIN
        Set @i = CHARINDEX(@NEWLINE, @iInput)
        if @i>8000 OR @i=0 Set @i=8000
        Print SUBSTRING(@iInput, 0, @i)
        Set @iInput = SUBSTRING(@iInput, @i+1, LEN(@iInput))
      END
    END

How can I merge the columns from two tables into one output?

I guess that what you want to do is an UNION of both tables.

If both tables have the same columns then you can just do

SELECT category_id, col1, col2, col3
  FROM items_a
UNION 
SELECT category_id, col1, col2, col3 
  FROM items_b

Else, you might have to do something like

SELECT category_id, col1, col2, col3
  FROM items_a 
UNION 
SELECT category_id, col_1 as col1, col_2 as col2, col_3 as col3
  FROM items_b

How to click a href link using Selenium

You can use this method:

For the links if you use linkText(); it is more effective than the any other locator.

driver.findElement(By.linkText("App Configuration")).click();

MySQL: @variable vs. variable. What's the difference?

MySQL has a concept of user-defined variables.

They are loosely typed variables that may be initialized somewhere in a session and keep their value until the session ends.

They are prepended with an @ sign, like this: @var

You can initialize this variable with a SET statement or inside a query:

SET @var = 1

SELECT @var2 := 2

When you develop a stored procedure in MySQL, you can pass the input parameters and declare the local variables:

DELIMITER //

CREATE PROCEDURE prc_test (var INT)
BEGIN
    DECLARE  var2 INT;
    SET var2 = 1;
    SELECT  var2;
END;
//

DELIMITER ;

These variables are not prepended with any prefixes.

The difference between a procedure variable and a session-specific user-defined variable is that a procedure variable is reinitialized to NULL each time the procedure is called, while the session-specific variable is not:

CREATE PROCEDURE prc_test ()
BEGIN
    DECLARE var2 INT DEFAULT 1;
    SET var2 = var2 + 1;
    SET @var2 = @var2 + 1;
    SELECT  var2, @var2;
END;

SET @var2 = 1;

CALL prc_test();

var2  @var2
---   ---
2     2


CALL prc_test();

var2  @var2
---   ---
2     3


CALL prc_test();

var2  @var2
---   ---
2     4

As you can see, var2 (procedure variable) is reinitialized each time the procedure is called, while @var2 (session-specific variable) is not.

(In addition to user-defined variables, MySQL also has some predefined "system variables", which may be "global variables" such as @@global.port or "session variables" such as @@session.sql_mode; these "session variables" are unrelated to session-specific user-defined variables.)

Using querySelectorAll to retrieve direct children

I am just doing this without even trying it. Would this work?

myDiv = getElementById("myDiv");
myDiv.querySelectorAll(this.id + " > .foo");

Give it a try, maybe it works maybe not. Apolovies, but I am not on a computer now to try it (responding from my iPhone).

HashMaps and Null values?

you can probably do it like this:

String k = null;
String v = null;
options.put(k,v);

Pandas sort by group aggregate and column

One way to do this is to insert a dummy column with the sums in order to sort:

In [10]: sum_B_over_A = df.groupby('A').sum().B

In [11]: sum_B_over_A
Out[11]: 
A
bar    0.253652
baz   -2.829711
foo    0.551376
Name: B

in [12]: df['sum_B_over_A'] = df.A.apply(sum_B_over_A.get_value)

In [13]: df
Out[13]: 
     A         B      C  sum_B_over_A
0  foo  1.624345  False      0.551376
1  bar -0.611756   True      0.253652
2  baz -0.528172  False     -2.829711
3  foo -1.072969   True      0.551376
4  bar  0.865408  False      0.253652
5  baz -2.301539   True     -2.829711

In [14]: df.sort(['sum_B_over_A', 'A', 'B'])
Out[14]: 
     A         B      C   sum_B_over_A
5  baz -2.301539   True      -2.829711
2  baz -0.528172  False      -2.829711
1  bar -0.611756   True       0.253652
4  bar  0.865408  False       0.253652
3  foo -1.072969   True       0.551376
0  foo  1.624345  False       0.551376

and maybe you would drop the dummy row:

In [15]: df.sort(['sum_B_over_A', 'A', 'B']).drop('sum_B_over_A', axis=1)
Out[15]: 
     A         B      C
5  baz -2.301539   True
2  baz -0.528172  False
1  bar -0.611756   True
4  bar  0.865408  False
3  foo -1.072969   True
0  foo  1.624345  False

How to check if an app is installed from a web-page on an iPhone?

iOS Safari has a feature that allows you to add a "smart" banner to your webpage that will link either to your app, if it is installed, or to the App Store.

You do this by adding a meta tag to the page. You can even specify a detailed app URL if you want the app to do something special when it loads.

Details are at Apple's Promoting Apps with Smart App Banners page.

The mechanism has the advantages of being easy and presenting a standardized banner. The downside is that you don't have much control over the look or location. Also, all bets are off if the page is viewed in a browser other than Safari.

Select all text inside EditText when it gets focus

You can also add an OnClick Method to the editText after

_editText.setSelectAllOnFocus(true);

and in that:

_editText.clearFocus();
_editText.requestFocus();

As soon as you click the editText the whole text is selected.

Try-catch block in Jenkins pipeline script

This answer worked for me:

pipeline {
  agent any
  stages {
    stage("Run unit tests"){
      steps {
        script {
          try {
            sh  '''
              # Run unit tests without capturing stdout or logs, generates cobetura reports
              cd ./python
              nosetests3 --with-xcoverage --nocapture --with-xunit --nologcapture --cover-package=application
              cd ..
              '''
          } finally {
            junit 'nosetests.xml'
          }
        }
      }
    }
    stage ('Speak') {
      steps{
        echo "Hello, CONDITIONAL"
      }
    }
  }
}

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

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

HTML CSS Invisible Button

You can use CSS to hide the button.

button {
  visibility: hidden;
}

If your <button> is just a clickable area on the image, why bother make it a button? You can use <map> element instead.

What is the difference between a var and val definition in Scala?

As so many others have said, the object assigned to a val cannot be replaced, and the object assigned to a var can. However, said object can have its internal state modified. For example:

class A(n: Int) {
  var value = n
}

class B(n: Int) {
  val value = new A(n)
}

object Test {
  def main(args: Array[String]) {
    val x = new B(5)
    x = new B(6) // Doesn't work, because I can't replace the object created on the line above with this new one.
    x.value = new A(6) // Doesn't work, because I can't replace the object assigned to B.value for a new one.
    x.value.value = 6 // Works, because A.value can receive a new object.
  }
}

So, even though we can't change the object assigned to x, we could change the state of that object. At the root of it, however, there was a var.

Now, immutability is a good thing for many reasons. First, if an object doesn't change internal state, you don't have to worry if some other part of your code is changing it. For example:

x = new B(0)
f(x)
if (x.value.value == 0)
  println("f didn't do anything to x")
else
  println("f did something to x")

This becomes particularly important with multithreaded systems. In a multithreaded system, the following can happen:

x = new B(1)
f(x)
if (x.value.value == 1) {
  print(x.value.value) // Can be different than 1!
}

If you use val exclusively, and only use immutable data structures (that is, avoid arrays, everything in scala.collection.mutable, etc.), you can rest assured this won't happen. That is, unless there's some code, perhaps even a framework, doing reflection tricks -- reflection can change "immutable" values, unfortunately.

That's one reason, but there is another reason for it. When you use var, you can be tempted into reusing the same var for multiple purposes. This has some problems:

  • It will be more difficult for people reading the code to know what is the value of a variable in a certain part of the code.
  • You may forget to re-initialize the variable in some code path, and end up passing wrong values downstream in the code.

Simply put, using val is safer and leads to more readable code.

We can, then, go the other direction. If val is that better, why have var at all? Well, some languages did take that route, but there are situations in which mutability improves performance, a lot.

For example, take an immutable Queue. When you either enqueue or dequeue things in it, you get a new Queue object. How then, would you go about processing all items in it?

I'll go through that with an example. Let's say you have a queue of digits, and you want to compose a number out of them. For example, if I have a queue with 2, 1, 3, in that order, I want to get back the number 213. Let's first solve it with a mutable.Queue:

def toNum(q: scala.collection.mutable.Queue[Int]) = {
  var num = 0
  while (!q.isEmpty) {
    num *= 10
    num += q.dequeue
  }
  num
}

This code is fast and easy to understand. Its main drawback is that the queue that is passed is modified by toNum, so you have to make a copy of it beforehand. That's the kind of object management that immutability makes you free from.

Now, let's covert it to an immutable.Queue:

def toNum(q: scala.collection.immutable.Queue[Int]) = {
  def recurse(qr: scala.collection.immutable.Queue[Int], num: Int): Int = {
    if (qr.isEmpty)
      num
    else {
      val (digit, newQ) = qr.dequeue
      recurse(newQ, num * 10 + digit)
    }
  }
  recurse(q, 0)
}

Because I can't reuse some variable to keep track of my num, like in the previous example, I need to resort to recursion. In this case, it is a tail-recursion, which has pretty good performance. But that is not always the case: sometimes there is just no good (readable, simple) tail recursion solution.

Note, however, that I can rewrite that code to use an immutable.Queue and a var at the same time! For example:

def toNum(q: scala.collection.immutable.Queue[Int]) = {
  var qr = q
  var num = 0
  while (!qr.isEmpty) {
    val (digit, newQ) = qr.dequeue
    num *= 10
    num += digit
    qr = newQ
  }
  num
}

This code is still efficient, does not require recursion, and you don't need to worry whether you have to make a copy of your queue or not before calling toNum. Naturally, I avoided reusing variables for other purposes, and no code outside this function sees them, so I don't need to worry about their values changing from one line to the next -- except when I explicitly do so.

Scala opted to let the programmer do that, if the programmer deemed it to be the best solution. Other languages have chosen to make such code difficult. The price Scala (and any language with widespread mutability) pays is that the compiler doesn't have as much leeway in optimizing the code as it could otherwise. Java's answer to that is optimizing the code based on the run-time profile. We could go on and on about pros and cons to each side.

Personally, I think Scala strikes the right balance, for now. It is not perfect, by far. I think both Clojure and Haskell have very interesting notions not adopted by Scala, but Scala has its own strengths as well. We'll see what comes up on the future.

How do I check that a number is float or integer?

Try these functions to test whether a value is a number primitive value that has no fractional part and is within the size limits of what can be represented as an exact integer.

function isFloat(n) {
    return n === +n && n !== (n|0);
}

function isInteger(n) {
    return n === +n && n === (n|0);
}

What is the difference between SQL and MySQL?

SQL stands for Structured Query Language, and it is a programming language designed for querying data from a database. MySQL is a relational database management system, which is a completely different thing.

MySQL is an open-source platform that uses SQL, just like MSSQL, which is Microsoft's product (not open-source) that uses SQL for database management.

How do I do a bulk insert in mySQL using node.js

Bulk insert in Node.js can be done using the below code. I have referred lots of blog for getting this work.

please refer this link as well. https://www.technicalkeeda.com/nodejs-tutorials/insert-multiple-records-into-mysql-using-nodejs

The working code.

  const educations = request.body.educations;
  let queryParams = [];
  for (let i = 0; i < educations.length; i++) {
    const education = educations[i];
    const userId = education.user_id;
    const from = education.from;
    const to = education.to;
    const instituteName = education.institute_name;
    const city = education.city;
    const country = education.country;
    const certificateType = education.certificate_type;
    const studyField = education.study_field;
    const duration = education.duration;

    let param = [
      from,
      to,
      instituteName,
      city,
      country,
      certificateType,
      studyField,
      duration,
      userId,
    ];

    queryParams.push(param);
  }

  let sql =
    "insert into tbl_name (education_from, education_to, education_institute_name, education_city, education_country, education_certificate_type, education_study_field, education_duration, user_id) VALUES ?";
  let sqlQuery = dbManager.query(sql, [queryParams], function (
    err,
    results,
    fields
  ) {
    let res;
    if (err) {
      console.log(err);
      res = {
        success: false,
        message: "Insertion failed!",
      };
    } else {
      res = {
        success: true,
        id: results.insertId,
        message: "Successfully inserted",
      };
    }

    response.send(res);
  });

Hope this will help you.

Redirect to external URI from ASP.NET MVC controller

Try this (I've used Home controller and Index View):

return RedirectToAction("Index", "Home");

Setting value of active workbook in Excel VBA

Try this.

Dim Workbk as workbook
Set Workbk = thisworkbook

Now everything you program will apply just for your containing macro workbook.

Assertion failure in dequeueReusableCellWithIdentifier:forIndexPath:

Although this question is fairly old, there is another possibility: If you are using Storyboards, you simply have to set the CellIdentifier in the Storyboard.

So if your CellIdentifier is "Cell", just set the "Identifier" property: enter image description here

Make sure to clean your build after doing so. XCode sometimes has some issues with Storyboard updates

How to save an HTML5 Canvas as an image on a server?

I just made an imageCrop and Upload feature with

https://www.npmjs.com/package/react-image-crop

to get the ImagePreview ( the cropped image rendering in a canvas)

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob

canvas.toBlob(function(blob){...}, 'image/jpeg', 0.95);

I prefer sending data in blob with content type image/jpeg rather than toDataURL ( a huge base64 string`

My implementation for uploading to Azure Blob using SAS URL

axios.post(azure_sas_url, image_in_blob, {
   headers: {
      'x-ms-blob-type': 'BlockBlob',
      'Content-Type': 'image/jpeg'
   }
})

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

I have a short version for you. It works well for me!

var match      = str.match(/[abc]/gi);
var firstIndex = str.indexOf(match[0]);
var lastIndex  = str.lastIndexOf(match[match.length-1]);

And if you want a prototype version:

String.prototype.indexOfRegex = function(regex){
  var match = this.match(regex);
  return match ? this.indexOf(match[0]) : -1;
}

String.prototype.lastIndexOfRegex = function(regex){
  var match = this.match(regex);
  return match ? this.lastIndexOf(match[match.length-1]) : -1;
}

EDIT : if you want to add support for fromIndex

String.prototype.indexOfRegex = function(regex, fromIndex){
  var str = fromIndex ? this.substring(fromIndex) : this;
  var match = str.match(regex);
  return match ? str.indexOf(match[0]) + fromIndex : -1;
}

String.prototype.lastIndexOfRegex = function(regex, fromIndex){
  var str = fromIndex ? this.substring(0, fromIndex) : this;
  var match = str.match(regex);
  return match ? str.lastIndexOf(match[match.length-1]) : -1;
}

To use it, as simple as this:

var firstIndex = str.indexOfRegex(/[abc]/gi);
var lastIndex  = str.lastIndexOfRegex(/[abc]/gi);

How to remove all files from directory without removing directory in Node.js

To remove all files from a directory, first you need to list all files in the directory using fs.readdir, then you can use fs.unlink to remove each file. Also fs.readdir will give just the file names, you need to concat with the directory name to get the full path.

Here is an example

const fs = require('fs');
const path = require('path');

const directory = 'test';

fs.readdir(directory, (err, files) => {
  if (err) throw err;

  for (const file of files) {
    fs.unlink(path.join(directory, file), err => {
      if (err) throw err;
    });
  }
});

Update node version 14

There is a recursive flag that you can use in rmdir to remove all the files recursively. See nodejs docs for more information.

const fs = require('fs').promises;

const directory = 'test';

fs.rmdir(directory, { recursive: true })
  .then(() => console.log('directory removed!'));

How to execute AngularJS controller function on page load?

When using $routeProvider you can resolve on .state and bootstrap your service. This is to say, you are going to load Controller and View, only after resolve your Service:

ui-routes

 .state('nn', {
        url: "/nn",
        templateUrl: "views/home/n.html",
        controller: 'nnCtrl',
        resolve: {
          initialised: function (ourBootstrapService, $q) {

            var deferred = $q.defer();

            ourBootstrapService.init().then(function(initialised) {
              deferred.resolve(initialised);
            });
            return deferred.promise;
          }
        }
      })

Service

function ourBootstrapService() {

 function init(){ 
    // this is what we need
 }
}

Get Mouse Position

If you're using Swing as your UI layer, you can use a Mouse-Motion Listener for this.

Calling Objective-C method from C++ member function?

Step 1

Create a objective c file(.m file) and it's corresponding header file.

// Header file (We call it "ObjCFunc.h")

#ifndef test2_ObjCFunc_h
#define test2_ObjCFunc_h
@interface myClass :NSObject
-(void)hello:(int)num1;
@end
#endif

// Corresponding Objective C file(We call it "ObjCFunc.m")

#import <Foundation/Foundation.h>
#include "ObjCFunc.h"
@implementation myClass
//Your objective c code here....
-(void)hello:(int)num1
{
NSLog(@"Hello!!!!!!");
}
@end

Step 2

Now we will implement a c++ function to call the objective c function that we just created! So for that we will define a .mm file and its corresponding header file(".mm" file is to be used here because we will be able to use both Objective C and C++ coding in the file)

//Header file(We call it "ObjCCall.h")

#ifndef __test2__ObjCCall__
#define __test2__ObjCCall__
#include <stdio.h>
class ObjCCall
{
public:
static void objectiveC_Call(); //We define a static method to call the function directly using the class_name
};
#endif /* defined(__test2__ObjCCall__) */

//Corresponding Objective C++ file(We call it "ObjCCall.mm")

#include "ObjCCall.h"
#include "ObjCFunc.h"
void ObjCCall::objectiveC_Call()
{
//Objective C code calling.....
myClass *obj=[[myClass alloc]init]; //Allocating the new object for the objective C   class we created
[obj hello:(100)];   //Calling the function we defined
}

Step 3

Calling the c++ function(which actually calls the objective c method)

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__
#include "cocos2d.h"
#include "ObjCCall.h"
class HelloWorld : public cocos2d::Layer
{
public:
// there's no 'id' in cpp, so we recommend returning the class instance pointer
static cocos2d::Scene* createScene();
// Here's a difference. Method 'init' in cocos2d-x returns bool, instead of returning  'id' in cocos2d-iphone
virtual bool init();
// a selector callback
void menuCloseCallback(cocos2d::Ref* pSender);
void ObCCall();  //definition
// implement the "static create()" method manually
CREATE_FUNC(HelloWorld);
};
#endif // __HELLOWORLD_SCENE_H__

//Final call

#include "HelloWorldScene.h"
#include "ObjCCall.h"
USING_NS_CC;
Scene* HelloWorld::createScene()
{
// 'scene' is an autorelease object
auto scene = Scene::create();
// 'layer' is an autorelease object
auto layer = HelloWorld::create();
// add layer as a child to scene
scene->addChild(layer);
// return the scene
return scene;
}
// on "init" you need to initialize your instance
bool HelloWorld::init()
{
//////////////////////////////
// 1. super init first
if ( !Layer::init() )
{
    return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
Vec2 origin = Director::getInstance()->getVisibleOrigin();

/////////////////////////////
// 2. add a menu item with "X" image, which is clicked to quit the program
//    you may modify it.

// add a "close" icon to exit the progress. it's an autorelease object
auto closeItem = MenuItemImage::create(
                                       "CloseNormal.png",
                                       "CloseSelected.png",
                                       CC_CALLBACK_1(HelloWorld::menuCloseCallback,  this));

closeItem->setPosition(Vec2(origin.x + visibleSize.width - closeItem->getContentSize().width/2 ,
                            origin.y + closeItem->getContentSize().height/2));

// create menu, it's an autorelease object
auto menu = Menu::create(closeItem, NULL);
menu->setPosition(Vec2::ZERO);
this->addChild(menu, 1);

/////////////////////////////
// 3. add your codes below...

// add a label shows "Hello World"
// create and initialize a label

auto label = Label::createWithTTF("Hello World", "fonts/Marker Felt.ttf", 24);

// position the label on the center of the screen
label->setPosition(Vec2(origin.x + visibleSize.width/2,
                        origin.y + visibleSize.height - label- >getContentSize().height));
// add the label as a child to this layer
this->addChild(label, 1);
// add "HelloWorld" splash screen"
auto sprite = Sprite::create("HelloWorld.png");
// position the sprite on the center of the screen
sprite->setPosition(Vec2(visibleSize.width/2 + origin.x, visibleSize.height/2 +     origin.y));
// add the sprite as a child to this layer
this->addChild(sprite, 0);
this->ObCCall();   //first call
return true;
}
void HelloWorld::ObCCall()  //Definition
{
ObjCCall::objectiveC_Call();  //Final Call  
}
void HelloWorld::menuCloseCallback(Ref* pSender)
{
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) || (CC_TARGET_PLATFORM ==   CC_PLATFORM_WINRT)
MessageBox("You pressed the close button. Windows Store Apps do not implement a close    button.","Alert");
return;
#endif
Director::getInstance()->end();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
exit(0);
#endif
}

Hope this works!

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

I'm finding that Tomcat can't seem to find classes defined in other projects, maybe even in the main project. It's failing on the filter definition which is the first definition in web.xml. If I add the project and its dependencies to the server's launch configuration then I just move on to a new error, all of which seems to point to it not setting up the project properly.

Our setup is quite complex. We have multiple components as projects in Eclipse with separate output projects. We have a separate webapp directory which contains the static HTML and images, as well as our WEB-INF.

Eclipse is "Europa Winter release". Tomcat is 6.0.18. I tried version 2.4 and 2.5 of the "Dynamic Web Module" facet.

Thanks for any help!

  • Richard

React Native Error: ENOSPC: System limit for number of file watchers reached

Please refer this link[1]. Visual Studio code has mentioned a brief explanation for this error message. I also encountered the same error. Adding the below parameter in the relavant file will fix this issue.

 fs.inotify.max_user_watches=524288

[1] https://code.visualstudio.com/docs/setup/linux#_visual-studio-code-is-unable-to-watch-for-file-changes-in-this-large-workspace-error-enospc

Export/import jobs in Jenkins

The most easy way, with direct access to the machine is to copy the job folder from first jenkins to another one (you can exclude workspaces - workspace folder), because the whole job configuration is stored in the xml file on the disk.

Then in the new jenkins just reload configuration in the global settings (admin access is required) should be enough, if not, then you will need to restart Jenkins tool.

Another way can be to use plugins mentioned above this post.

edit: - in case you can probably also exclude modules folders

Pipe to/from the clipboard in Bash script

on Wayland xcopy doesn't seem to work, use wl-clipboard instead. e.g. on fedora

sudo dnf install wl-clipboard

tree | wl-copy

wl-paste > file

Change the Bootstrap Modal effect

Here is pure Bootstrap 4 with CSS 3 solution.

<div class="modal fade2" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
      </div>
      <div class="modal-body">
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-primary" data-dismiss="modal">OK</button>
      </div>
    </div>
  </div>
</div>
.fade2 {
    transform: scale(0.9);
    opacity: 0;
    transition: all .2s linear;
    display: block !important;
}

.fade2.show {
    opacity: 1;
    transform: scale(1);
}
$('#exampleModal').modal();

function afterModalTransition(e) {
  e.setAttribute("style", "display: none !important;");
}
$('#exampleModal').on('hide.bs.modal', function (e) {
    setTimeout( () => afterModalTransition(this), 200);
})

Full example here.

Maybe it will help someone.

--

Thank you @DavidDomain too.

View JSON file in Browser

In Chrome, use JSONView to view formatted JSON.

To view "local" *.json files: - after install You must open the Extensions option from Window menu. - Check box next to "Allow Access to File URLs" - note that save is automatic (i.e. no explicit save necessary)

Re-open the *.json file and it should be formatted.

How to use http.client in Node.js if there is basic authorization

From Node.js http.request API Docs you could use something similar to

var http = require('http');

var request = http.request({'hostname': 'www.example.com',
                            'auth': 'user:password'
                           }, 
                           function (response) {
                             console.log('STATUS: ' + response.statusCode);
                             console.log('HEADERS: ' + JSON.stringify(response.headers));
                             response.setEncoding('utf8');
                             response.on('data', function (chunk) {
                               console.log('BODY: ' + chunk);
                             });
                           });
request.end();

How to add parameters into a WebRequest?

Hope this works

webRequest.Credentials= new NetworkCredential("API_User","API_Password");

git stash blunder: git stash pop and ended up with merge conflicts

I had a similar thing happen to me. I didn't want to stage the files just yet so I added them with git add and then just did git reset. This basically just added and then unstaged my changes but cleared the unmerged paths.

XmlSerializer: remove unnecessary xsi and xsd namespaces

//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

//Add an empty namespace and empty value
ns.Add("", "");

//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);

//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns)

How to find a value in an array and remove it by using PHP array functions?

First of all, as others mentioned, you will be using the "array_search()" & the "unset()" methodsas shown below:-

<?php
$arrayDummy = array( 'aaaa', 'bbbb', 'cccc', 'dddd', 'eeee', 'ffff', 'gggg' );
unset( $arrayDummy[array_search( 'dddd', $arrayDummy )] ); // Index 3 is getting unset here.
print_r( $arrayDummy ); // This will show the indexes as 0, 1, 2, 4, 5, 6.
?>

Now to re-index the same array, without sorting any of the array values, you will need to use the "array_values()" method as shown below:-

<?php
$arrayDummy = array_values( $arrayDummy );
print_r( $arrayDummy ); // Now, you will see the indexes as 0, 1, 2, 3, 4, 5.
?>

Hope it helps.

Adding one day to a date

<?php

function plusTimetoOldtime($Old_Time,$getFormat,$Plus_Time) {
    return date($getFormat,strtotime(date($getFormat,$Old_Time).$Plus_Time));
}

$Old_Time = strtotime("now");
$Plus_Time = '+1 day';
$getFormat = 'Y-m-d H:i:s';

echo plusTimetoOldtime($Old_Time,$getFormat,$Plus_Time);

?>

printing all contents of array in C#

You can use for loop

    int[] random_numbers = {10, 30, 44, 21, 51, 21, 61, 24, 14}
    int array_length = random_numbers.Length;
    for (int i = 0; i < array_length; i++){
        if(i == array_length - 1){
              Console.Write($"{random_numbers[i]}\n");
        } else{
              Console.Write($"{random_numbers[i]}, ");
         }
     }

Difference between nVidia Quadro and Geforce cards?

Surfing the web, you will find many technical justifications for Quadro price. Real answer is in "demand for reliable and task specific graphic cards".

Imagine you have an architectural firm with many fat projects on deadline. Your computers are only used in working with one specific CAD software. If foundation of your business is supposed to rely on these computers, you would want to make sure this foundation is strong.

For such clients, Nvidia engineered cards like Quadro, providing what they call "Professional Solution". And if you are among the targeted clients, you would really appreciate reliability of these graphic cards.

Many believe Geforce have become powerful and reliable enough to take Quadro's place. But in the end, it depends on the software you are mostly going to use and importance of reliability in what you do.

RestSharp JSON Parameter Posting

Here is complete console working application code. Please install RestSharp package.

using RestSharp;
using System;

namespace RESTSharpClient
{
    class Program
    {
        static void Main(string[] args)
        {
        string url = "https://abc.example.com/";
        string jsonString = "{" +
                "\"auth\": {" +
                    "\"type\" : \"basic\"," +
                    "\"password\": \"@P&p@y_10364\"," +
                    "\"username\": \"prop_apiuser\"" +
                "}," +
                "\"requestId\" : 15," +
                "\"method\": {" +
                    "\"name\": \"getProperties\"," +
                    "\"params\": {" +
                        "\"showAllStatus\" : \"0\"" +
                    "}" +
                "}" +
            "}";

        IRestClient client = new RestClient(url);
        IRestRequest request = new RestRequest("api/properties", Method.POST, DataFormat.Json);
        request.AddHeader("Content-Type", "application/json; CHARSET=UTF-8");
        request.AddJsonBody(jsonString);

        var response = client.Execute(request);
        Console.WriteLine(response.Content);
        //TODO: do what you want to do with response.
    }
  }
}

ES6 modules in the browser: Uncaught SyntaxError: Unexpected token import

Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="..."> it will work.

Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module

Laravel blade check empty foreach

You should use empty()

@if (!empty($status->replies)) 

<div class="media-body reply-body">
    @foreach ($status->replies as $reply)
        <p>{{ $reply->body }}</p>
    @endforeach
</div>

@endif

You can use count, but if the array is larger it takes longer, if you only need to know if its empty, empty is the better one to use.

When to use async false and async true in ajax function in jquery

In basic terms synchronous requests wait for the response to be received from the request before it allows any code processing to continue. At first this may seem like a good thing to do, but it absolutely is not.

As mentioned, while the request is in process the browser will halt execution of all script and also rendering of the UI as the JS engine of the majority of browsers is (effectively) single-threaded. This means that to your users the browser will appear unresponsive and they may even see OS-level warnings that the program is not responding and to ask them if its process should be ended. It's for this reason that synchronous JS has been deprecated and you see warnings about its use in the devtools console.

The alternative of asynchronous requests is by far the better practice and should always be used where possible. This means that you need to know how to use callbacks and/or promises in order to handle the responses to your async requests when they complete, and also how to structure your JS to work with this pattern. There are many resources already available covering this, this, for example, so I won't go into it here.

There are very few occasions where a synchronous request is necessary. In fact the only one I can think of is when making a request within the beforeunload event handler, and even then it's not guaranteed to work.

In summary. you should look to learn and employ the async pattern in all requests. Synchronous requests are now an anti-pattern which cause more issues than they generally solve.

"An attempt was made to load a program with an incorrect format" even when the platforms are the same

A bit off topic for this post, but searching for this error message brought me here.

If you are building through team system and getting this error, the build definition process tab has a "MSBuild Platform" setting. If this is set to "Auto", you may experience this problem. Changing it to "X86" can also resolve the error.

Declare an empty two-dimensional array in Javascript?

ES6

Matrix m with size 3 rows and 5 columns (remove .fill(0) to not init by zero)

[...Array(3)].map(x=>Array(5).fill(0))       

_x000D_
_x000D_
let Array2D = (r,c) => [...Array(r)].map(x=>Array(c).fill(0));

let m = Array2D(3,5);

m[1][0] = 2;  // second row, first column
m[2][4] = 8;  // last row, last column

// print formated array
console.log(JSON.stringify(m)
  .replace(/(\[\[)(.*)(\]\])/g,'[\n  [$2]\n]').replace(/],/g,'],\n  ')
);
_x000D_
_x000D_
_x000D_

How to add a custom Ribbon tab using VBA?

In addition to Roi-Kyi Bryant answer, this code fully works in Excel 2010. Press ALT + F11 and VBA editor will pop up. Double click on ThisWorkbook on the left side, then paste this code:

Private Sub Workbook_Activate()

Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String

hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"

ribbonXML = "<mso:customUI      xmlns:mso='http://schemas.microsoft.com/office/2009/07/customui'>" & vbNewLine
ribbonXML = ribbonXML + "  <mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "    <mso:qat/>" & vbNewLine
ribbonXML = ribbonXML + "    <mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + "      <mso:tab id='reportTab' label='My Actions' insertBeforeQ='mso:TabFormat'>" & vbNewLine
ribbonXML = ribbonXML + "        <mso:group id='reportGroup' label='Reports' autoScale='true'>" & vbNewLine
ribbonXML = ribbonXML + "          <mso:button id='runReport' label='Trim' " & vbNewLine
ribbonXML = ribbonXML + "imageMso='AppointmentColor3'      onAction='TrimSelection'/>" & vbNewLine
ribbonXML = ribbonXML + "        </mso:group>" & vbNewLine
ribbonXML = ribbonXML + "      </mso:tab>" & vbNewLine
ribbonXML = ribbonXML + "    </mso:tabs>" & vbNewLine
ribbonXML = ribbonXML + "  </mso:ribbon>" & vbNewLine
ribbonXML = ribbonXML + "</mso:customUI>"

ribbonXML = Replace(ribbonXML, """", "")

Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile

End Sub

Private Sub Workbook_Deactivate()

Dim hFile As Long
Dim path As String, fileName As String, ribbonXML As String, user As String

hFile = FreeFile
user = Environ("Username")
path = "C:\Users\" & user & "\AppData\Local\Microsoft\Office\"
fileName = "Excel.officeUI"

ribbonXML = "<mso:customUI           xmlns:mso=""http://schemas.microsoft.com/office/2009/07/customui"">" & _
"<mso:ribbon></mso:ribbon></mso:customUI>"

Open path & fileName For Output Access Write As hFile
Print #hFile, ribbonXML
Close hFile

End Sub

Don't forget to save and re-open workbook. Hope this helps!

Permission denied (publickey) when SSH Access to Amazon EC2 instance

I solved the problem just putting sudo before

sudo ssh -i mykey.pem myec2.amazonaws.com

But the proper solution is to change the ownership first, and then connect as a normal user as Janus Troelsen said below. In my case it would be:

chown wellington:wellington key.pem

Adding a 'share by email' link to website

<a target="_blank" title="Share this page" href="http://www.sharethis.com/share?url=[INSERT URL]&title=[INSERT TITLE]&summary=[INSERT SUMMARY]&img=[INSERT IMAGE URL]&pageInfo=%7B%22hostname%22%3A%22[INSERT DOMAIN NAME]%22%2C%22publisher%22%3A%22[INSERT PUBLISHERID]%22%7D"><img width="86" height="25" alt="Share this page" src="http://w.sharethis.com/images/share-classic.gif"></a>

Instructions

First, insert these lines wherever you want within your newsletter code. Then:

  1. Change "INSERT URL" to whatever website holds the shared content.
  2. Change "INSERT TITLE" to the title of the article.
  3. Change "INSERT SUMMARY" to a short summary of the article.
  4. Change "INSERT IMAGE URL" to an image that will be shared with the rest of the content.
  5. Change "INSERT DOMAIN NAME" to your domain name.
  6. Change "INSERT PUBLISHERID" to your publisher ID (if you have an account, if not, remove "[INSERT PUBLISHERID]" or sign up!)

If you are using this on an email newsletter, make sure you add our sharing buttons to the destination page. This will ensure that you get complete sharing analytics for your page. Make sure you replace "INSERT PUBLISHERID" with your own.

Find the location of a character in string

You can make the output just 4 and 24 using unlist:

unlist(gregexpr(pattern ='2',"the2quickbrownfoxeswere2tired"))
[1]  4 24

What is the best collation to use for MySQL with PHP?

In your database upload file, add the followin line before any line:

SET NAMES utf8;

And your problem should be solved.

AngularJS - difference between pristine/dirty and touched/untouched

$pristine/$dirty tells you whether the user actually changed anything, while $touched/$untouched tells you whether the user has merely been there/visited.

This is really useful for validation. The reason for $dirty was always to avoid showing validation responses until the user has actually visited a certain control. But, by using only the $dirty property, the user wouldn't get validation feedback unless they actually altered the value. So, an $invalid field still wouldn't show the user a prompt if the user didn't change/interact with the value. If the user entirely ignored a required field, everything looked OK.

With Angular 1.3 and ng-touched, you can now set a particular style on a control as soon as the user has blurred, regardless of whether they actually edited the value or not.

Here's a CodePen that shows the difference in behavior.

How to update Ruby to 1.9.x on Mac?

As The Tin Man suggests (above) RVM (Ruby Version Manager) is the Standard for upgrading your Ruby installation on OSX: https://rvm.io

To get started, open a Terminal Window and issue the following command:

\curl -L https://get.rvm.io | bash -s stable --ruby

( you will need to trust the RVM Dev Team that the command is not malicious - if you're a paranoid penguin like me, you can always go read the source: https://github.com/wayneeseguin/rvm ) When it's complete you need to restart the terminal to get the rvm command working.

rvm list known

( shows you the latest available versions of Ruby )

rvm install ruby-2.3.1

For a specific version, followed by

rvm use ruby-2.3.1

or if you just want the latest (current) version:

rvm install current && rvm use current

( installs the current stable release - at time of writing ruby-2.3.1 - please update this wiki when new versions released )

Note on Compiling Ruby: In my case I also had to install Homebrew http://mxcl.github.com/homebrew/ to get the gems I needed (RSpec) which in turn forces you to install Xcode (if you haven't already) https://itunes.apple.com/us/app/xcode/id497799835 AND/OR install the GCC package from: https://github.com/kennethreitz/osx-gcc-installer to avoid errors running "make".

Edit: As of Mavericks you can choose to install only the Xcode command line tools instead of the whole Xcode package, which comes with gcc and lots of other things you might need for building packages. It can be installed by running xcode-select --install and following the on-screen prompt.

Note on erros: if you get the error "RVM is not a function" while trying this command, visit: How do I change my Ruby version using RVM? for the solution.

invalid target release: 1.7

In IntelliJ IDEA this happened to me when I imported a project that had been working fine and running with Java 1.7. I apparently hadn't notified IntelliJ that java 1.7 had been installed on my machine, and it wasn't finding my $JAVA_HOME.

On a Mac, this is resolved by:

Right clicking on the module | Module Settings | Project

and adding the 1.7 SDK by selecting "New" in the Project SDK.

Then go to the main IntelliJ IDEA menu | Preferences | Maven | Runner

and select the correct JRE. In my case it updated correctly Use Project SDK, which was now 1.7.

CSS to make table 100% of max-width

max-width is definitely not well supported. If you're going to use it, use it in a media query in your style tag. ios, android, and windows phone default mail all support them. (gmail and outlook mobile don't)

http://www.campaignmonitor.com/guides/mobile/targeting/

Look at the starbucks example at the bottom

Create session factory in Hibernate 4

The following expresses the experience I had with hibernate 4.0.0.Final.

The javadoc (distributed under LGPL license) of org.hibernate.cfg.Configuration class states that:

NOTE : This will be replaced by use of ServiceRegistryBuilder and org.hibernate.metamodel.MetadataSources instead after the 4.0 release at which point this class will become deprecated and scheduled for removal in 5.0. See HHH-6183, HHH-2578 and HHH-6586 for details

After looking at issue 2578, i used something like this:

ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().configure().buildServiceRegistry();
MetadataSources metadataSources = new MetadataSources(serviceRegistry);
metadataSources.addResource("some_mapping.hbm.xml")
SessionFactory sessionFactory = metadataSources.buildMetadata().buildSessionFactory();

For it to start reading configuration, i had to modify my hibernate 3.2.6 configuration and mapping files to use xmlns="http://www.hibernate.org/xsd/hibernate-configuration" and xmlns="http://www.hibernate.org/xsd/hibernate-mapping" and also remove the dtd specifications.

I couldn't find a way for it to inspect mappings defined in hibernate.cfg.xml and hibernate. prefix for hibernate-related properties in hibernate.cfg.xml is no longer optional.

This might work for some.

I, for one, ran into some error because mapping files contained <cache usage="read-write" /> and ended up using deprecated Configuration way:

Configuration configuration = new Configuration().configure();
SessionFactoryImpl sessionFactory = (SessionFactoryImpl) configuration.buildSessionFactory();
EventListenerRegistry listenerRegistry = sessionFactory.getServiceRegistry().getService(EventListenerRegistry.class);
SolrIndexEventListener indexListener = new SolrIndexEventListener(); // a SaveOrUpdateEventListener i wanted to attach
listenerRegistry.appendListeners(EventType.SAVE_UPDATE, indexListener);

I had to programatically append event listeners because Configuration no longer looks for them in hibernate.cfg.xml

Running a command in a new Mac OS X Terminal window

I've been trying to do this for a while. Here is a script that changes to the same working directory, runs the command, and closes the terminal window.

#!/bin/sh 
osascript <<END 
tell application "Terminal"
    do script "cd \"`pwd`\";$1;exit"
end tell
END

Move / Copy File Operations in Java

Here's how to do this with java.nio operations:

public static void copyFile(File sourceFile, File destFile) throws IOException {
    if(!destFile.exists()) {
        destFile.createNewFile();
    }

    FileChannel source = null;
    FileChannel destination = null;
    try {
        source = new FileInputStream(sourceFile).getChannel();
        destination = new FileOutputStream(destFile).getChannel();

        // previous code: destination.transferFrom(source, 0, source.size());
        // to avoid infinite loops, should be:
        long count = 0;
        long size = source.size();              
        while((count += destination.transferFrom(source, count, size-count))<size);
    }
    finally {
        if(source != null) {
            source.close();
        }
        if(destination != null) {
            destination.close();
        }
    }
}

Why does Git treat this text file as a binary file?

This is also caused (on Windows at least) by text files that have UTF-8 with BOM encoding. Changing the encoding to regular UTF-8 immediately made Git see the file as type=text

Change the location of the ~ directory in a Windows install of Git Bash

I'd share what I did, which works not only for Git, but MSYS/MinGW as well.

The HOME environment variable is not normally set for Windows applications, so creating it through Windows did not affect anything else. From the Computer Properties (right-click on Computer - or whatever it is named - in Explorer, and select Properties, or Control Panel -> System and Security -> System), choose Advanced system settings, then Environment Variables... and create a new one, HOME, and assign it wherever you like.

If you can't create new environment variables, the other answer will still work. (I went through the details of how to create environment variables precisely because it's so dificult to find.)

Number of days between past date and current date in Google spreadsheet

  1. Today() does return value in DATE format.

  2. Select your "Days left field" and paste this formula in the field =DAYS360(today(),C2)

  3. Go to Format > Number > More formats >Custom number format and select the number with no decimal numbers.

I tested, it works, at least in new version of Sheets, March 2015.

Java LinkedHashMap get first or last entry

Though linkedHashMap doesn't provide any method to get first, last or any specific object.

But its pretty trivial to get :

Map<Integer,String> orderMap = new LinkedHashMap<Integer,String>();  
Set<Integer> al =   orderMap.keySet();

now using iterator on al object ; you can get any object.

How to stash my previous commit?

If it were me, I would avoid any risky revision editing and do the following instead:

  1. Create a new branch on the SHA where 222 was committed, basically as a bookmark.

  2. Switch back to the main branch. In it, revert commit 222.

  3. Push all the commits that have been made, which will push commit 111 only, because 222 was reverted.

  4. Work on the branch from step #1 if needed. Merge from the trunk to it as needed to keep it up to date. I wouldn't bother with stash.

When it's time for the changes in commit 222 to go in, that branch can be merged to trunk.

Get changes from master into branch in Git

Scenario :

  • I created a branch from master say branch-1 and pulled it to my local.
  • My Friend created a branch from master say branch-2.
  • He committed some code changes to master.
  • Now I want to take those changes from master branch to my local branch.

Solution

git stash // to save all existing changes in local branch
git checkout master // Switch to master branch from branch-1
git pull // take changes from the master
git checkout branch-1 // switchback to your own branch
git rebase master // merge all the changes and move you git head  forward
git stash apply // reapply all you saved changes 

You can find conflicts on your file after executing "git stash apply". You need to fix it manually and now you are ready to push.

How to use google maps without api key

Now you must have API key. You can generate that in google developer console. Here is LINK to the explanation.

Fatal error: Cannot use object of type stdClass as array in

Controller (Example: User.php)

<?php
defined('BASEPATH') or exit('No direct script access allowed');

class Users extends CI_controller
{

    // Table
    protected  $table = 'users';

    function index()
    {
        $data['users'] = $this->model->ra_object($this->table);
        $this->load->view('users_list', $data);
    }
}

View (Example: users_list.php)

<table>
    <thead>
        <tr>
            <th>Name</th>
            <th>Surname</th>
        </tr>
    </thead>

    <tbody>
        <?php foreach($users as $user) : ?>
            <tr>
            <td><?php echo $user->name; ?></td>
            <td><?php echo $user->surname; ?></th>
        </tr>
        <?php endforeach; ?>
    </tbody>
</table>
<!-- // User table -->

IIS AppPoolIdentity and file system write access permissions

The ApplicationPoolIdentity is assigned membership of the Users group as well as the IIS_IUSRS group. On first glance this may look somewhat worrying, however the Users group has somewhat limited NTFS rights.

For example, if you try and create a folder in the C:\Windows folder then you'll find that you can't. The ApplicationPoolIdentity still needs to be able to read files from the windows system folders (otherwise how else would the worker process be able to dynamically load essential DLL's).

With regard to your observations about being able to write to your c:\dump folder. If you take a look at the permissions in the Advanced Security Settings, you'll see the following:

enter image description here

See that Special permission being inherited from c:\:

enter image description here

That's the reason your site's ApplicationPoolIdentity can read and write to that folder. That right is being inherited from the c:\ drive.

In a shared environment where you possibly have several hundred sites, each with their own application pool and Application Pool Identity, you would store the site folders in a folder or volume that has had the Users group removed and the permissions set such that only Administrators and the SYSTEM account have access (with inheritance).

You would then individually assign the requisite permissions each IIS AppPool\[name] requires on it's site root folder.

You should also ensure that any folders you create where you store potentially sensitive files or data have the Users group removed. You should also make sure that any applications that you install don't store sensitive data in their c:\program files\[app name] folders and that they use the user profile folders instead.

So yes, on first glance it looks like the ApplicationPoolIdentity has more rights than it should, but it actually has no more rights than it's group membership dictates.

An ApplicationPoolIdentity's group membership can be examined using the SysInternals Process Explorer tool. Find the worker process that is running with the Application Pool Identity you're interested in (you will have to add the User Name column to the list of columns to display:

enter image description here

For example, I have a pool here named 900300 which has an Application Pool Identity of IIS APPPOOL\900300. Right clicking on properties for the process and selecting the Security tab we see:

enter image description here

As we can see IIS APPPOOL\900300 is a member of the Users group.

Why check both isset() and !empty()

  • From the PHP Web site, referring to the empty() function:

Returns FALSE if var has a non-empty and non-zero value.

That’s a good thing to know. In other words, everything from NULL, to 0 to “” will return TRUE when using the empty() function.

  • Here is the description of what the isset() function returns:

Returns TRUE if var exists; FALSE otherwise.

In other words, only variables that don’t exist (or, variables with strictly NULL values) will return FALSE on the isset() function. All variables that have any type of value, whether it is 0, a blank text string, etc. will return TRUE.

Child inside parent with min-height: 100% not inheriting height

Kushagra Gour's solution does work (at least in Chrome and IE) and solves the original problem without having to use display: table; and display: table-cell;. See plunker: http://plnkr.co/edit/ULEgY1FDCsk8yiRTfOWU

Setting min-height: 100%; height: 1px; on the outer div causes its actual height to be at least 100%, as required. It also allows the inner div to correctly inherit the height.

How to add a progress bar to a shell script?

I have built on the answer provided by fearside

This connects to an Oracle database to retrieve the progress of an RMAN restore.

#!/bin/bash

 # 1. Create ProgressBar function
 # 1.1 Input is currentState($1) and totalState($2)
 function ProgressBar {
 # Process data
let _progress=(${1}*100/${2}*100)/100
let _done=(${_progress}*4)/10
let _left=40-$_done
# Build progressbar string lengths
_fill=$(printf "%${_done}s")
_empty=$(printf "%${_left}s")

# 1.2 Build progressbar strings and print the ProgressBar line
# 1.2.1 Output example:
# 1.2.1.1 Progress : [########################################] 100%
printf "\rProgress : [${_fill// /#}${_empty// /-}] ${_progress}%%"

}

function rman_check {
sqlplus -s / as sysdba <<EOF
set heading off
set feedback off
select
round((sofar/totalwork) * 100,0) pct_done
from
v\$session_longops
where
totalwork > sofar
AND
opname NOT LIKE '%aggregate%'
AND
opname like 'RMAN%';
exit
EOF
}

# Variables
_start=1

# This accounts as the "totalState" variable for the ProgressBar function
_end=100

_rman_progress=$(rman_check)
#echo ${_rman_progress}

# Proof of concept
#for number in $(seq ${_start} ${_end})

while [ ${_rman_progress} -lt 100 ]
do

for number in _rman_progress
do
sleep 10
ProgressBar ${number} ${_end}
done

_rman_progress=$(rman_check)

done
printf '\nFinished!\n'

how to call javascript function in html.actionlink in asp.net mvc?

<a onclick="MyFunc()">blabla..</a>

There is nothing more in @Html.ActionLink that you could utilize in this case. And razor is evel by itself, drop it from where you can.

Find mouse position relative to element

function myFunction(e) {
    var x =  e.clientX - e.currentTarget.offsetLeft ; 
    var y = e.clientY - e.currentTarget.offsetTop ;
}

this works ok!

What is the connection string for localdb for version 11

This is a fairly old thread, but since I was reinstalling my Visual Studio 2015 Community today, I thought I might add some info on what to use on VS2015, or what might work in general.

To see which instances were installed by default, type sqllocaldb info inside a command prompt. On my machine, I get two instances, the first one named MSSQLLocalDB.

C:\>sqllocaldb info
MSSQLLocalDB
ProjectsV13

You can also create a new instance if you wish, using sqllocaldb create "some_instance_name", but the default one will work just fine:

// if not using a verbatim string literal, don't forget to escape backslashes
@"Server=(localdb)\MSSQLLocalDB;Integrated Security=true;"

Remove first Item of the array (like popping from stack)

There is a function called shift(). It will remove the first element of your array.

There is some good documentation and examples.

How to create a stopwatch using JavaScript?

jsbin.com demo

You'll see the demo code is just a start/stop/reset millisecond counter. If you want to do fanciful formatting on the time, that's completely up to you. This should be more than enough to get you started.

This was a fun little project to work on. Here's how I'd approach it

var Stopwatch = function(elem, options) {

  var timer       = createTimer(),
      startButton = createButton("start", start),
      stopButton  = createButton("stop", stop),
      resetButton = createButton("reset", reset),
      offset,
      clock,
      interval;

  // default options
  options = options || {};
  options.delay = options.delay || 1;

  // append elements     
  elem.appendChild(timer);
  elem.appendChild(startButton);
  elem.appendChild(stopButton);
  elem.appendChild(resetButton);

  // initialize
  reset();

  // private functions
  function createTimer() {
    return document.createElement("span");
  }

  function createButton(action, handler) {
    var a = document.createElement("a");
    a.href = "#" + action;
    a.innerHTML = action;
    a.addEventListener("click", function(event) {
      handler();
      event.preventDefault();
    });
    return a;
  }

  function start() {
    if (!interval) {
      offset   = Date.now();
      interval = setInterval(update, options.delay);
    }
  }

  function stop() {
    if (interval) {
      clearInterval(interval);
      interval = null;
    }
  }

  function reset() {
    clock = 0;
    render();
  }

  function update() {
    clock += delta();
    render();
  }

  function render() {
    timer.innerHTML = clock/1000; 
  }

  function delta() {
    var now = Date.now(),
        d   = now - offset;

    offset = now;
    return d;
  }

  // public API
  this.start  = start;
  this.stop   = stop;
  this.reset  = reset;
};

Get some basic HTML wrappers for it

<!-- create 3 stopwatches -->
<div class="stopwatch"></div>
<div class="stopwatch"></div>
<div class="stopwatch"></div>

Usage is dead simple from there

var elems = document.getElementsByClassName("stopwatch");

for (var i=0, len=elems.length; i<len; i++) {
  new Stopwatch(elems[i]);
}

As a bonus, you get a programmable API for the timers as well. Here's a usage example

var elem = document.getElementById("my-stopwatch");
var timer = new Stopwatch(elem, {delay: 10});

// start the timer
timer.start();

// stop the timer
timer.stop();

// reset the timer
timer.reset();

jQuery plugin

As for the jQuery portion, once you have nice code composition as above, writing a jQuery plugin is easy mode

(function($) {

  var Stopwatch = function(elem, options) {
    // code from above...
  };

  $.fn.stopwatch = function(options) {
    return this.each(function(idx, elem) {
      new Stopwatch(elem, options);
    });
  };
})(jQuery);

jQuery plugin usage

// all elements with class .stopwatch; default delay (1 ms)
$(".stopwatch").stopwatch();

// a specific element with id #my-stopwatch; custom delay (10 ms)
$("#my-stopwatch").stopwatch({delay: 10});

Excel column number from column name

Based on Anastasiya's answer. I think this is the shortest vba command:

Option Explicit

Sub Sample()
    Dim sColumnLetter as String
    Dim iColumnNumber as Integer

    sColumnLetter = "C"
    iColumnNumber = Columns(sColumnLetter).Column

    MsgBox "The column number is " & iColumnNumber
End Sub

Caveat: The only condition for this code to work is that a worksheet is active, because Columns is equivalent to ActiveSheet.Columns. ;)

How to set environment variables in Python?

Environment variables must be strings, so use

os.environ["DEBUSSY"] = "1"

to set the variable DEBUSSY to the string 1.

To access this variable later, simply use:

print(os.environ["DEBUSSY"])

Child processes automatically inherit the environment variables of the parent process -- no special action on your part is required.

Double precision - decimal places

Decimal representation of floating point numbers is kind of strange. If you have a number with 15 decimal places and convert that to a double, then print it out with exactly 15 decimal places, you should get the same number. On the other hand, if you print out an arbitrary double with 15 decimal places and the convert it back to a double, you won't necessarily get the same value back—you need 17 decimal places for that. And neither 15 nor 17 decimal places are enough to accurately display the exact decimal equivalent of an arbitrary double. In general, you need over 100 decimal places to do that precisely.

See the Wikipedia page for double-precision and this article on floating-point precision.

How to use nanosleep() in C? What are `tim.tv_sec` and `tim.tv_nsec`?

Half a second is 500,000,000 nanoseconds, so your code should read:

tim.tv_sec  = 0;
tim.tv_nsec = 500000000L;

As things stand, you code is sleeping for 1.0000005s (1s + 500ns).

How to change Visual Studio 2012,2013 or 2015 License Key?

I had the same problem and wanted to change the product key to another. Unfortunate it's not as easy as it was on VS2010.

The following steps work:

  • Remove the registry key containing the license information: HKEY_CLASSES_ROOT\Licenses\77550D6B-6352-4E77-9DA3-537419DF564B

  • If you can't find the key, use sysinternals ProcessMonitor to check the registry access of VS2012 to locate the correct key which is always in HKEY_CLASSES_ROOT\Licenses

  • After you remove this key, VS2012 will tell you that it's license information is incorrect. Go to "Programs and features" and repair VS2012.

  • After the repair, VS2012 is reverted to a 30 day trial and you can enter a new product key. This could also be used to stay in a trial version loop and never enter a producy key.

setup.py examples?

You may find the HitchHiker's Guide to Packaging helpful, even though it is incomplete. I'd start with the Quick Start tutorial. Try also just browsing through Python packages on the Python Package Index. Just download the tarball, unpack it, and have a look at the setup.py file. Or even better, only bother looking through packages that list a public source code repository such as one hosted on GitHub or BitBucket. You're bound to run into one on the front page.

My final suggestion is to just go for it and try making one; don't be afraid to fail. I really didn't understand it until I started making them myself. It's trivial to create a new package on PyPI and just as easy to remove it. So, create a dummy package and play around.

How to get difference between two rows for a column field?

Query to Find the date difference between 2 rows of a single column

SELECT
Column name,
DATEDIFF(
(SELECT MAX(date) FROM table name WHERE Column name < b. Column name),
Column name) AS days_since_last
FROM table name AS b

MVC Calling a view from a different controller

You can move you read.aspx view to Shared folder. It is standard way in such circumstances

check if variable is dataframe

Use the built-in isinstance() function.

import pandas as pd

def f(var):
    if isinstance(var, pd.DataFrame):
        print("do stuff")

Cleanest way to build an SQL string in Java

Google provides a library called the Room Persitence Library which provides a very clean way of writing SQL for Android Apps, basically an abstraction layer over underlying SQLite Database. Bellow is short code snippet from the official website:

@Dao
public interface UserDao {
    @Query("SELECT * FROM user")
    List<User> getAll();

    @Query("SELECT * FROM user WHERE uid IN (:userIds)")
    List<User> loadAllByIds(int[] userIds);

    @Query("SELECT * FROM user WHERE first_name LIKE :first AND "
           + "last_name LIKE :last LIMIT 1")
    User findByName(String first, String last);

    @Insert
    void insertAll(User... users);

    @Delete
    void delete(User user);
}

There are more examples and better documentation in the official docs for the library.

There is also one called MentaBean which is a Java ORM. It has nice features and seems to be pretty simple way of writing SQL.

PKIX path building failed: unable to find valid certification path to requested target

Here is the solution that I used for installing a site's public cert into the systems keystore for use.

Download the certificate with the following command:

unix, linux, mac

openssl s_client -connect [host]:[port|443] < /dev/null | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > [host].crt

windows

openssl s_client -connect [host]:[port|443] < NUL | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > [host].crt

That will create a crt that can be used to import into a keystore.

Install the new certificate with the command:

keytool -import -alias "[host]" -keystore [path to keystore] -file [host].crt

This will allow you to import the new cert from the site that is causing the exception.

How to specify the JDK version in android studio?

For new Android Studio versions, go to C:\Program Files\Android\Android Studio\jre\bin(or to location of Android Studio installed files) and open command window at this location and type in following command in command prompt:-

java -version

How do I set the default value for an optional argument in Javascript?

ES6 Update - ES6 (ES2015 specification) allows for default parameters

The following will work just fine in an ES6 (ES015) environment...

function(nodeBox, str="hai")
{
  // ...
}

How do I find if a string starts with another string in Ruby?

The method mentioned by steenslag is terse, and given the scope of the question it should be considered the correct answer. However it is also worth knowing that this can be achieved with a regular expression, which if you aren't already familiar with in Ruby, is an important skill to learn.

Have a play with Rubular: http://rubular.com/

But in this case, the following ruby statement will return true if the string on the left starts with 'abc'. The \A in the regex literal on the right means 'the beginning of the string'. Have a play with rubular - it will become clear how things work.

'abcdefg' =~  /\Aabc/ 

Error: More than one module matches. Use skip-import option to skip importing the component into the closest module

when you have more than one module, you need to specify module name

 ng g c componentName --module=modulename.module 

Error Dropping Database (Can't rmdir '.test\', errno: 17)

In my case I didn't see any tables under my database on phpMyAdmin I am using Wamp server but when I checked the directory under C:\wamp\bin\mysql\mysql5.6.12\data I found this employed.ibd when I deleted this file manually I was able to drop the database from phpMyAdmin smoothly without any problems.

Material Design not styling alert dialogs

UPDATED ON Aug 2019 WITH The Material components for android library:

With the new Material components for Android library you can use the new com.google.android.material.dialog.MaterialAlertDialogBuilder class, which extends from the existing androidx.appcompat.AlertDialog.Builder class and provides support for the latest Material Design specifications.

Just use something like this:

new MaterialAlertDialogBuilder(context)
            .setTitle("Dialog")
            .setMessage("Lorem ipsum dolor ....")
            .setPositiveButton("Ok", /* listener = */ null)
            .setNegativeButton("Cancel", /* listener = */ null)
            .show();

You can customize the colors extending the ThemeOverlay.MaterialComponents.MaterialAlertDialog style:

  <style name="CustomMaterialDialog" parent="@style/ThemeOverlay.MaterialComponents.MaterialAlertDialog">
     <!-- Background Color-->
     <item name="android:background">#006db3</item>
     <!-- Text Color for title and message -->
     <item name="colorOnSurface">@color/secondaryColor</item>
     <!-- Text Color for buttons -->
     <item name="colorPrimary">@color/white</item> 
     ....
  </style>  

To apply your custom style just use the constructor:

new MaterialAlertDialogBuilder(context, R.style.CustomMaterialDialog)

enter image description here

To customize the buttons, the title and the body text check this post for more details.

You can also change globally the style in your app theme:

 <!-- Base application theme. -->
 <style name="AppTheme" parent="Theme.MaterialComponents.Light">
    ...
    <item name="materialAlertDialogTheme">@style/CustomMaterialDialog</item>
 </style>

WITH SUPPORT LIBRARY and APPCOMPAT THEME:

With the new AppCompat v22.1 you can use the new android.support.v7.app.AlertDialog.

Just use a code like this:

import android.support.v7.app.AlertDialog

AlertDialog.Builder builder =
       new AlertDialog.Builder(this, R.style.AppCompatAlertDialogStyle);
builder.setTitle("Dialog");
builder.setMessage("Lorem ipsum dolor ....");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();

And use a style like this:

<style name="AppCompatAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
        <item name="colorAccent">#FFCC00</item>
        <item name="android:textColorPrimary">#FFFFFF</item>
        <item name="android:background">#5fa3d0</item>
    </style>

Otherwise you can define in your current theme:

<style name="AppTheme" parent="Theme.AppCompat.Light">
    <!-- your style -->
    <item name="alertDialogTheme">@style/AppCompatAlertDialogStyle</item>
</style>

and then in your code:

 import android.support.v7.app.AlertDialog

    AlertDialog.Builder builder =
           new AlertDialog.Builder(this);

Here the AlertDialog on Kitkat: enter image description here

How to enable curl in xampp?

For XAMPP on MACOS or Linux, remove the semicolon in php.ini file after extension=curl.so

FileNotFoundException..Classpath resource not found in spring?

Looking at your classpath you exclude src/main/resources and src/test/resources:

    <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources"/>
    <classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources"/>

Is there a reason for it? Try not to exclude a classpath to spring-config.xml :)

How to deal with ModalDialog using selenium webdriver?

What you are using is not a model dialog, it is a separate window.

Use this code:

private static Object firstHandle;
private static Object lastHandle;

public static void switchToWindowsPopup() {
    Set<String> handles = DriverManager.getCurrent().getWindowHandles();
    Iterator<String> itr = handles.iterator();
    firstHandle = itr.next();
    lastHandle = firstHandle;
    while (itr.hasNext()) {
        lastHandle = itr.next();
    }
    DriverManager.getCurrent().switchTo().window(lastHandle.toString());
}

public static void switchToMainWindow() {
    DriverManager.getCurrent().switchTo().window(firstHandle.toString());

Javascript: set label text

InnerHTML should be innerHTML:

document.getElementById('LblAboutMeCount').innerHTML = charsleft;

You should bind your checkLength function to your textarea with jQuery rather than calling it inline and rather intrusively:

$(document).ready(function() {
    $('textarea[name=text]').keypress(function(e) {
        checkLength($(this),512,$('#LblTextCount'));
    }).focus(function() {
        checkLength($(this),512,$('#LblTextCount'));
    });
});

You can neaten up checkLength by using more jQuery, and I wouldn't use 'object' as a formal parameter:

function checkLength(obj, maxlength, label) {
    charsleft = (maxlength - obj.val().length);
    // never allow to exceed the specified limit
    if( charsleft < 0 ) {
        obj.val(obj.val().substring(0, maxlength-1));
    }
    // I'm trying to set the value of charsleft into the label
    label.text(charsleft);
    $('#LblAboutMeCount').html(charsleft);
}

So if you apply the above, you can change your markup to:

<textarea name="text"></textarea>

Is there any pythonic way to combine two dicts (adding values for keys that appear in both)?

myDict = {}
for k in itertools.chain(A.keys(), B.keys()):
    myDict[k] = A.get(k, 0)+B.get(k, 0)

Current user in Magento?

Have a look at the helper class: Mage_Customer_Helper_Data

To simply get the customer name, you can write the following code:-

$customerName = Mage::helper('customer')->getCustomerName();

For more information about the customer's entity id, website id, email, etc. you can use getCustomer function. The following code shows what you can get from it:-

echo "<pre>"; print_r(Mage::helper('customer')->getCustomer()->getData()); echo "</pre>";

From the helper class, you can also get information about customer login url, register url, logout url, etc.

From the isLoggedIn function in the helper class, you can also check whether a customer is logged in or not.

Adding item to Dictionary within loop

As per my understanding you want data in dictionary as shown below:

key1: value1-1,value1-2,value1-3....value100-1
key2: value2-1,value2-2,value2-3....value100-2
key3: value3-1,value3-2,value3-2....value100-3

for this you can use list for each dictionary keys:

case_list = {}
for entry in entries_list:
    if key in case_list:
        case_list[key1].append(value)
    else:
        case_list[key1] = [value]

Load a HTML page within another HTML page

You can use jQuery

<html> 
  <head> 
    <script src="jquery.js"></script> 
    <script> 
    $(function(){
      $("#divId").load("b.html"); 
    });
    </script> 
  </head> 

  <body> 
     <div id="divId" style="display:none;"></div>
  </body> 
</html>

on click event you can make it display block .

How to use particular CSS styles based on screen size / device

Detection is automatic. You must specify what css can be used for each screen resolution:

/* for all screens, use 14px font size */
body {  
    font-size: 14px;    
}
/* responsive, form small screens, use 13px font size */
@media (max-width: 479px) {
    body {
        font-size: 13px;
    }
}

How can I make Jenkins CI with Git trigger on pushes to master?

You need to specify the branch. By default it listens to anything. See the blog post Hudson: Git and Maven plugins.

How to enable C++11/C++0x support in Eclipse CDT?

Update 2016:

As of gcc 6 (changes), the default C++ dialect is C++14. That means that unless you explicitly need a newer or older dialect than than, you don't need to do anything with eclipse anymore.

For Luna and Mars

This community wiki section incorporates the answer by Trismegistos;

1. Before creating project, configure Eclipse syntax parser:

Window -> Preferences -> C/C++ -> Build -> Settings -> Discovery -> CDT GCC Build-in Compiler Settings

in the text box entitled Command to get compiler specs append -std=c++14 2. Create project, configuration depends on what kind of project you created:

For project created as: File -> New -> Project -> C/C++ -> C++ Project

Right click on created project and open

Properties -> C/C++ Build -> Settings -> Tool Settings -> GCC C++ Compiler -> Dialect

Put -std=c++14 into text box entitled other dialect flags or select ISO C++11 from the Language standard drop down.

There's now a new way to solve this without the GXX_EXPERIMENTAL hack.

For most recent versions: (Currently Juno and Kepler Luna):

Under newer versions of Juno the settings are located at Project properties -> C/C++ General -> Preprocessor Include Paths, Macros etc. -> tab Providers -> CDT GCC Builtin Compiler Settings ().

Older versions 2012/2013:

  1. Under C/C++ Build (at project settings), find the Preprocessor Include Path and go to the Providers Tab. Deselect all except CDT GCC Builtin Compiler Settings. Then untag Share settings entries … . Add the option -std=c++11 to the text box called Command to get compiler specs.

  2. Go to paths and symbols. Under Symbols, click restore defaults, and then apply.


Notes:

Eclipse is picky about hitting apply, you need to do it every time you leave a settings tab.

[Self-promotion]: I wrote my own more detailed instructions based on the above. http://scrupulousabstractions.tumblr.com/post/36441490955/eclipse-mingw-builds

Thanks to the user Nobody at https://stackoverflow.com/a/13635080/1149664

PDF Editing in PHP?

Don't know if this is an option, but it would work very similar to Zend's pdf library, but you don't need to load a bunch of extra code (the zend framework). It just extends FPDF.

http://www.setasign.de/products/pdf-php-solutions/fpdi/

Here you can basically do the same thing. Load the PDF, write over top of it, and then save to a new PDF. In FPDI you basically insert the PDF as an image so you can put whatever you want over it.

But again, this uses FPDF, so if you don't want to use that, then it won't work.

JavaScript validation for empty input field

_x000D_
_x000D_
<script type="text/javascript">_x000D_
  function validateForm() {_x000D_
    var a = document.forms["Form"]["answer_a"].value;_x000D_
    var b = document.forms["Form"]["answer_b"].value;_x000D_
    var c = document.forms["Form"]["answer_c"].value;_x000D_
    var d = document.forms["Form"]["answer_d"].value;_x000D_
    if (a == null || a == "", b == null || b == "", c == null || c == "", d == null || d == "") {_x000D_
      alert("Please Fill All Required Field");_x000D_
      return false;_x000D_
    }_x000D_
  }_x000D_
</script>_x000D_
_x000D_
<form method="post" name="Form" onsubmit="return validateForm()" action="">_x000D_
  <textarea cols="30" rows="2" name="answer_a" id="a"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_b" id="b"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_c" id="c"></textarea>_x000D_
  <textarea cols="30" rows="2" name="answer_d" id="d"></textarea>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Scroll to element on click in Angular 4

You can achieve that by using the reference to an angular DOM element as follows:

Here is the example in stackblitz

the component template:

<div class="other-content">
      Other content
      <button (click)="element.scrollIntoView({ behavior: 'smooth', block: 'center' })">
        Click to scroll
      </button>
    </div>
    <div id="content" #element>
      Some text to scroll
</div>

Weird PHP error: 'Can't use function return value in write context'

Can be cause by wrong operator, =, when it should be ==

if(mysql_num_rows($result) = 1)
    return $result;
else
    return false;

This code throws this error

Note that = is assignment operator and not comparison operator. Fix is to change = to ==.

How to run a script as root on Mac OS X?

In order for sudo to work the way everyone suggest, you need to be in the admin group.

Ring Buffer in Java

A very interesting project is disruptor. It has a ringbuffer and is used from what I know in financial applications.

See here: code of ringbuffer

I checked both Guava's EvictingQueue and ArrayDeque.

ArrayDeque does not limit growth if it's full it will double size and hence is not precisely acting like a ringbuffer.

EvictingQueue does what it promises but internally uses a Deque to store things and just bounds memory.

Hence, if you care about memory being bounded ArrayDeque is not fullfilling your promise. If you care about object count EvictingQueue uses internal composition (bigger object size).

A simple and memory efficient one can be stolen from jmonkeyengine. verbatim copy

import java.util.Iterator;
import java.util.NoSuchElementException;

public class RingBuffer<T> implements Iterable<T> {

  private T[] buffer;          // queue elements
  private int count = 0;          // number of elements on queue
  private int indexOut = 0;       // index of first element of queue
  private int indexIn = 0;       // index of next available slot

  // cast needed since no generic array creation in Java
  public RingBuffer(int capacity) {
    buffer = (T[]) new Object[capacity];
  }

  public boolean isEmpty() {
    return count == 0;
  }

  public int size() {
    return count;
  }

  public void push(T item) {
    if (count == buffer.length) {
        throw new RuntimeException("Ring buffer overflow");
    }
    buffer[indexIn] = item;
    indexIn = (indexIn + 1) % buffer.length;     // wrap-around
    count++;
  }

  public T pop() {
    if (isEmpty()) {
        throw new RuntimeException("Ring buffer underflow");
    }
    T item = buffer[indexOut];
    buffer[indexOut] = null;                  // to help with garbage collection
    count--;
    indexOut = (indexOut + 1) % buffer.length; // wrap-around
    return item;
  }

  public Iterator<T> iterator() {
    return new RingBufferIterator();
  }

  // an iterator, doesn't implement remove() since it's optional
  private class RingBufferIterator implements Iterator<T> {

    private int i = 0;

    public boolean hasNext() {
        return i < count;
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }

    public T next() {
        if (!hasNext()) {
            throw new NoSuchElementException();
        }
        return buffer[i++];
    }
  }
}

How to print a two dimensional array?

Well, since 'X' is a char and not an int, you cannot actually replace it in the matrix itself, however, the following code should print an 'x' char whenever it comes across a 1.

public void printGrid(int[][] in){  
    for(int i = 0; i < 20; i++){  
        for(int j = 0; j < 20; j++){  
            if(in[i][j] == 1)  
                System.out.print('X' + "\t");
            else
                System.out.print(in[i][j] + "\t");
        }
        System.out.print("\n");
    }
}

How to calculate distance between two locations using their longitude and latitude value

in build.gradle:

compile 'com.google.maps.android:android-maps-utils:0.4'

and then:

public static Double distanceBetween(LatLng point1, LatLng point2) {
    if (point1 == null || point2 == null) {
        return null;
    }

    return SphericalUtil.computeDistanceBetween(point1, point2);
}

Taking the record with the max date

The analytic function approach would look something like

SELECT a, some_date_column
  FROM (SELECT a,
               some_date_column,
               rank() over (partition by a order by some_date_column desc) rnk
          FROM tablename)
 WHERE rnk = 1

Note that depending on how you want to handle ties (or whether ties are possible in your data model), you may want to use either the ROW_NUMBER or the DENSE_RANK analytic function rather than RANK.

Given the lat/long coordinates, how can we find out the city/country?

Please check the below answer. It works for me

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position){

        initialize(position.coords.latitude,position.coords.longitude);
    }); 
}

function initialize(lat,lng) {
    //directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    //directionsService = new google.maps.DirectionsService();
    var latlng = new google.maps.LatLng(lat, lng);

    //alert(latlng);
    getLocation(latlng);
}

function getLocation(latlng){

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'latLng': latlng}, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var loc = getCountry(results);
                    alert("location is::"+loc);
                }
            }
        });

}

function getCountry(results)
{
    for (var i = 0; i < results[0].address_components.length; i++)
    {
        var shortname = results[0].address_components[i].short_name;
        var longname = results[0].address_components[i].long_name;
        var type = results[0].address_components[i].types;
        if (type.indexOf("country") != -1)
        {
            if (!isNullOrWhitespace(shortname))
            {
                return shortname;
            }
            else
            {
                return longname;
            }
        }
    }

}

function isNullOrWhitespace(text) {
    if (text == null) {
        return true;
    }
    return text.replace(/\s/gi, '').length < 1;
}

basic authorization command for curl

Background

You can use the base64 CLI tool to generate the base64 encoded version of your username + password like this:

$ echo -n "joeuser:secretpass" | base64
am9ldXNlcjpzZWNyZXRwYXNz

-or-

$ base64 <<<"joeuser:secretpass"
am9ldXNlcjpzZWNyZXRwYXNzCg==

Base64 is reversible so you can also decode it to confirm like this:

$ echo -n "joeuser:secretpass" | base64 | base64 -D
joeuser:secretpass

-or-

$ base64 <<<"joeuser:secretpass" | base64 -D
joeuser:secretpass

NOTE: username = joeuser, password = secretpass

Example #1 - using -H

You can put this together into curl like this:

$ curl -H "Authorization: Basic $(base64 <<<"joeuser:secretpass")" http://example.com

Example #2 - using -u

Most will likely agree that if you're going to bother doing this, then you might as well just use curl's -u option.

$ curl --help |grep -- "--user "
 -u, --user USER[:PASSWORD]  Server user and password

For example:

$ curl -u someuser:secretpass http://example.com

But you can do this in a semi-safer manner if you keep your credentials in a encrypted vault service such as LastPass or Pass.

For example, here I'm using the LastPass' CLI tool, lpass, to retrieve my credentials:

$ curl -u $(lpass show --username example.com):$(lpass show --password example.com) \
     http://example.com

Example #3 - using curl config

There's an even safer way to hand your credentials off to curl though. This method makes use of the -K switch.

$ curl -X GET -K \
    <(cat <<<"user = \"$(lpass show --username example.com):$(lpass show --password example.com)\"") \
    http://example.com

When used, your details remain hidden, since they're passed to curl via a temporary file descriptor, for example:

+ curl -skK /dev/fd/63 -XGET -H 'Content-Type: application/json' https://es-data-01a.example.com:9200/_cat/health
++ cat
+++ lpass show --username example.com
+++ lpass show --password example.com
1561075296 00:01:36 rdu-es-01 green 9 6 2171 1085 0 0 0 0 - 100.0%       

NOTE: Above I'm communicating with one of our Elasticsearch nodes, inquiring about the cluster's health.

This method is dynamically creating a file with the contents user = "<username>:<password>" and giving that to curl.

HTTP Basic Authorization

The methods shown above are facilitating a feature known as Basic Authorization that's part of the HTTP standard.

When the user agent wants to send authentication credentials to the server, it may use the Authorization field.

The Authorization field is constructed as follows:

  1. The username and password are combined with a single colon (:). This means that the username itself cannot contain a colon.
  2. The resulting string is encoded into an octet sequence. The character set to use for this encoding is by default unspecified, as long as it is compatible with US-ASCII, but the server may suggest use of UTF-8 by sending the charset parameter.
  3. The resulting string is encoded using a variant of Base64.
  4. The authorization method and a space (e.g. "Basic ") is then prepended to the encoded string.

For example, if the browser uses Aladdin as the username and OpenSesame as the password, then the field's value is the base64-encoding of Aladdin:OpenSesame, or QWxhZGRpbjpPcGVuU2VzYW1l. Then the Authorization header will appear as:

Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l

Source: Basic access authentication

Testing two JSON objects for equality ignoring child order in Java

Use this library: https://github.com/lukas-krecan/JsonUnit

Pom:

<dependency>
    <groupId>net.javacrumbs.json-unit</groupId>
    <artifactId>json-unit-assertj</artifactId>
    <version>2.24.0</version>
    <scope>test</scope>
</dependency>

IGNORING_ARRAY_ORDER - ignores order in arrays

assertThatJson("{\"test\":[1,2,3]}")
  .when(Option.IGNORING_ARRAY_ORDER)
  .isEqualTo("{\"test\": [3,2,1]}");

no suitable HttpMessageConverter found for response type

If you are using Spring Boot, you might want to make sure you have the Jackson dependency in your classpath. You can do this manually via:

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-annotations</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-core</artifactId>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
    </dependency>

Or you can use the web starter:

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

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

Use Jackson-annotations.jar will solve the problem, as it worked for me.

How do I add a custom script to my package.json file that runs a javascript file?

Lets say in scripts you want to run 2 commands with a single command:

"scripts":{
  "start":"any command",
  "singleCommandToRunTwoCommand":"some command here && npm start"
}

Now go to your terminal and run there npm run singleCommandToRunTwoCommand.

Difference between subprocess.Popen and os.system

subprocess.Popen() is strict super-set of os.system().

Facebook Open Graph not clearing cache

I had a different, but similar problem with Facebook recently, and found that the scraper/debug page mentioned, simply does not appear to read any page in its entirety. My meta properties for Open Graph were further down in the head section, and the scraper would constantly inform me that the image specification was not correct, and would use a cached version regardless. I moved the Open Graph tags further up in the code, near the very top of the page, and then everything worked perfectly, every time.

How do I find the absolute position of an element using jQuery?

.offset() will return the offset position of an element as a simple object, eg:

var position = $(element).offset(); // position = { left: 42, top: 567 }

You can use this return value to position other elements at the same spot:

$(anotherElement).css(position)

How to add background image for input type="button"?

.button{
    background-image:url('/image/btn.png');
    background-repeat:no-repeat;
}

canvas.toDataURL() SecurityError

Just use the crossOrigin attribute and pass 'anonymous' as the second parameter

var img = new Image();
img.setAttribute('crossOrigin', 'anonymous');
img.src = url;

Javascript: Setting location.href versus location

You might set location directly because it's slightly shorter. If you're trying to be terse, you can usually omit the window. too.

URL assignments to both location.href and location are defined to work in JavaScript 1.0, back in Netscape 2, and have been implemented in every browser since. So take your pick and use whichever you find clearest.

Git Cherry-Pick and Conflicts

Also, to complete what @claudio said, when cherry-picking you can also use a merging strategy.

So you could something like this git cherry-pick --strategy=recursive -X theirs commit or git cherry-pick --strategy=recursive -X ours commit

Insert data to MySql DB and display if insertion is success or failure

According to the book PHP and MySQL for Dynamic Web Sites (4th edition)

Example:

$r = mysqli_query($dbc, $q);

For simple queries like INSERT, UPDATE, DELETE, etc. (which do not return records), the $r variable—short for result—will be either TRUE or FALSE, depending upon whether the query executed successfully.

Keep in mind that “executed successfully” means that it ran without error; it doesn’t mean that the query’s execution necessarily had the desired result; you’ll need to test for that.

Then how to test?

While the mysqli_num_rows() function will return the number of rows generated by a SELECT query, mysqli_affected_rows() returns the number of rows affected by an INSERT, UPDATE, or DELETE query. It’s used like so:

$num = mysqli_affected_rows($dbc);

Unlike mysqli_num_rows(), the one argument the function takes is the database connection ($dbc), not the results of the previous query ($r).

How to set placeholder value using CSS?

From what I understand using,

::-webkit-input-placeholder::beforeor ::-webkit-input-placeholder::after,

to add more placeholder content doesn't work anymore. Think its a new Chrome update.

Really annoying as it was a great workaround, now im back to just adding lots of empty spaces between lines that I want in a placeholder. eg:

<input type="text" value="" id="email1" placeholder="I am on one line.                                              I am on a second line                                                                                     etc etc..." />

Why an abstract class implementing an interface can miss the declaration/implementation of one of the interface's methods?

Abstract classes are not required to implement the methods. So even though it implements an interface, the abstract methods of the interface can remain abstract. If you try to implement an interface in a concrete class (i.e. not abstract) and you do not implement the abstract methods the compiler will tell you: Either implement the abstract methods or declare the class as abstract.

Executing multiple commands from a Windows cmd script

If you are running in Windows you can use the following command.

Drive:

cd "Script location"
schtasks /run /tn "TASK1"
schtasks /run /tn "TASK2"
schtasks /run /tn "TASK3"
exit

transform object to array with lodash

If you want some custom mapping (like original Array.prototype.map) of Object into an Array, you can just use _.forEach:

let myObject = {
  key1: "value1",
  key2: "value2",
  // ...
};

let myNewArray = [];

_.forEach(myObject, (value, key) => {
  myNewArray.push({
    someNewKey: key,
    someNewValue: value.toUpperCase() // just an example of new value based on original value
  });
});

// myNewArray => [{ someNewKey: key1, someNewValue: 'VALUE1' }, ... ];

See lodash doc of _.forEach https://lodash.com/docs/#forEach

Google Maps JavaScript API RefererNotAllowedMapError

None of these fixes were working for me until I found out that RefererNotAllowedMapError can be caused by not having a billing account linked to the project. So make sure to activate your free trial or whatever.

Is it possible to add an HTML link in the body of a MAILTO link

Please check below javascript in IE. Don't know if other modern browser will work or not.

<html>
    <head>
        <script type="text/javascript">
            function OpenOutlookDoc(){
                try {

                    var outlookApp = new ActiveXObject("Outlook.Application");
                    var nameSpace = outlookApp.getNameSpace("MAPI");
                    mailFolder = nameSpace.getDefaultFolder(6);
                    mailItem = mailFolder.Items.add('IPM.Note.FormA');
                    mailItem.Subject="a subject test";
                    mailItem.To = "[email protected]";
                    mailItem.HTMLBody = "<b>bold</b>";
                    mailItem.display (0); 
                }
                catch(e){
                    alert(e);
                    // act on any error that you get
                }
            }
        </script>
    </head>
    <body>
        <a href="javascript:OpenOutlookDoc()">Click</a>
    </body>
</html>

Is it better to use std::memcpy() or std::copy() in terms to performance?

Just a minor addition: The speed difference between memcpy() and std::copy() can vary quite a bit depending on if optimizations are enabled or disabled. With g++ 6.2.0 and without optimizations memcpy() clearly wins:

Benchmark             Time           CPU Iterations
---------------------------------------------------
bm_memcpy            17 ns         17 ns   40867738
bm_stdcopy           62 ns         62 ns   11176219
bm_stdcopy_n         72 ns         72 ns    9481749

When optimizations are enabled (-O3), everything looks pretty much the same again:

Benchmark             Time           CPU Iterations
---------------------------------------------------
bm_memcpy             3 ns          3 ns  274527617
bm_stdcopy            3 ns          3 ns  272663990
bm_stdcopy_n          3 ns          3 ns  274732792

The bigger the array the less noticeable the effect gets, but even at N=1000 memcpy() is about twice as fast when optimizations aren't enabled.

Source code (requires Google Benchmark):

#include <string.h>
#include <algorithm>
#include <vector>
#include <benchmark/benchmark.h>

constexpr int N = 10;

void bm_memcpy(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    memcpy(r.data(), a.data(), N * sizeof(int));
  }
}

void bm_stdcopy(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    std::copy(a.begin(), a.end(), r.begin());
  }
}

void bm_stdcopy_n(benchmark::State& state)
{
  std::vector<int> a(N);
  std::vector<int> r(N);

  while (state.KeepRunning())
  {
    std::copy_n(a.begin(), N, r.begin());
  }
}

BENCHMARK(bm_memcpy);
BENCHMARK(bm_stdcopy);
BENCHMARK(bm_stdcopy_n);

BENCHMARK_MAIN()

/* EOF */

Flexbox: 4 items per row

Here is another apporach.

You can accomplish it in this way too:

.parent{
  display: flex;
  flex-wrap: wrap;
}

.child{
  width: 25%;
  box-sizing: border-box;
}

Sample: https://codepen.io/capynet/pen/WOPBBm

And a more complete sample: https://codepen.io/capynet/pen/JyYaba

Sort an array in Java

just FYI, you can now use Java 8 new API for sorting any type of array using parallelSort

parallelSort uses Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads available in the thread pool.

the two methods that can be used to sort int array,

parallelSort(int[] a)
parallelSort(int[] a,int fromIndex,int toIndex)

How to display an activity indicator with text on iOS 8 with Swift?

Xcode 9.0 • Swift 4.0


import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var filterButton: UIButton!
    @IBOutlet weak var saveButton: UIButton!
    let destinationUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        .appendingPathComponent("filteredImage.png")
    let imagePicker = UIImagePickerController()
    let messageFrame = UIView()
    var activityIndicator = UIActivityIndicatorView()
    var strLabel = UILabel()
    let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
    func activityIndicator(_ title: String) {
        strLabel.removeFromSuperview()
        activityIndicator.removeFromSuperview()
        effectView.removeFromSuperview()
        strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 46))
        strLabel.text = title
        strLabel.font = .systemFont(ofSize: 14, weight: .medium)
        strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
        effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 160, height: 46)
        effectView.layer.cornerRadius = 15
        effectView.layer.masksToBounds = true
        activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
        activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
        activityIndicator.startAnimating()
        effectView.contentView.addSubview(activityIndicator)
        effectView.contentView.addSubview(strLabel)
        view.addSubview(effectView)
    }
    func saveImage() {
        do {
            try imageView.image?.data?.write(to: destinationUrl, options: .atomic)
            print("file saved")
        } catch {
            print(error)
        }
    }        
    func applyFilterToImage() {
        imageView.image = imageView.image?.applying(contrast: 1.5)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        guard let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/a/a8/VST_images_the_Lagoon_Nebula.jpg"), let data = try? Data(contentsOf: url), let image = UIImage(data: data) else { return }
        view.backgroundColor = UIColor(white: 0, alpha: 1)
        imageView.image = image
    }
    @IBAction func startSavingImage(_ sender: AnyObject) {
        saveButton.isEnabled = false
        filterButton.isEnabled = false
        activityIndicator("Saving Image")
        DispatchQueue.main.async {
            self.saveImage()
            DispatchQueue.main.async {
                self.effectView.removeFromSuperview()
                self.saveButton.isEnabled = true
                self.filterButton.isEnabled = true
            }
        }
    }
    @IBAction func filterAction(_ sender: AnyObject) {
        filterButton.isEnabled = false
        saveButton.isEnabled = false
        activityIndicator("Applying Filter")
        DispatchQueue.main.async {
            self.applyFilterToImage()
            DispatchQueue.main.async {
                self.effectView.removeFromSuperview()
                self.filterButton.isEnabled = true
                self.saveButton.isEnabled = true
            }
        }
    }
    @IBAction func cameraAction(_ sender: AnyObject) {
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePicker.delegate = self
            imagePicker.sourceType = .camera
            present(imagePicker, animated: true)
        }
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [AnyHashable: Any]!) {
        dismiss(animated: true, completion: nil)
        imageView.image = image
    }
}

extension Data {
    var image: UIImage? { return UIImage(data: self) }
}

extension UIImage {
    var data: Data? { return UIImagePNGRepresentation(self) }
    func applying(contrast value: NSNumber) -> UIImage? {
        guard let ciImage = CIImage(image: self)?.applyingFilter("CIColorControls", withInputParameters: [kCIInputContrastKey: value]) else { return nil }
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        defer { UIGraphicsEndImageContext() }
        UIImage(ciImage: ciImage).draw(in: CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

Using CMake to generate Visual Studio C++ project files

CMake produces Visual Studio Projects and Solutions seamlessly. You can even produce projects/solutions for different Visual Studio versions without making any changes to the CMake files.

Adding and removing source files is just a matter of modifying the CMakeLists.txt which has the list of source files and regenerating the projects/solutions. There is even a globbing function to find all the sources in a directory (though it should be used with caution).

The following link explains CMake and Visual Studio specific behavior very well.

CMake and Visual Studio

How do I delete from multiple tables using INNER JOIN in SQL server

This is an alternative way of deleting records without leaving orphans.


Declare @user Table(keyValue int  , someString varchar(10))
insert into @user
values(1,'1 value')

insert into @user
values(2,'2 value')

insert into @user
values(3,'3 value')

Declare @password Table(  keyValue int , details varchar(10))
insert into @password
values(1,'1 Password')
insert into @password
values(2,'2 Password')
insert into @password
values(3,'3 Password')

        --before deletion
  select * from @password a inner join @user b
                on a.keyvalue = b.keyvalue
  select * into #deletedID from @user where keyvalue=1 -- this works like the output example
  delete  @user where keyvalue =1
  delete @password where keyvalue in (select keyvalue from #deletedid)

  --After deletion--
  select * from @password a inner join @user b
                on a.keyvalue = b.keyvalue

C++ initial value of reference to non-const must be an lvalue

When you pass a pointer by a non-const reference, you are telling the compiler that you are going to modify that pointer's value. Your code does not do that, but the compiler thinks that it does, or plans to do it in the future.

To fix this error, either declare x constant

// This tells the compiler that you are not planning to modify the pointer
// passed by reference
void test(float * const &x){
    *x = 1000;
}

or make a variable to which you assign a pointer to nKByte before calling test:

float nKByte = 100.0;
// If "test()" decides to modify `x`, the modification will be reflected in nKBytePtr
float *nKBytePtr = &nKByte;
test(nKBytePtr);

Copy folder recursively in Node.js

Yes, ncp is cool though...

You might want/should promisify its function to make it super cool. While you're at it, add it to a tools file to reuse it.

Below is a working version which is Async and uses Promises.


File index.js

const {copyFolder} = require('./tools/');

return copyFolder(
    yourSourcePath,
    yourDestinationPath
)
.then(() => {
    console.log('-> Backup completed.')
}) .catch((err) => {
    console.log("-> [ERR] Could not copy the folder: ", err);
})

File tools.js

const ncp = require("ncp");

/**
 * Promise Version of ncp.ncp()
 *
 * This function promisifies ncp.ncp().
 * We take the asynchronous function ncp.ncp() with
 * callback semantics and derive from it a new function with
 * promise semantics.
 */
ncp.ncpAsync = function (sourcePath, destinationPath) {
  return new Promise(function (resolve, reject) {
      try {
          ncp.ncp(sourcePath, destinationPath, function(err){
              if (err) reject(err); else resolve();
          });
      } catch (err) {
          reject(err);
      }
  });
};

/**
 * Utility function to copy folders asynchronously using
 * the Promise returned by ncp.ncp().
 */
const copyFolder = (sourcePath, destinationPath) => {
    return ncp.ncpAsync(sourcePath, destinationPath, function (err) {
        if (err) {
            return console.error(err);
        }
    });
}
module.exports.copyFolder = copyFolder;

Set active tab style with AngularJS

A way to solve this without having to rely on URLs is to add a custom attribute to every partial during $routeProvider configuration, like this:

$routeProvider.
    when('/dashboard', {
        templateUrl: 'partials/dashboard.html',
        controller: widgetsController,
        activetab: 'dashboard'
    }).
    when('/lab', {
        templateUrl: 'partials/lab.html',
        controller: widgetsController,
        activetab: 'lab'
    });

Expose $route in your controller:

function widgetsController($scope, $route) {
    $scope.$route = $route;
}

Set the active class based on the current active tab:

<li ng-class="{active: $route.current.activetab == 'dashboard'}"></li>
<li ng-class="{active: $route.current.activetab == 'lab'}"></li>

"The import org.springframework cannot be resolved."

The only solution worked for me is add maven-compiler-plugin to the pom.xml

<project ...>
    ...
    <build>
        ...
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.7</source>
                    <target>1.7</target>
                    <fork>true</fork>
                    <executable>C:\Program Files\Java\jdk1.7.0_79\bin\javac</executable>
                </configuration>
            </plugin>
        </plugins>
    </build>
    ...
</project>

Is there a /dev/null on Windows?

NUL works programmatically as well. E.g. the following:

freopen("NUL", "w", stderr);

works as expected without creating a file. (MSVC++ 12.0)

Cannot find java. Please use the --jdkhome switch

What worked for me is:

  • make sure java path is available:
$ which java
/usr/bin/java
  • then in etc/netbeans.conf make sure netbeans_jdkhome is commented out
  • in Finder go to /bin/ click on netbeans (terminal icon)

You would expect ./netbeans --jdkhome=/usr/bin/java to work, but it doesn't for some reason.

Convert xlsx file to csv using batch

You need an external tool, in example: SoftInterface.com - Convert XLSX to CSV.

After installing it, you can use following command in your batch:

"c:\Program Files\Softinterface, Inc\Convert XLS\ConvertXLS.EXE" /S"C:\MyExcelFile.xlsx" /F51 /N"Sheet1" /T"C:\MyExcelFile.CSV" /C6 /M1 /V

Python urllib2, basic HTTP authentication, and tr.im

Same solutions as Python urllib2 Basic Auth Problem apply.

see https://stackoverflow.com/a/24048852/1733117; you can subclass urllib2.HTTPBasicAuthHandler to add the Authorization header to each request that matches the known url.

class PreemptiveBasicAuthHandler(urllib2.HTTPBasicAuthHandler):
    '''Preemptive basic auth.

    Instead of waiting for a 403 to then retry with the credentials,
    send the credentials if the url is handled by the password manager.
    Note: please use realm=None when calling add_password.'''
    def http_request(self, req):
        url = req.get_full_url()
        realm = None
        # this is very similar to the code from retry_http_basic_auth()
        # but returns a request object.
        user, pw = self.passwd.find_user_password(realm, url)
        if pw:
            raw = "%s:%s" % (user, pw)
            auth = 'Basic %s' % base64.b64encode(raw).strip()
            req.add_unredirected_header(self.auth_header, auth)
        return req

    https_request = http_request

How to save an image locally using Python whose URL address I already know?

Python 3

urllib.request — Extensible library for opening URLs

from urllib.error import HTTPError
from urllib.request import urlretrieve

try:
    urlretrieve(image_url, image_local_path)
except FileNotFoundError as err:
    print(err)   # something wrong with local path
except HTTPError as err:
    print(err)  # something wrong with url

make image( not background img) in div repeat?

Not with CSS you can't. You need to use JS. A quick example copying the img to the background:

var $el = document.getElementById( 'rightflower' )
  , $img = $el.getElementsByTagName( 'img' )[0]
  , src  = $img.src

$el.innerHTML = "";
$el.style.background = "url( " + src + " ) repeat-y;"

Or you can actually repeat the image, but how many times?

var $el = document.getElementById( 'rightflower' )
  , str = ""
  , imgHTML = $el.innerHTML
  , i, i2;
for( i=0,i2=10; i<i2; i++ ){
    str += imgHTML;
}
$el.innerHTML = str;

Copy filtered data to another sheet using VBA

it needs to be .Row.count not Row.Number?

That's what I used and it works fine Sub TransfersToCleared() Dim ws As Worksheet Dim LastRow As Long Set ws = Application.Worksheets("Export (2)") 'Data Source LastRow = Range("A" & Rows.Count).End(xlUp).Row ws.Range("A2:AB" & LastRow).SpecialCells(xlCellTypeVisible).Copy

how to enable sqlite3 for php?

For Debian distributions. Nothing worked for until I added the debian main repositories on the apt sources (I don't know how were they removed): sudo vi /etc/apt/sources.list

and added

deb  http://deb.debian.org/debian  stretch main
deb-src  http://deb.debian.org/debian  stretch main

after that sudo apt-get update (you can upgrade too) and finally sudo apt-get install php-sqlite3

AWS S3: The bucket you are attempting to access must be addressed using the specified endpoint

I encountered this issue when using a different AWS profile. I saw the error when I was using an account with admin permissions, so the possibility of permissions issues seemed unlikely.

It's really a pet peeve of mine that AWS is so prone to issuing error messages that have such little correlation with the required actions, from a user perspective.

How to make a transparent HTML button?

The solution is pretty easy actually:

<button style="border:1px solid black; background-color: transparent;">Test</button>

This is doing an inline style. You're defining the border to be 1px, solid line, and black in color. The background color is then set to transparent.


UPDATE

Seems like your ACTUAL question is how do you prevent the border after clicking on it. That can be resolved with a CSS pseudo selector: :active.

button {
    border: none;
    background-color: transparent;
    outline: none;
}
button:focus {
    border: none;
}

JSFiddle Demo

Position absolute but relative to parent

Incase someone wants to postion a child div directly under a parent

#father {
   position: relative;
}

#son1 {
   position: absolute;
   top: 100%;
}

Working demo Codepen

Removing pip's cache?

If using virtualenv, look for the build directory under your environments root.

Is There a Better Way of Checking Nil or Length == 0 of a String in Ruby?

As it was said here before Rails (ActiveSupport) have a handy blank? method and it is implemented like this:

class Object
  def blank?
    respond_to?(:empty?) ? empty? : !self
  end
end

Pretty easy to add to any ruby-based project.

The beauty of this solution is that it works auto-magicaly not only for Strings but also for Arrays and other types.

UnicodeDecodeError: 'utf8' codec can't decode byte 0xa5 in position 0: invalid start byte

I switched this simply by defining a different codec package in the read_csv() command:

encoding = 'unicode_escape'

Eg:

import pandas as pd
data = pd.read_csv(filename, encoding= 'unicode_escape')

How to change Windows 10 interface language on Single Language version

1) Upgrade using windows update or using "media creation tool" http://windows.microsoft.com/en-us/windows-10/media-creation-tool-install

  • if you are using "media creation tool" select "Upgrade this PC now"

When Windows 10 installed check that it is activated.

2) Now as you have activated Windows 10 using "media creation tool" http://windows.microsoft.com/en-us/windows-10/media-creation-tool-install select second option "Create installation media for another PC" here you can select Windows version and its language. Make sure that Windows version is also "Single Language"

3) Boot from you device, USB in my case and install clean Windows in English or any other language you selected.

reference http://bit.ly/1RKmPBs

Creating a SearchView that looks like the material design guidelines

It is actually quite easy to do this, if you are using android.support.v7 library.

Step - 1

Declare a menu item

<item android:id="@+id/action_search"
    android:title="Search"
    android:icon="@drawable/abc_ic_search_api_mtrl_alpha"
    app:showAsAction="ifRoom|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView" />

Step - 2

Extend AppCompatActivity and in the onCreateOptionsMenu setup the SearchView.

import android.support.v7.widget.SearchView;

...

public class YourActivity extends AppCompatActivity {

    ...

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_home, menu);
        // Retrieve the SearchView and plug it into SearchManager
        final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
        SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
        searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
        return true;
    }

    ... 

}

Result

enter image description here

enter image description here

Cordova : Requirements check failed for JDK 1.8 or greater

Guys to get the mix right on Windows, you need to do the following

  1. Download and install any version of JDK 1.8 or higher.
  2. Open environment variables, create an environment variable called JAVA_HOME and set value to JDK install path. C:\Program Files\Java\jdk1.8.0_162 make sure you do not add the \bin in the value.

enter image description here

  1. In your system path variable, put a semi-colon ; and add this value to system path e.g C:\Program Files\Java\jdk1.8.0_162\bin; Here the \bin is added.

Note: The environment variables are tricky.They are supposed to be closed by a ; before opening another. That is why we put one before adding the value and one after the value to close it.

enter image description here

  1. Now close terminal and reopen then run previous commands.