Programs & Examples On #Agent based modeling

Agent-based modeling is a computer simulation method where agents make decisions based on their interactions with each other and their environment. It combines elements of game theory, complex systems, emergence, computational sociology, multi-agent systems, and evolutionary programming.

How to ignore the certificate check when ssl

Rather than adding a callback to ServicePointManager which will override certificate validation globally, you can set the callback on a local instance of HttpClient. This approach should only affect calls made using that instance of HttpClient.

Here is sample code showing how ignoring certificate validation errors for specific servers might be implemented in a Web API controller.

using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;

public class MyController : ApiController
{

    // use this HttpClient instance when making calls that need cert errors suppressed
    private static readonly HttpClient httpClient;

    static MyController()
    {
        // create a separate handler for use in this controller
        var handler = new HttpClientHandler();

        // add a custom certificate validation callback to the handler
        handler.ServerCertificateCustomValidationCallback = ((sender, cert, chain, errors) => ValidateCert(sender, cert, chain, errors));

        // create an HttpClient that will use the handler
        httpClient = new HttpClient(handler);
    }

    protected static ValidateCert(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors errors)
    {

        // set a list of servers for which cert validation errors will be ignored
        var overrideCerts = new string[]
        {
            "myproblemserver",
            "someotherserver",
            "localhost"
        };

        // if the server is in the override list, then ignore any validation errors
        var serverName = cert.Subject.ToLower();
        if (overrideCerts.Any(overrideName => serverName.Contains(overrideName))) return true;

        // otherwise use the standard validation results
        return errors == SslPolicyErrors.None;
    }

}

Passing data into "router-outlet" child components

Service:

import {Injectable, EventEmitter} from "@angular/core";    

@Injectable()
export class DataService {
onGetData: EventEmitter = new EventEmitter();

getData() {
  this.http.post(...params).map(res => {
    this.onGetData.emit(res.json());
  })
}

Component:

import {Component} from '@angular/core';    
import {DataService} from "../services/data.service";       
    
@Component()
export class MyComponent {
  constructor(private DataService:DataService) {
    this.DataService.onGetData.subscribe(res => {
      (from service on .emit() )
    })
  }

  //To send data to all subscribers from current component
  sendData() {
    this.DataService.onGetData.emit(--NEW DATA--);
  }
}

How to get featured image of a product in woocommerce

get_the_post_thumbnail function returns html not url of featured image. You should use get_post_thumbnail_id to get post id of featured image and then use wp_get_attachment_image_src to get url of featured image.

Try this:

<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 80, 'product_cat' => 'profiler', 'orderby' => 'rand' );

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
    <div class="dvThumb col-xs-4 col-sm-3 col-md-3 profiler-select profiler<?php echo the_title(); ?>" data-profile="<?php echo $loop->post->ID; ?>">
        <?php $featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($loop->post->ID)); ?>
        <?php if($featured_image) { ?>
        <img src="<?php $featured_image[0]; ?>" data-id="<?php echo $loop->post->ID; ?>">
        <?php } ?>
        <p><?php the_title(); ?></p>
        <span class="price"><?php echo $product->get_price_html(); ?></span>
    </div>
<?php endwhile; ?>

What's the difference between an element and a node in XML?

Element is the only kind of node that can have child nodes and attributes.

Document also has child nodes, BUT
no attributes, no text, exactly one child element.

Display Images Inline via CSS

You have a line break <br> in-between the second and third images in your markup. Get rid of that, and it'll show inline.

What is a C++ delegate?

A delegate is a class that wraps a pointer or reference to an object instance, a member method of that object's class to be called on that object instance, and provides a method to trigger that call.

Here's an example:

template <class T>
class CCallback
{
public:
    typedef void (T::*fn)( int anArg );

    CCallback(T& trg, fn op)
        : m_rTarget(trg)
        , m_Operation(op)
    {
    }

    void Execute( int in )
    {
        (m_rTarget.*m_Operation)( in );
    }

private:

    CCallback();
    CCallback( const CCallback& );

    T& m_rTarget;
    fn m_Operation;

};

class A
{
public:
    virtual void Fn( int i )
    {
    }
};


int main( int /*argc*/, char * /*argv*/ )
{
    A a;
    CCallback<A> cbk( a, &A::Fn );
    cbk.Execute( 3 );
}

Pointer to a string in C?

The string is basically bounded from the place where it is pointed to (char *ptrChar;), to the null character (\0).

The char *ptrChar; actually points to the beginning of the string (char array), and thus that is the pointer to that string, so when you do like ptrChar[x] for example, you actually access the memory location x times after the beginning of the char (aka from where ptrChar is pointing to).

What's the most useful and complete Java cheat sheet?

This Quick Reference looks pretty good if you're looking for a language reference. It's especially geared towards the user interface portion of the API.

For the complete API, however, I always use the Javadoc. I reference it constantly.

How do I cast a string to integer and have 0 in case of error in the cast with PostgreSQL?

This should also do the job but this is across SQL and not postgres specific.

select avg(cast(mynumber as numeric)) from my table

How to activate the Bootstrap modal-backdrop?

Just append a div with that class to body, then remove it when you're done:

// Show the backdrop
$('<div class="modal-backdrop"></div>').appendTo(document.body);

// Remove it (later)
$(".modal-backdrop").remove();

Live Example:

_x000D_
_x000D_
$("input").click(function() {_x000D_
  var bd = $('<div class="modal-backdrop"></div>');_x000D_
  bd.appendTo(document.body);_x000D_
  setTimeout(function() {_x000D_
    bd.remove();_x000D_
  }, 2000);_x000D_
});
_x000D_
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/css/bootstrap-combined.min.css" rel="stylesheet" type="text/css" />_x000D_
<script src="//code.jquery.com/jquery.min.js"></script>_x000D_
<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.2/js/bootstrap.min.js"></script>_x000D_
<p>Click the button to get the backdrop for two seconds.</p>_x000D_
<input type="button" value="Click Me">
_x000D_
_x000D_
_x000D_

JavaScript global event mechanism

How to Catch Unhandled Javascript Errors

Assign the window.onerror event to an event handler like:

<script type="text/javascript">
window.onerror = function(msg, url, line, col, error) {
   // Note that col & error are new to the HTML 5 spec and may not be 
   // supported in every browser.  It worked for me in Chrome.
   var extra = !col ? '' : '\ncolumn: ' + col;
   extra += !error ? '' : '\nerror: ' + error;

   // You can view the information in an alert to see things working like this:
   alert("Error: " + msg + "\nurl: " + url + "\nline: " + line + extra);

   // TODO: Report this error via ajax so you can keep track
   //       of what pages have JS issues

   var suppressErrorAlert = true;
   // If you return true, then error alerts (like in older versions of 
   // Internet Explorer) will be suppressed.
   return suppressErrorAlert;
};
</script>

As commented in the code, if the return value of window.onerror is true then the browser should suppress showing an alert dialog.

When does the window.onerror Event Fire?

In a nutshell, the event is raised when either 1.) there is an uncaught exception or 2.) a compile time error occurs.

uncaught exceptions

  • throw "some messages"
  • call_something_undefined();
  • cross_origin_iframe.contentWindow.document;, a security exception

compile error

  • <script>{</script>
  • <script>for(;)</script>
  • <script>"oops</script>
  • setTimeout("{", 10);, it will attempt to compile the first argument as a script

Browsers supporting window.onerror

  • Chrome 13+
  • Firefox 6.0+
  • Internet Explorer 5.5+
  • Opera 11.60+
  • Safari 5.1+

Screenshot:

Example of the onerror code above in action after adding this to a test page:

<script type="text/javascript">
call_something_undefined();
</script>

Javascript alert showing error information detailed by the window.onerror event

Example for AJAX error reporting

var error_data = {
    url: document.location.href,
};

if(error != null) {
    error_data['name'] = error.name; // e.g. ReferenceError
    error_data['message'] = error.line;
    error_data['stack'] = error.stack;
} else {
    error_data['msg'] = msg;
    error_data['filename'] = filename;
    error_data['line'] = line;
    error_data['col'] = col;
}

var xhr = new XMLHttpRequest();

xhr.open('POST', '/ajax/log_javascript_error');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onload = function() {
    if (xhr.status === 200) {
        console.log('JS error logged');
    } else if (xhr.status !== 200) {
        console.error('Failed to log JS error.');
        console.error(xhr);
        console.error(xhr.status);
        console.error(xhr.responseText);
    }
};
xhr.send(JSON.stringify(error_data));

JSFiddle:

https://jsfiddle.net/nzfvm44d/

References:

How can I generate an MD5 hash?

I have a Class (Hash) to convert plain text in hash in formats: md5 or sha1, simillar that php functions (md5, sha1):

public class Hash {
    /**
     * 
     * @param txt, text in plain format
     * @param hashType MD5 OR SHA1
     * @return hash in hashType 
     */
    public static String getHash(String txt, String hashType) {
        try {
                    java.security.MessageDigest md = java.security.MessageDigest.getInstance(hashType);
                    byte[] array = md.digest(txt.getBytes());
                    StringBuffer sb = new StringBuffer();
                    for (int i = 0; i < array.length; ++i) {
                        sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
                 }
                    return sb.toString();
            } catch (java.security.NoSuchAlgorithmException e) {
                //error action
            }
            return null;
    }

    public static String md5(String txt) {
        return Hash.getHash(txt, "MD5");
    }

    public static String sha1(String txt) {
        return Hash.getHash(txt, "SHA1");
    }
}

Testing with JUnit and PHP

PHP Script:

<?php

echo 'MD5 :' . md5('Hello World') . "\n";
echo 'SHA1:' . sha1('Hello World') . "\n";

Output PHP script:

MD5 :b10a8db164e0754105b7a99be72e3fe5
SHA1:0a4d55a8d778e5022fab701977c5d840bbc486d0

Using example and Testing with JUnit:

    public class HashTest {

    @Test
    public void test() {
        String txt = "Hello World";
        assertEquals("b10a8db164e0754105b7a99be72e3fe5", Hash.md5(txt));
        assertEquals("0a4d55a8d778e5022fab701977c5d840bbc486d0", Hash.sha1(txt));
    }

}

Code in GitHub

https://github.com/fitorec/java-hashes

How to make an HTTP request + basic auth in Swift

go plain for SWIFT 3 and APACHE simple Auth:

func urlSession(_ session: URLSession, task: URLSessionTask,
                didReceive challenge: URLAuthenticationChallenge,
                completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {

    let credential = URLCredential(user: "test",
                                   password: "test",
                                   persistence: .none)

    completionHandler(.useCredential, credential)


}

How to set environment via `ng serve` in Angular 6

You can try: ng serve --configuration=dev/prod

To build use: ng build --prod --configuration=dev

Hope you are using a different kind of environment.

Call multiple functions onClick ReactJS

this onclick={()=>{ f1(); f2() }} helped me a lot if i want two different functions at the same time. But now i want to create an audiorecorder with only one button. So if i click first i want to run the StartFunction f1() and if i click again then i want to run StopFunction f2().

How do you guys realize this?

Git Clone - Repository not found

I was also having same issue. I was trying to clone the repo which was private and my git installed in osx has keychain which was not allowing me to clone the repo...

I tried

git clone https://username:[email protected]/NAME/repo.git 

but it didn't work as my password was containing the field @.

I just ran

git credential-osxkeychain erase
host=github.com
protocol=https

command and press enter and it worked perfectly fine. Actually you need to remove the keychain already stored in the osx.

a tag as a submit button?

Give the form an id, and then:

document.getElementById("yourFormId").submit();

Best practice would probably be to give your link an id too, and get rid of the event handler:

document.getElementById("yourLinkId").onclick = function() {
    document.getElementById("yourFormId").submit();
}

Passing an array to a query using a WHERE clause

Besides using the IN query, you have two options to do so as in an IN query there is a risk of an SQL injection vulnerability. You can use looping to get the exact data you want or you can use the query with OR case

1. SELECT *
      FROM galleries WHERE id=1 or id=2 or id=5;


2. $ids = array(1, 2, 5);
   foreach ($ids as $id) {
      $data[] = SELECT *
                    FROM galleries WHERE id= $id;
   }

React ignores 'for' attribute of the label element

For React you must use it's per-define keywords to define html attributes.

class -> className

is used and

for -> htmlFor

is used, as react is case sensitive make sure you must follow small and capital as required.

What is /dev/null 2>&1?

>> /dev/null redirects standard output (stdout) to /dev/null, which discards it.

(The >> seems sort of superfluous, since >> means append while > means truncate and write, and either appending to or writing to /dev/null has the same net effect. I usually just use > for that reason.)

2>&1 redirects standard error (2) to standard output (1), which then discards it as well since standard output has already been redirected.

Show Current Location and Nearby Places and Route between two places using Google Maps API in Android

Lots of answers so far, which are all excellent pointers to API's and tutorials. One thing I'd like to add is that I work out how far the markers are from my location using something like:

float distance = (float) loc.distanceTo(loc2);

Hope this helps refine the detail for your problem. It returns a rough estimate of distance (in m) between points, and is useful for getting rid of POI that might be too far away - good to declutter your map?

SUM of grouped COUNT in SQL Query

The way I interpreted this question is needing the subtotal value of each group of answers. Subtotaling turns out to be very easy, using PARTITION:

SUM(COUNT(0)) OVER (PARTITION BY [Grouping]) AS [MY_TOTAL]

This is what my full SQL call looks like:

SELECT MAX(GroupName) [name], MAX(AUX2)[type],  
COUNT(0) [count], SUM(COUNT(0)) OVER(PARTITION BY GroupId) AS [total]
    FROM [MyView]
  WHERE Active=1 AND Type='APP' AND Completed=1
    AND [Date] BETWEEN '01/01/2014' AND GETDATE()
    AND Id = '5b9xxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' AND GroupId IS NOT NULL
  GROUP BY AUX2, GroupId

The data returned from this looks like:

name    type    count   total
Training Group 2    Cancelation 1   52
Training Group 2    Completed   41  52
Training Group 2    No Show 6   52
Training Group 2    Rescheduled 4   52
Training Group 3    NULL        4   10535
Training Group 3    Cancelation 857 10535
Training Group 3    Completed   7923    10535
Training Group 3    No Show 292 10535
Training Group 3    Rescheduled 1459    10535
Training Group 4    Cancelation 2   27
Training Group 4    Completed   24  27
Training Group 4    Rescheduled 1   27

How to open the Chrome Developer Tools in a new window?

You have to click and hold until the other icon shows up, then slide the mouse down to the icon.

Change the background color of a pop-up dialog

To change the background color of all dialogs and pop-ups in your app, use colorBackgroundFloating attribute.

<style name="MyApplicationTheme" parent="@style/Theme.AppCompat.NoActionBar">
...
<item name="colorBackgroundFloating">
    @color/background</item>
<item name="android:colorBackgroundFloating" tools:targetApi="23">
    @color/background</item>
...
</style>

Documentation:

colorBackgroundFloating

What is a CSRF token? What is its importance and how does it work?

The root of it all is to make sure that the requests are coming from the actual users of the site. A csrf token is generated for the forms and Must be tied to the user's sessions. It is used to send requests to the server, in which the token validates them. This is one way of protecting against csrf, another would be checking the referrer header.

How can I insert into a BLOB column from an insert statement in sqldeveloper?

To insert a VARCHAR2 into a BLOB column you can rely on the function utl_raw.cast_to_raw as next:

insert into mytable(id, myblob) values (1, utl_raw.cast_to_raw('some magic here'));

It will cast your input VARCHAR2 into RAW datatype without modifying its content, then it will insert the result into your BLOB column.

More details about the function utl_raw.cast_to_raw

Window.Open with PDF stream instead of PDF location

Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { // Directly use base 64 encoded data for rest browsers (not IE)
        var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
        window.open(dataURI, '_blank');
    }

}

How to increase maximum execution time in php

ini_set('max_execution_time', '300'); //300 seconds = 5 minutes
ini_set('max_execution_time', '0'); // for infinite time of execution 

Place this at the top of your PHP script and let your script loose!

Taken from Increase PHP Script Execution Time Limit Using ini_set()

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

Don't use in Browser

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

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

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

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

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

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

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

Printing string variable in Java

You're getting the toString() value returned by the Scanner object itself which is not what you want and not how you use a Scanner object. What you want instead is the data obtained by the Scanner object. For example,

Scanner input = new Scanner(System.in);
String data = input.nextLine();
System.out.println(data);

Please read the tutorial on how to use it as it will explain all.

Edit
Please look here: Scanner tutorial

Also have a look at the Scanner API which will explain some of the finer points of Scanner's methods and properties.

Extracting text OpenCV

This is a C# version of the answer from dhanushka using OpenCVSharp

        Mat large = new Mat(INPUT_FILE);
        Mat rgb = new Mat(), small = new Mat(), grad = new Mat(), bw = new Mat(), connected = new Mat();

        // downsample and use it for processing
        Cv2.PyrDown(large, rgb);
        Cv2.CvtColor(rgb, small, ColorConversionCodes.BGR2GRAY);

        // morphological gradient
        var morphKernel = Cv2.GetStructuringElement(MorphShapes.Ellipse, new OpenCvSharp.Size(3, 3));
        Cv2.MorphologyEx(small, grad, MorphTypes.Gradient, morphKernel);

        // binarize
        Cv2.Threshold(grad, bw, 0, 255, ThresholdTypes.Binary | ThresholdTypes.Otsu);

        // connect horizontally oriented regions
        morphKernel = Cv2.GetStructuringElement(MorphShapes.Rect, new OpenCvSharp.Size(9, 1));
        Cv2.MorphologyEx(bw, connected, MorphTypes.Close, morphKernel);

        // find contours
        var mask = new Mat(Mat.Zeros(bw.Size(), MatType.CV_8UC1), Range.All);
        Cv2.FindContours(connected, out OpenCvSharp.Point[][] contours, out HierarchyIndex[] hierarchy, RetrievalModes.CComp, ContourApproximationModes.ApproxSimple, new OpenCvSharp.Point(0, 0));

        // filter contours
        var idx = 0;
        foreach (var hierarchyItem in hierarchy)
        {
            idx = hierarchyItem.Next;
            if (idx < 0)
                break;
            OpenCvSharp.Rect rect = Cv2.BoundingRect(contours[idx]);
            var maskROI = new Mat(mask, rect);
            maskROI.SetTo(new Scalar(0, 0, 0));

            // fill the contour
            Cv2.DrawContours(mask, contours, idx, Scalar.White, -1);

            // ratio of non-zero pixels in the filled region
            double r = (double)Cv2.CountNonZero(maskROI) / (rect.Width * rect.Height);
            if (r > .45 /* assume at least 45% of the area is filled if it contains text */
                 &&
            (rect.Height > 8 && rect.Width > 8) /* constraints on region size */
            /* these two conditions alone are not very robust. better to use something 
            like the number of significant peaks in a horizontal projection as a third condition */
            )
            {
                Cv2.Rectangle(rgb, rect, new Scalar(0, 255, 0), 2);
            }
        }

        rgb.SaveImage(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "rgb.jpg"));

Why aren't programs written in Assembly more often?

I'm sure there are many reasons, but two quick reasons I can think of are

  1. Assembly code is definitely harder to read (I'm positive its more time-consuming to write as well)
  2. When you have a huge team of developers working on a product, it is helpful to have your code divided into logical blocks and protected by interfaces.

How to convert list data into json in java

Try like below with Gson Library.

Earlier Conversion List format were:

[Product [Id=1, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=32 inches, Price=33500.5, Stock=17.0], Product [Id=2, City=Bengalore, Category=TV, Brand=Samsung, Name=Samsung LED, Type=LED, Size=42 inches, Price=41850.0, Stock=9.0]]

and here the conversion source begins.

//** Note I have created the method toString() in Product class.

//Creating and initializing a java.util.List of Product objects
List<Product> productList = (List<Product>)productRepository.findAll();

//Creating a blank List of Gson library JsonObject
List<JsonObject> entities = new ArrayList<JsonObject>();

//Simply printing productList size
System.out.println("Size of productList is : " + productList.size());

//Creating a Iterator for productList
Iterator<Product> iterator = productList.iterator();

//Run while loop till Product Object exists.
while(iterator.hasNext()){

    //Creating a fresh Gson Object
    Gson gs = new Gson();

    //Converting our Product Object to JsonElement 
    //Object by passing the Product Object String value (iterator.next())
    JsonElement element = gs.fromJson (gs.toJson(iterator.next()), JsonElement.class);

    //Creating JsonObject from JsonElement
    JsonObject jsonObject = element.getAsJsonObject();

    //Collecting the JsonObject to List
    entities.add(jsonObject);

}

//Do what you want to do with Array of JsonObject
System.out.println(entities);

Converted Json Result is :

[{"Id":1,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"32 inches","Price":33500.5,"Stock":17.0}, {"Id":2,"City":"Bengalore","Category":"TV","Brand":"Samsung","Name":"Samsung LED","Type":"LED","Size":"42 inches","Price":41850.0,"Stock":9.0}]

Hope this would help many guys!

Should I use JSLint or JSHint JavaScript validation?

Well, Instead of doing manual lint settings we can include all the lint settings at the top of our JS file itself e.g.

Declare all the global var in that file like:

/*global require,dojo,dojoConfig,alert */

Declare all the lint settings like:

/*jslint browser:true,sloppy:true,nomen:true,unparam:true,plusplus:true,indent:4 */

Hope this will help you :)

Loop through the rows of a particular DataTable

You want to loop on the .Rows, and access the column for the row like q("column")

Just:

        For Each q In dtDataTable.Rows
            strDetail = q("Detail")
        Next

Also make sure to check msdn doc for any class you are using + use intellisense

Why are static variables considered evil?

From my point of view static variable should be only read only data or variables created by convention.

For example we have a ui of some project, and we have a list of countries, languages, user roles, etc. And we have class to organize this data. we absolutely sure that app will not work without this lists. so the first that we do on app init is checking this list for updates and getting this list from api (if needed). So we agree that this data is "always" present in app. It is practically read only data so we don't need to take care of it's state - thinking about this case we really don't want to have a lot of instances of those data - this case looks a perfect candidate to be static.

Not connecting to SQL Server over VPN

Try changing Server name with its IP for example

SERVERNAME//SQLSERVER -> 192.168.0.2//SQLSERVER

its work flawlessly with me using VPN

How can I divide one column of a data frame through another?

There are a plethora of ways in which this can be done. The problem is how to make R aware of the locations of the variables you wish to divide.

Assuming

d <- read.table(text = "263807.0    1582
196190.5    1016
586689.0    3479
")
names(d) <- c("min", "count2.freq")
> d
       min count2.freq
1 263807.0        1582
2 196190.5        1016
3 586689.0        3479

My preferred way

To add the desired division as a third variable I would use transform()

> d <- transform(d, new = min / count2.freq)
> d
       min count2.freq      new
1 263807.0        1582 166.7554
2 196190.5        1016 193.1009
3 586689.0        3479 168.6373

The basic R way

If doing this in a function (i.e. you are programming) then best to avoid the sugar shown above and index. In that case any of these would do what you want

## 1. via `[` and character indexes
d[, "new"] <- d[, "min"] / d[, "count2.freq"]

## 2. via `[` with numeric indices
d[, 3] <- d[, 1] / d[, 2]

## 3. via `$`
d$new <- d$min / d$count2.freq

All of these can be used at the prompt too, but which is easier to read:

d <- transform(d, new = min / count2.freq)

or

d$new <- d$min / d$count2.freq ## or any of the above examples

Hopefully you think like I do and the first version is better ;-)

The reason we don't use the syntactic sugar of tranform() et al when programming is because of how they do their evaluation (look for the named variables). At the top level (at the prompt, working interactively) transform() et al work just fine. But buried in function calls or within a call to one of the apply() family of functions they can and often do break.

Likewise, be careful using numeric indices (## 2. above); if you change the ordering of your data, you will select the wrong variables.

The preferred way if you don't need replacement

If you are just wanting to do the division (rather than insert the result back into the data frame, then use with(), which allows us to isolate the simple expression you wish to evaluate

> with(d, min / count2.freq)
[1] 166.7554 193.1009 168.6373

This is again much cleaner code than the equivalent

> d$min / d$count2.freq
[1] 166.7554 193.1009 168.6373

as it explicitly states that "using d, execute the code min / count2.freq. Your preference may be different to mine, so I have shown all options.

Catch browser's "zoom" event in JavaScript

Lets define px_ratio as below:

px ratio = ratio of physical pixel to css px.

if any one zoom The Page, the viewport pxes (px is different from pixel ) reduces and should be fit to The screen so the ratio (physical pixel / CSS_px ) must get bigger.

but in window Resizing, screen size reduces as well as pxes. so the ratio will maintain.

zooming: trigger windows.resize event --> and change px_ratio

but

resizing: trigger windows.resize event --> doesn’t change px_ratio

//for zoom detection
px_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth;

$(window).resize(function(){isZooming();});

function isZooming(){
    var newPx_ratio = window.devicePixelRatio || window.screen.availWidth / document.documentElement.clientWidth;
    if(newPx_ratio != px_ratio){
        px_ratio = newPx_ratio;
        console.log("zooming");
        return true;
    }else{
        console.log("just resizing");
        return false;
    }
}

The key point is difference between CSS PX and Physical Pixel.

https://gist.github.com/abilogos/66aba96bb0fb27ab3ed4a13245817d1e

Is the buildSessionFactory() Configuration method deprecated in Hibernate

Yes, it is deprecated. http://docs.jboss.org/hibernate/core/4.0/javadocs/org/hibernate/cfg/Configuration.html#buildSessionFactory() specifically tells you to use the other method you found instead (buildSessionFactory(ServiceRegistry serviceRegistry)) - so use it.

The documentation is copied over from release to release, and likely just hasn't been updated yet (they don't rewrite the manual with every release) - so trust the Javadocs.

The specifics of this change can be viewed at:

Some additional references:

Android Respond To URL in Intent

You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/ vs https/, www. vs no www., etc).

For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms)

Note that path prefix is optional.

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="http" />
            <data android:scheme="https" />

            <data android:host="www.docs.google.com" />
            <data android:host="docs.google.com" />

            <data android:pathPrefix="/forms" />
        </intent-filter>

Call parent method from child class c#

To access properties and methods of a parent class use the base keyword. So in your child class LoadData() method you would do this:

public class Child : Parent 
{
    public void LoadData() 
    {
        base.MyMethod(); // call method of parent class
        base.CurrentRow = 1; // set property of parent class
        // other stuff...
    }
}

Note that you would also have to change the access modifier of your parent MyMethod() to at least protected for the child class to access it.

How do I clear a search box with an 'x' in bootstrap 3?

Do it with inline styles and script:

<div class="btn-group has-feedback has-clear">
    <input id="searchinput" type="search" class="form-control" style="width:200px;">
        <a 
id="searchclear" 
class="glyphicon glyphicon-remove-circle form-control-feedback form-control-clear" 
style="pointer-events:auto; text-decoration:none; cursor:pointer;"
onclick="$(this).prev('input').val('');return false;">
</a>
</div>

Django Forms: if not valid, show form with error message

simply you can do like this because when you initialized the form in contains form data and invalid data as well:

def some_func(request):
    form = MyForm(request.POST)
    if form.is_valid():
         //other stuff
    return render(request,template_name,{'form':form})

if will raise the error in the template if have any but the form data will still remain as :

error_demo_here

What is the simplest way to convert array to vector?

One simple way can be the use of assign() function that is pre-defined in vector class.

e.g.

array[5]={1,2,3,4,5};

vector<int> v;
v.assign(array, array+5); // 5 is size of array.

Get value from JToken that may not exist (best practices)

Here is how you can check if the token exists:

if (jobject["Result"].SelectToken("Items") != null) { ... }

It checks if "Items" exists in "Result".

This is a NOT working example that causes exception:

if (jobject["Result"]["Items"] != null) { ... }

How to force IE10 to render page in IE9 document mode

I haven't seen this done before, but this is how it was done for emulating IE 8/7 when using IE 9:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE9">

If not, then try this one:

<meta http-equiv="X-UA-Compatible" content="IE=9">

Add those to your header with the other meta tags. This should force IE10 to render as IE9.

Another option you could do (assuming you are using PHP) is add this to your .htaccess file:

Header set X-UA-Compatible "IE=9"

This will perform the action universally, rather than having to worry about adding the meta tag to all of your headers.

List of phone number country codes

Rather than trying to roll your own logic for determining the country code of a phone number, I highly recommend using Google's libphonenumber project. This project is very extensive and well maintained, and has been ported to a several languages.

D3.js: How to get the computed width and height for an arbitrary element?

For SVG elements

Using something like selection.node().getBBox() you get values like

{
    height: 5, 
    width: 5, 
    y: 50, 
    x: 20
} 

For HTML elements

Use selection.node().getBoundingClientRect()

Where is Java Installed on Mac OS X?

if you are using sdkman

you can check it with sdk home java <installed_java_version>

$  sdk home java 8.0.252.j9-adpt
/Users/admin/.sdkman/candidates/java/8.0.252.j9-adpt

you can get your installed java version with

$ sdk list java

Found 'OR 1=1/* sql injection in my newsletter database

The specific value in your database isn't what you should be focusing on. This is likely the result of an attacker fuzzing your system to see if it is vulnerable to a set of standard attacks, instead of a targeted attack exploiting a known vulnerability.

You should instead focus on ensuring that your application is secure against these types of attacks; OWASP is a good resource for this.

If you're using parameterized queries to access the database, then you're secure against Sql injection, unless you're using dynamic Sql in the backend as well.

If you're not doing this, you're vulnerable and you should resolve this immediately.

Also, you should consider performing some sort of validation of e-mail addresses.

python pandas dataframe to dictionary

Another (slightly shorter) solution for not losing duplicate entries:

>>> ptest = pd.DataFrame([['a',1],['a',2],['b',3]], columns=['id','value'])
>>> ptest
  id  value
0  a      1
1  a      2
2  b      3

>>> pdict = dict()
>>> for i in ptest['id'].unique().tolist():
...     ptest_slice = ptest[ptest['id'] == i]
...     pdict[i] = ptest_slice['value'].tolist()
...

>>> pdict
{'b': [3], 'a': [1, 2]}

ld cannot find -l<library>

you can add the Path to coinhsl lib to LD_LIBRARY_PATH variable. May be that will help.

export LD_LIBRARY_PATH=/xx/yy/zz:$LD_LIBRARY_PATH

where /xx/yy/zz represent the path to coinhsl lib.

ES6 modules implementation, how to load a json file

With json-loader installed, now you can simply use:

import suburbs from '../suburbs.json';

or, even more simply:

import suburbs from '../suburbs';

Display PDF within web browser

You can use the <embed> tag with the source of the file in the src attribute. This uses the native browser PDF viewer.

<embed src="your_pdf_src" style="position:absolute; left: 0; top: 0;" width="100%" height="100%" type="application/pdf">

Live example:

_x000D_
_x000D_
<embed src="https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf" style="position:absolute; left: 0; top: 0;" width="100%" height="100%" type="application/pdf">
_x000D_
_x000D_
_x000D_

Loading the PDF inside a snippet won't work, since the frame into which the plugin is loading is sandboxed.

Tested in Chrome and Firefox. See it in action.

How to set image button backgroundimage for different state?

Create an xml file in your drawable like this :

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item
        android:state_enabled="false"
        android:drawable="@drawable/btn_sendemail_disable" />
    <item
        android:state_pressed="true"
        android:state_enabled="true"
        android:drawable="@drawable/btn_send_email_click" />
    <item
        android:state_focused="true"
        android:state_enabled="true"
        android:drawable="@drawable/btn_sendemail_roll" />
    <item
        android:state_enabled="true"
        android:drawable="@drawable/btn_sendemail" />
</selector>

And set images accordingly and then set this xml as background of your imageButton.

How to move up a directory with Terminal in OS X

For Mac Terminal

cd ..   # one up
cd ../  # two up
cd      # home directory 
cd /    # root directory
cd "yaya-13" # use quotes if the file name contains punctuation or spaces

git pull keeping local changes

We can also try git pull with rebase

git pull --rebase origin dev

How much RAM is SQL Server actually using?

Go to management studio and run sp_helpdb <db_name>, it will give detailed disk usage for the specified database. Running it without any parameter values will list high level information for all databases in the instance.

How to autoplay HTML5 mp4 video on Android?

In Android 4.1 and 4.2, I use the following code.

    evt.initMouseEvent( "click", true,true,window,0,0,0,0,0,false,false,false,false,0, true );
    var v = document.getElementById("video");
    v.dispatchEvent(evt);

where html is

    <video id="video" src="sample.mp4" poster="image.jpg" controls></video>

This works well. But In Android 4.4, it does not work.

Javascript: Fetch DELETE and PUT requests

Some examples:

async function loadItems() { try { let response = await fetch(https://url/${AppID}); let result = await response.json(); return result; } catch (err) { } }

async function addItem(item) {
    try {
        let response = await fetch("https://url", {
            method: "POST",
            body: JSON.stringify({
                AppId: appId,
                Key: item,
                Value: item,
                someBoolean: false,
            }),
            headers: {
                "Content-Type": "application/json",
            },
        });
        let result = await response.json();
        return result;
    } catch (err) {
    }
}

async function removeItem(id) {
    try {
        let response = await fetch(`https://url/${id}`, {
            method: "DELETE",
        });
    } catch (err) {
    }
}

async function updateItem(item) {
    try {
        let response = await fetch(`https://url/${item.id}`, {
            method: "PUT",
            body: JSON.stringify(todo),
            headers: {
                "Content-Type": "application/json",
            },
        });
    } catch (err) {
    }
}

Android Lint contentDescription warning

Since it is only a warning you can suppress it. Go to your XML's Graphical Layout and do this:

  1. Click on the right top corner red button

    enter image description here

  2. Select "Disable Issue Type" (for example)

    enter image description here

Five equal columns in twitter bootstrap

Bootstrap or other grid system it doesn't always mean simpler and better. Inside your .container or .row (to keep your responsive layout) u can just create 5 divs (with class .col f.e.) and add css like this:
.col { width: 20%; float: left };

update: nowodays its better to use flexbox

How to implement a material design circular progress bar in android

With the Material Components library you can use the CircularProgressIndicator:

Something like:

<com.google.android.material.progressindicator.CircularProgressIndicator
      android:indeterminate="true"          
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      app:indicatorColor="@array/progress_colors"
      app:indicatorSize="xxdp"
      app:showAnimationBehavior="inward"/>

where array/progress_colors is an array with the colors:

  <integer-array name="progress_colors">
    <item>@color/yellow_500</item>
    <item>@color/blue_700</item>
    <item>@color/red_500</item>
  </integer-array>

enter image description here

Note: it requires at least the version 1.3.0

django admin - add custom form fields that are not part of the model

you can always create new admin template , and do what you need in your admin_view (override the admin add url to your admin_view):

 url(r'^admin/mymodel/mymodel/add/$' , 'admin_views.add_my_special_model')

Reactjs: Unexpected token '<' Error

in my case, i had failed to include the type attribute on my script tag.

<script type="text/jsx">

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

The meaning of CascadeType.ALL is that the persistence will propagate (cascade) all EntityManager operations (PERSIST, REMOVE, REFRESH, MERGE, DETACH) to the relating entities.

It seems in your case to be a bad idea, as removing an Address would lead to removing the related User. As a user can have multiple addresses, the other addresses would become orphans. However the inverse case (annotating the User) would make sense - if an address belongs to a single user only, it is safe to propagate the removal of all addresses belonging to a user if this user is deleted.

BTW: you may want to add a mappedBy="addressOwner" attribute to your User to signal to the persistence provider that the join column should be in the ADDRESS table.

How do you calculate log base 2 in Java for integers?

This is the function that I use for this calculation:

public static int binlog( int bits ) // returns 0 for bits=0
{
    int log = 0;
    if( ( bits & 0xffff0000 ) != 0 ) { bits >>>= 16; log = 16; }
    if( bits >= 256 ) { bits >>>= 8; log += 8; }
    if( bits >= 16  ) { bits >>>= 4; log += 4; }
    if( bits >= 4   ) { bits >>>= 2; log += 2; }
    return log + ( bits >>> 1 );
}

It is slightly faster than Integer.numberOfLeadingZeros() (20-30%) and almost 10 times faster (jdk 1.6 x64) than a Math.log() based implementation like this one:

private static final double log2div = 1.000000000001 / Math.log( 2 );
public static int log2fp0( int bits )
{
    if( bits == 0 )
        return 0; // or throw exception
    return (int) ( Math.log( bits & 0xffffffffL ) * log2div );
}

Both functions return the same results for all possible input values.

Update: The Java 1.7 server JIT is able to replace a few static math functions with alternative implementations based on CPU intrinsics. One of those functions is Integer.numberOfLeadingZeros(). So with a 1.7 or newer server VM, a implementation like the one in the question is actually slightly faster than the binlog above. Unfortunatly the client JIT doesn't seem to have this optimization.

public static int log2nlz( int bits )
{
    if( bits == 0 )
        return 0; // or throw exception
    return 31 - Integer.numberOfLeadingZeros( bits );
}

This implementation also returns the same results for all 2^32 possible input values as the the other two implementations I posted above.

Here are the actual runtimes on my PC (Sandy Bridge i7):

JDK 1.7 32 Bits client VM:

binlog:         11.5s
log2nlz:        16.5s
log2fp:        118.1s
log(x)/log(2): 165.0s

JDK 1.7 x64 server VM:

binlog:          5.8s
log2nlz:         5.1s
log2fp:         89.5s
log(x)/log(2): 108.1s

This is the test code:

int sum = 0, x = 0;
long time = System.nanoTime();
do sum += log2nlz( x ); while( ++x != 0 );
time = System.nanoTime() - time;
System.out.println( "time=" + time / 1000000L / 1000.0 + "s -> " + sum );

Eclipse - Unable to install breakpoint due to missing line number attributes

For Spring related issues consider that in some cases it generate classes "without line numbers"; for example a @Service annotated class without an interface, add the interface and you can debug. see here for a complete example.

@Service("SkillService")
public class TestServiceWithoutInterface {
   public void doSomething() {
      System.out.println("Hello TestServiceWithoutInterface");
   }
}

The service above will have an interface generated by spring causing "missing line numbers". Adding a real interface solve the generation problem:

public interface TestService {
    void doSomething();
}

@Service("SkillService")
public class TestServiceImpl implements TestService {
   public void doSomething() {
      System.out.println("Hello TestServiceImpl");
   }
}

Force “landscape” orientation mode

screen.orientation.lock('landscape');

Will force it to change to and stay in landscape mode. Tested on Nexus 5.

http://www.w3.org/TR/screen-orientation/#examples

An example of how to use getopts in bash

The example packaged with getopt (my distro put it in /usr/share/getopt/getopt-parse.bash) looks like it covers all of your cases:

#!/bin/bash

# A small example program for using the new getopt(1) program.
# This program will only work with bash(1)
# An similar program using the tcsh(1) script language can be found
# as parse.tcsh

# Example input and output (from the bash prompt):
# ./parse.bash -a par1 'another arg' --c-long 'wow!*\?' -cmore -b " very long "
# Option a
# Option c, no argument
# Option c, argument `more'
# Option b, argument ` very long '
# Remaining arguments:
# --> `par1'
# --> `another arg'
# --> `wow!*\?'

# Note that we use `"$@"' to let each command-line parameter expand to a 
# separate word. The quotes around `$@' are essential!
# We need TEMP as the `eval set --' would nuke the return value of getopt.
TEMP=`getopt -o ab:c:: --long a-long,b-long:,c-long:: \
     -n 'example.bash' -- "$@"`

if [ $? != 0 ] ; then echo "Terminating..." >&2 ; exit 1 ; fi

# Note the quotes around `$TEMP': they are essential!
eval set -- "$TEMP"

while true ; do
    case "$1" in
        -a|--a-long) echo "Option a" ; shift ;;
        -b|--b-long) echo "Option b, argument \`$2'" ; shift 2 ;;
        -c|--c-long) 
            # c has an optional argument. As we are in quoted mode,
            # an empty parameter will be generated if its optional
            # argument is not found.
            case "$2" in
                "") echo "Option c, no argument"; shift 2 ;;
                *)  echo "Option c, argument \`$2'" ; shift 2 ;;
            esac ;;
        --) shift ; break ;;
        *) echo "Internal error!" ; exit 1 ;;
    esac
done
echo "Remaining arguments:"
for arg do echo '--> '"\`$arg'" ; done

How to load a tsv file into a Pandas DataFrame?

As of 17.0 from_csv is discouraged.

Use pd.read_csv(fpath, sep='\t') or pd.read_table(fpath).

.bashrc: Permission denied

.bashrc is not meant to be executed but sourced. Try this instead:

. ~/.bashrc

Cheers!

How to get current user in asp.net core

This is old question but my case shows that my case wasn't discussed here.

I like the most the answer of Simon_Weaver (https://stackoverflow.com/a/54411397/2903893). He explains in details how to get user name using IPrincipal and IIdentity. This answer is absolutely correct and I recommend to use this approach. However, during debugging I encountered with the problem when ASP.NET can NOT populate service principle properly. (or in other words, IPrincipal.Identity.Name is null)

It's obvious that to get user name MVC framework should take it from somewhere. In the .NET world, ASP.NET or ASP.NET Core is using Open ID Connect middleware. In the simple scenario web apps authenticate a user in a web browser. In this scenario, the web application directs the user’s browser to sign them in to Azure AD. Azure AD returns a sign-in response through the user’s browser, which contains claims about the user in a security token. To make it work in the code for your application, you'll need to provide the authority to which you web app delegates sign-in. When you deploy your web app to Azure Service the common scenario to meet this requirements is to configure web app: "App Services" -> YourApp -> "Authentication / Authorization" blade -> "App Service Authenticatio" = "On" and so on (https://github.com/Huachao/azure-content/blob/master/articles/app-service-api/app-service-api-authentication.md). I beliebe (this is my educated guess) that under the hood of this process the wizard adjusts "parent" web config of this web app by adding the same settings that I show in following paragraphs. Basically, the issue why this approach does NOT work in ASP.NET Core is because "parent" machine config is ignored by webconfig. (this is not 100% sure, I just give the best explanation that I have). So, to meke it work you need to setup this manually in your app.

Here is an article that explains how to manyally setup your app to use Azure AD. https://github.com/Azure-Samples/active-directory-aspnetcore-webapp-openidconnect-v2/tree/aspnetcore2-2

Step 1: Register the sample with your Azure AD tenant. (it's obvious, don't want to spend my time of explanations).

Step 2: In the appsettings.json file: replace the ClientID value with the Application ID from the application you registered in Application Registration portal on Step 1. replace the TenantId value with common

Step 3: Open the Startup.cs file and in the ConfigureServices method, after the line containing .AddAzureAD insert the following code, which enables your application to sign in users with the Azure AD v2.0 endpoint, that is both Work and School and Microsoft Personal accounts.

services.Configure<OpenIdConnectOptions>(AzureADDefaults.OpenIdScheme, options =>
{
    options.Authority = options.Authority + "/v2.0/";
    options.TokenValidationParameters.ValidateIssuer = false;
});

Summary: I've showed one more possible issue that could leed to an error that topic starter is explained. The reason of this issue is missing configurations for Azure AD (Open ID middleware). In order to solve this issue I propose manually setup "Authentication / Authorization". The short overview of how to setup this is added.

How to get a file or blob from an object URL?

Using fetch for example like below:

 fetch(<"yoururl">, {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + <your access token if need>
    },
       })
.then((response) => response.blob())
.then((blob) => {
// 2. Create blob link to download
 const url = window.URL.createObjectURL(new Blob([blob]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', `sample.xlsx`);
 // 3. Append to html page
 document.body.appendChild(link);
 // 4. Force download
 link.click();
 // 5. Clean up and remove the link
 link.parentNode.removeChild(link);
})

You can paste in on Chrome console to test. the file with download with 'sample.xlsx' Hope it can help!

How to make a website secured with https

What kind of business data? Trade secrets or just stuff that they don't want people to see but if it got out, it wouldn't be a big deal? If we are talking trade secrets, financial information, customer information and stuff that's generally confidential. Then don't even go down that route.

I'm wondering whether I need to use a secured connection (https) or just the forms authentication is enough.

Use a secure connection all the way.

Do I need to alter the code / Config

Yes. Well may be not. You may want to have an expert do this for you.

Is SSL and https one and the same...

Mostly yes. People usually refer to those things as the same thing.

Do I need to apply with someone to get some license or something.

You probably want to have your certificate signed by a certificate authority. It will cost you or your client a bit of money.

Do I need to make all my pages secured or only the login page...

Use https throughout. Performance is usually not an issue if the site is meant for internal users.

I was searching Internet for answer, but I was not able to get all these points... Any whitepaper or other references would also be helpful...

Start here for some pointers: http://www.owasp.org/index.php/Category:OWASP_Guide_Project

Note that SSL is a minuscule piece of making your web site secure once it is accessible from the internet. It does not prevent most sort of hacking.

Is there a Sleep/Pause/Wait function in JavaScript?

You need to re-factor the code into pieces. This doesn't stop execution, it just puts a delay in between the parts.

function partA() {
  ...
  window.setTimeout(partB,1000);
}

function partB() {
   ...
}

What is the difference between CMD and ENTRYPOINT in a Dockerfile?

I'll add my answer as an example1 that might help you better understand the difference.

Let's suppose we want to create an image that will always run a sleep command when it starts. We'll create our own image and specify a new command:

FROM ubuntu
CMD sleep 10

Building the image:

docker build -t custom_sleep .
docker run custom_sleep
# sleeps for 10 seconds and exits

What if we want to change the number of seconds? We would have to change the Dockerfile since the value is hardcoded there, or override the command by providing a different one:

docker run custom_sleep sleep 20

While this works, it's not a good solution, as we have a redundant "sleep" command. Why redundant? Because the container's only purpose is to sleep, so having to specify the sleep command explicitly is a bit awkward.

Now let's try using the ENTRYPOINT instruction:

FROM ubuntu
ENTRYPOINT sleep

This instruction specifies the program that will be run when the container starts.

Now we can run:

docker run custom_sleep 20

What about a default value? Well, you guessed it right:

FROM ubuntu
ENTRYPOINT ["sleep"]
CMD ["10"]

The ENTRYPOINT is the program that will be run, and the value passed to the container will be appended to it.

The ENTRYPOINT can be overridden by specifying an --entrypoint flag, followed by the new entry point you want to use.

Not mine, I once watched a tutorial that provided this example

How can I make a .NET Windows Forms application that only runs in the System Tray?

Simply add

this.WindowState = FormWindowState.Minimized;
this.ShowInTaskbar = false;

to your form object. You will see only an icon at system tray.

Why is a div with "display: table-cell;" not affected by margin?

Table cells don't respect margin, but you could use transparent borders instead:

div {
  display: table-cell;
  border: 5px solid transparent;
}

Note: you can't use percentages here... :(

Unable to load script.Make sure you are either running a Metro server or that your bundle 'index.android.bundle' is packaged correctly for release

I did: react-native start and npx react-native run-android.

However, for Min19, (Ubuntu based) I was having the same problem until I run:

echo fs.inotify.max_user_watches=582222 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

From: https://reactnative.dev/docs/troubleshooting#content

At least I got the app running in my cell phone.

What is the difference between id and class in CSS, and when should I use them?

id selector can be used to more elements. here is the example:

css:

#t_color{
    color: red;
}
#f_style{
    font-family: arial;
    font-size: 20px;
}

html:

<p id="t_color"> test only </p>
<div id="t_color">the box text</div>

I tested on internet explorer (ver. 11.0) and Chrome (ver.47.0). it works on both of them.

The "unique" only means one element can not have more than one id attributes like class selector. Neither

<p id="t_color f_style">...</p>

nor

<p id="t_color" id="f_style">...</p>

How to draw a standard normal distribution in R

Something like this perhaps?

x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)

How to not wrap contents of a div?

A combination of both float: left; white-space: nowrap; worked for me.

Each of them independently didn't accomplish the desired result.

How to connect wireless network adapter to VMWare workstation?

Change your network adapter to a bridged connection, this will directly connect to your computers physical network.

difference between width auto and width 100 percent

Width auto

The initial width of a block level element like div or p is auto. This makes it expand to occupy all available horizontal space within its containing block. If it has any horizontal padding or border, the widths of those do not add to the total width of the element.

Width 100%

On the other hand, if you specify width:100%, the element’s total width will be 100% of its containing block plus any horizontal margin, padding and border (unless you’ve used box-sizing:border-box, in which case only margins are added to the 100% to change how its total width is calculated). This may be what you want, but most likely it isn’t.

To visualise the difference see this picture:

enter image description here

Source

How to use 'git pull' from the command line?

Try setting the HOME environment variable in Windows to your home folder (c:\users\username).

( you can confirm that this is the problem by doing echo $HOME in git bash and echo %HOME% in cmd - latter might not be available )

Retrieve specific commit from a remote Git repository

You can simply fetch the remote repo with:

git fetch <repo>

where,

  • <repo> can be a remote repo name (e.g. origin) or even a remote repo URL (e.g. https://git.foo.com/myrepo.git)

for example:

git fetch https://git.foo.com/myrepo.git 

after you fetched the repos you may merge the commits that you want (since the question is about retrieve one commit, instead merge you may use cherry-pick to pick just one commit):

git merge <commit>
  • <commit> can be the SHA1 commit

for example:

git cherry-pick 0a071603d87e0b89738599c160583a19a6d95545

or

git merge 0a071603d87e0b89738599c160583a19a6d95545

if is the latest commit that you want to merge, you also may use FETCH_HEAD variable :

git cherry-pick (or merge) FETCH_HEAD

Set type for function parameters?

Use typeof or instanceof:

const assert = require('assert');

function myFunction(Date myDate, String myString)
{
    assert( typeof(myString) === 'string',  'Error message about incorrect arg type');
    assert( myDate instanceof Date,         'Error message about incorrect arg type');
}

What is the benefit of using "SET XACT_ABORT ON" in a stored procedure?

It is used in transaction management to ensure that any errors result in the transaction being rolled back.

Unioning two tables with different number of columns

I came here and followed above answer. But mismatch in the Order of data type caused an error. The below description from another answer will come handy.

Are the results above the same as the sequence of columns in your table? because oracle is strict in column orders. this example below produces an error:

create table test1_1790 (
col_a varchar2(30),
col_b number,
col_c date);

create table test2_1790 (
col_a varchar2(30),
col_c date,
col_b number);

select * from test1_1790
union all
select * from test2_1790;

ORA-01790: expression must have same datatype as corresponding expression

As you see the root cause of the error is in the mismatching column ordering that is implied by the use of * as column list specifier. This type of errors can be easily avoided by entering the column list explicitly:

select col_a, col_b, col_c from test1_1790 union all select col_a, col_b, col_c from test2_1790; A more frequent scenario for this error is when you inadvertently swap (or shift) two or more columns in the SELECT list:

select col_a, col_b, col_c from test1_1790
union all
select col_a, col_c, col_b from test2_1790;

OR if the above does not solve your problem, how about creating an ALIAS in the columns like this: (the query is not the same as yours but the point here is how to add alias in the column.)

SELECT id_table_a, 
       desc_table_a, 
       table_b.id_user as iUserID, 
       table_c.field as iField
UNION
SELECT id_table_a, 
       desc_table_a, 
       table_c.id_user as iUserID, 
       table_c.field as iField

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

If you're trying to use MatDialog inside a service - let's call it 'PopupService' and that service is defined in a module with:

@Injectable({ providedIn: 'root' })

then it may not work. I am using lazy loading, but not sure if that's relevant or not.

You have to:

  • Provide your PopupService directly to the component that opens your dialog - using [ provide: PopupService ]. This allows it to use (with DI) the MatDialog instance in the component. I think the component calling open needs to be in the same module as the dialog component in this instance.
  • Move the dialog component up to your app.module (as some other answers have said)
  • Pass a reference for matDialog when you call your service.

Excuse my jumbled answer, the point being it's the providedIn: 'root' that is breaking things because MatDialog needs to piggy-back off a component.

Remove HTML Tags in Javascript with Regex

Like others have stated, regex will not work. Take a moment to read my article about why you cannot and should not try to parse html with regex, which is what you're doing when you're attempting to strip html from your source string.

jQuery AJAX submit form

There's also the submit event, which can be triggered like this $("#form_id").submit(). You'd use this method if the form is well represented in HTML already. You'd just read in the page, populate the form inputs with stuff, then call .submit(). It'll use the method and action defined in the form's declaration, so you don't need to copy it into your javascript.

examples

How to get multiline input from user

raw_input can correctly handle the EOF, so we can write a loop, read till we have received an EOF (Ctrl-D) from user:

Python 3

print("Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it.")
contents = []
while True:
    try:
        line = input()
    except EOFError:
        break
    contents.append(line)

Python 2

print "Enter/Paste your content. Ctrl-D or Ctrl-Z ( windows ) to save it."
contents = []
while True:
    try:
        line = raw_input("")
    except EOFError:
        break
    contents.append(line)

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException

I still remember the first weeks of my programming courses and I totally understand how you feel. Here is the code that solves your problem. In order to learn from this answer, try to run it adding several 'print' in the loop, so you can see the progress of the variables.

import java.util.*;
import java.lang.*;

public class foo
{

   public static void main(String[] args)
   { 
      double[] alpha = new double[50];
      int count = 0;

      for (int i=0; i<50; i++)
      {
          // System.out.print("variable i = " + i + "\n");
          if (i < 25)
          {
                alpha[i] = i*i;
          }
          else {
                alpha[i] = 3*i;
          }

          if (count < 10)
          {
            System.out.print(alpha[i]+ " "); 
          }  
          else {
            System.out.print("\n"); 
            System.out.print(alpha[i]+ " "); 
            count = 0;
          }

          count++;
      }

      System.out.print("\n"); 

    }
}

Java GC (Allocation Failure)

When use CMS GC in jdk1.8 will appeare this error, i change the G1 Gc solve this problem.

 -Xss512k -Xms6g -Xmx6g -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:InitiatingHeapOccupancyPercent=70 -XX:NewRatio=1 -XX:SurvivorRatio=6 -XX:G1ReservePercent=10 -XX:G1HeapRegionSize=32m -XX:ConcGCThreads=6 -Xloggc:gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps 

Getting indices of True values in a boolean list

Using element-wise multiplication and a set:

>>> states = [False, False, False, False, True, True, False, True, False, False, False, False, False, False, False, False]
>>> set(multiply(states,range(1,len(states)+1))-1).difference({-1})

Output: {4, 5, 7}

How to log PostgreSQL queries?

There is an extension in postgresql for this. It's name is "pg_stat_statements". https://www.postgresql.org/docs/9.4/pgstatstatements.html

Basically you have to change postgresql.conf file a little bit:

shared_preload_libraries= 'pg_stat_statements'
pg_stat_statements.track = 'all'

Then you have to log in DB and run this command:

create extension pg_stat_statements;

It will create new view with name "pg_stat_statements". In this view you can see all the executed queries.

What is the syntax for Typescript arrow functions with generics?

I to use this type of declaration:

const identity: { <T>(arg: T): T } = (arg) => arg;

It allows defining additional props to your function if you ever need to and in some cases, it helps keeping the function body cleaner from the generic definition.

If you don't need the additional props (namespace sort of thing), it can be simplified to:

const identity: <T>(arg: T) => T = (arg) => arg;

How to setup Main class in manifest file in jar produced by NetBeans project

I read and read and read to figure out why I was getting a class not found error, it turns out the manifest.mf had an error in the line:

Main-Class: com.example.MainClass

I fixed the error by going to Project Properties dialog (right-click Project Files), then Run and Main Class and corrected whatever Netbeans decided to put here. Netbean inserted the project name instead of the class name. No idea why. Probably inebriated on muratina...

Get safe area inset top and bottom heights

Objective-C Who had the problem when keyWindow is equal to nil. Just put the code above in viewDidAppear (not in viewDidLoad)

how to add <script>alert('test');</script> inside a text box?

. I usually do it element.value="<script>alert('test');</script>".

If sounds like you are generating an inline <script> element, in which case the </script> will end the HTML element and cause the script to terminate in the middle of the string.

Escape the / so that it isn't treated as an end tag by the HTML parser:

element.value = "<script>alert('test');<\/script>"

apache mod_rewrite is not working or not enabled

It's working.

my solution is:

1.create a test.conf into /etc/httpd/conf.d/test.conf

2.wrote some rule, like:

<Directory "/var/www/html/test">
RewriteEngine On
RewriteRule ^link([^/]*).html$ rewrite.php?link=$1 [L]
</Directory>

3.restart your Apache server.

4.try again yourself.

PHP header redirect 301 - what are the implications?

Search engines like 301 redirects better than a 404 or some other type of client side redirect, no worries there.

CPU usage will be minimal, if you want to save even more cycles you could try and handle the redirect in apache using htaccess, then php won't even have to get involved. If you want to load test a server, you can use ab which comes with apache, or httperf if you are looking for a more robust testing tool.

jQuery animated number counter from zero to value

This is working for me

$('.Count').each(function () {
    $(this).prop('Counter',0).animate({
        Counter: $(this).text()
    }, {
        duration: 4000,
        easing: 'swing',
        step: function (now) {
            $(this).text(Math.ceil(now));
        }
    });
});

Writing a dictionary to a csv file with one line for every 'key: value'

I've personally always found the csv module kind of annoying. I expect someone else will show you how to do this slickly with it, but my quick and dirty solution is:

with open('dict.csv', 'w') as f:  # This creates the file object for the context 
                                  # below it and closes the file automatically
    l = []
    for k, v in mydict.iteritems(): # Iterate over items returning key, value tuples
        l.append('%s: %s' % (str(k), str(v))) # Build a nice list of strings
    f.write(', '.join(l))                     # Join that list of strings and write out

However, if you want to read it back in, you'll need to do some irritating parsing, especially if it's all on one line. Here's an example using your proposed file format.

with open('dict.csv', 'r') as f: # Again temporary file for reading
    d = {}
    l = f.read().split(',')      # Split using commas
    for i in l:
        values = i.split(': ')   # Split using ': '
        d[values[0]] = values[1] # Any type conversion will need to happen here

Direct download from Google Drive using Google Drive API

I would consider downloading from the link, scraping the page that you get to grab the confirmation link, and then downloading that.

If you look at the "download anyway" URL it has an extra confirm query parameter with a seemingly randomly generated token. Since it's random...and you probably don't want to figure out how to generate it yourself, scraping might be the easiest way without knowing anything about how the site works.

You may need to consider various scenarios.

Android Studio : unmappable character for encoding UTF-8

I had the same problem because there was files with windows-1251 encoding and Cyrillic comments. In Android Studio which is based on IntelliJ IDEA you can solve it in two ways:

a) convert file encoding to UTF-8 or

b) set the right file encoding in your build.gradle script:

android {
    ...
    compileOptions.encoding = 'windows-1251' // write your encoding here
    ...

To convert file encoding use the menu at the bottom right corner of IDE. Select right file encoding first -> press Reload -> select UTF-8 -> press Convert.

Also read this Use the UTF-8, Luke! File Encodings in IntelliJ IDEA

IllegalStateException: Can not perform this action after onSaveInstanceState with ViewPager

Please check my answer here. Basically I just had to :

@Override
protected void onSaveInstanceState(Bundle outState) {
    //No call for super(). Bug on API Level > 11.
}

Don't make the call to super() on the saveInstanceState method. This was messing things up...

This is a known bug in the support package.

If you need to save the instance and add something to your outState Bundle you can use the following:

@Override
protected void onSaveInstanceState(Bundle outState) {
    outState.putString("WORKAROUND_FOR_BUG_19917_KEY", "WORKAROUND_FOR_BUG_19917_VALUE");
    super.onSaveInstanceState(outState);
}

In the end the proper solution was (as seen in the comments) to use :

transaction.commitAllowingStateLoss();

when adding or performing the FragmentTransaction that was causing the Exception.

Can you require two form fields to match with HTML5?

Not exactly with HTML5 validation but a little JavaScript can resolve the issue, follow the example below:

<p>Password:</p>
<input name="password" required="required" type="password" id="password" />
<p>Confirm Password:</p>
<input name="password_confirm" required="required" type="password" id="password_confirm" oninput="check(this)" />
<script language='javascript' type='text/javascript'>
    function check(input) {
        if (input.value != document.getElementById('password').value) {
            input.setCustomValidity('Password Must be Matching.');
        } else {
            // input is valid -- reset the error message
            input.setCustomValidity('');
        }
    }
</script>
<br /><br />
<input type="submit" />

Delete files older than 15 days using PowerShell

Try this:

dir C:\PURGE -recurse | 
where { ((get-date)-$_.creationTime).days -gt 15 } | 
remove-item -force

Use Robocopy to copy only changed files?

To answer all your questions:

Can I use ROBOCOPY for this?

Yes, RC should fit your requirements (simplicity, only copy what needed)


What exactly does it mean to exclude?

It will exclude copying - RC calls it skipping


Would the /XO option copy only newer files, not files of the same age?

Yes, RC will only copy newer files. Files of the same age will be skipped.

(the correct command would be robocopy C:\SourceFolder D:\DestinationFolder ABC.dll /XO)


Maybe in your case using the /MIR option could be useful. In general RC is rather targeted at directories and directory trees than single files.

IntelliJ - show where errors are

In my case, IntelliJ was simply in power safe mode

How can I format a number into a string with leading zeros?

use:

i.ToString("D10")

See Int32.ToString (MSDN), and Standard Numeric Format Strings (MSDN).

Or use String.PadLeft. For example,

int i = 321;
Key = i.ToString().PadLeft(10, '0');

Would result in 0000000321. Though String.PadLeft would not work for negative numbers.

See String.PadLeft (MSDN).

When do Java generics require <? extends T> instead of <T> and is there any downside of switching?

One way for me to understand wildcards is to think that the wildcard isn't specifying the type of the possible objects that given generic reference can "have", but the type of other generic references that it is is compatible with (this may sound confusing...) As such, the first answer is very misleading in it's wording.

In other words, List<? extends Serializable> means you can assign that reference to other Lists where the type is some unknown type which is or a subclass of Serializable. DO NOT think of it in terms of A SINGLE LIST being able to hold subclasses of Serializable (because that is incorrect semantics and leads to a misunderstanding of Generics).

Pandas sort by group aggregate and column

Groupby A:

In [0]: grp = df.groupby('A')

Within each group, sum over B and broadcast the values using transform. Then sort by B:

In [1]: grp[['B']].transform(sum).sort('B')
Out[1]:
          B
2 -2.829710
5 -2.829710
1  0.253651
4  0.253651
0  0.551377
3  0.551377

Index the original df by passing the index from above. This will re-order the A values by the aggregate sum of the B values:

In [2]: sort1 = df.ix[grp[['B']].transform(sum).sort('B').index]

In [3]: sort1
Out[3]:
     A         B      C
2  baz -0.528172  False
5  baz -2.301539   True
1  bar -0.611756   True
4  bar  0.865408  False
0  foo  1.624345  False
3  foo -1.072969   True

Finally, sort the 'C' values within groups of 'A' using the sort=False option to preserve the A sort order from step 1:

In [4]: f = lambda x: x.sort('C', ascending=False)

In [5]: sort2 = sort1.groupby('A', sort=False).apply(f)

In [6]: sort2
Out[6]:
         A         B      C
A
baz 5  baz -2.301539   True
    2  baz -0.528172  False
bar 1  bar -0.611756   True
    4  bar  0.865408  False
foo 3  foo -1.072969   True
    0  foo  1.624345  False

Clean up the df index by using reset_index with drop=True:

In [7]: sort2.reset_index(0, drop=True)
Out[7]:
     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

Sorting std::map using value

U can consider using boost::bimap that might gave you a feeling that map is sorted by key and by values simultaneously (this is not what really happens, though)

jQuery: click function exclude children.

Here is an example. Green square is parent and yellow square is child element.

Hope that this helps.

_x000D_
_x000D_
var childElementClicked;_x000D_
_x000D_
$("#parentElement").click(function(){_x000D_
_x000D_
  $("#childElement").click(function(){_x000D_
     childElementClicked = true;_x000D_
  });_x000D_
_x000D_
  if( childElementClicked != true ) {_x000D_
_x000D_
   // It is clicked on parent but not on child._x000D_
      // Now do some action that you want._x000D_
      alert('Clicked on parent');_x000D_
   _x000D_
  }else{_x000D_
      alert('Clicked on child');_x000D_
    }_x000D_
    _x000D_
    childElementClicked = false;_x000D_
 _x000D_
});
_x000D_
#parentElement{_x000D_
width:200px;_x000D_
height:200px;_x000D_
background-color:green;_x000D_
position:relative;_x000D_
}_x000D_
_x000D_
#childElement{_x000D_
margin-top:50px;_x000D_
margin-left:50px;_x000D_
width:100px;_x000D_
height:100px;_x000D_
background-color:yellow;_x000D_
position:absolute;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<div id="parentElement">_x000D_
  <div id="childElement">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

VB.NET - Click Submit Button on Webbrowser page

This seems to work easily.


Public Function LoginAsTech(ByVal UserID As String, ByVal Pass As String) As Boolean
        Dim MyDoc As New mshtml.HTMLDocument
        Dim DocElements As mshtml.IHTMLElementCollection = Nothing
        Dim LoginForm As mshtml.HTMLFormElement = Nothing

        ASPComplete = 0
        WB.Navigate(VitecLoginURI)
        BrowserLoop()

        MyDoc = WB.Document.DomDocument
        DocElements = MyDoc.getElementsByTagName("input")
        For Each i As mshtml.IHTMLElement In DocElements

            Select Case i.name
                Case "seLogin$UserName"
                    i.value = UserID
                Case "seLogin$Password"
                    i.value = Pass
                Case Else
                    Exit Select
            End Select

            frmServiceCalls.txtOut.Text &= i.name & " : " & i.value & " : " & i.type & vbCrLf
        Next i

        'Old Method for Clicking submit
        'WB.Document.Forms("form1").InvokeMember("submit")


        'Better Method to click submit
        LoginForm = MyDoc.forms.item("form1")
        LoginForm.item("seLogin$LoginButton").click()
        ASPComplete = 0
        BrowserLoop()



        MyDoc= WB.Document.DomDocument
        DocElements = MyDoc.getElementsByTagName("input")
        For Each j As mshtml.IHTMLElement In DocElements
            frmServiceCalls.txtOut.Text &= j.name & " : " & j.value & " : " & j.type & vbCrLf

        Next j

        frmServiceCalls.txtOut.Text &= vbCrLf & vbCrLf & WB.Url.AbsoluteUri & vbCrLf
        Return 1
End Function

Fastest way to serialize and deserialize .NET objects

Protobuf is very very fast.

See http://code.google.com/p/protobuf-net/wiki/Performance for in depth information concerning the performance of this system, and an implementation.

Oracle find a constraint

select * from all_constraints
where owner = '<NAME>'
and constraint_name = 'SYS_C00381400'
/

Like all data dictionary views, this a USER_CONSTRAINTS view if you just want to check your current schema and a DBA_CONSTRAINTS view for administration users.

The construction of the constraint name indicates a system generated constraint name. For instance, if we specify NOT NULL in a table declaration. Or indeed a primary or unique key. For example:

SQL> create table t23 (id number not null primary key)
  2  /

Table created.

SQL> select constraint_name, constraint_type
  2  from user_constraints
  3  where table_name = 'T23'
  4  /

CONSTRAINT_NAME                C
------------------------------ -
SYS_C00935190                  C
SYS_C00935191                  P

SQL>

'C' for check, 'P' for primary.

Generally it's a good idea to give relational constraints an explicit name. For instance, if the database creates an index for the primary key (which it will do if that column is not already indexed) it will use the constraint name oo name the index. You don't want a database full of indexes named like SYS_C00935191.

To be honest most people don't bother naming NOT NULL constraints.

Python error: AttributeError: 'module' object has no attribute

My solution is put those imports in __init__.py of lib:

in file: __init__.py
import mod1

Then,

import lib
lib.mod1

would work fine.

String to date in Oracle with milliseconds

Oracle stores only the fractions up to second in a DATE field.

Use TIMESTAMP instead:

SELECT  TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9')
FROM    dual

, possibly casting it to a DATE then:

SELECT  CAST(TO_TIMESTAMP('2004-09-30 23:53:48,140000000', 'YYYY-MM-DD HH24:MI:SS,FF9') AS DATE)
FROM    dual

How to sort an array of ints using a custom comparator?

If you can't change the type of your input array the following will work:

final int[] data = new int[] { 5, 4, 2, 1, 3 };
final Integer[] sorted = ArrayUtils.toObject(data);
Arrays.sort(sorted, new Comparator<Integer>() {
    public int compare(Integer o1, Integer o2) {
        // Intentional: Reverse order for this demo
        return o2.compareTo(o1);
    }
});
System.arraycopy(ArrayUtils.toPrimitive(sorted), 0, data, 0, sorted.length);

This uses ArrayUtils from the commons-lang project to easily convert between int[] and Integer[], creates a copy of the array, does the sort, and then copies the sorted data over the original.

<div> cannot appear as a descendant of <p>

I got this warning by using Material UI components, then I test the component="div" as prop to the below code and everything became correct:

import Grid from '@material-ui/core/Grid';
import Typography from '@material-ui/core/Typography';

<Typography component="span">
  <Grid component="span">
    Lorem Ipsum
  </Grid>
</Typography>

Actually, this warning happens because in the Material UI the default HTML tag of Grid component is div tag and the default Typography HTML tag is p tag, So now the warning happens,

Warning: validateDOMnesting(...): <div> cannot appear as a descendant of <p>

jQuery or Javascript - how to disable window scroll without overflow:hidden;

You can use jquery-disablescroll to solve the problem:

  • Disable scrolling: $window.disablescroll();
  • Enable scrolling again: $window.disablescroll("undo");

Supports handleWheel, handleScrollbar, handleKeys and scrollEventKeys.

Where does Jenkins store configuration files for the jobs it runs?

The best approach would be to keep your job configurations in a Jenkinsfile that live in source control.

Google Maps API v3 adding an InfoWindow to each marker

You can use this in event:

google.maps.event.addListener(marker, 'click', function() {  
    // this = marker
    var marker_map = this.getMap();
    this.info.open(marker_map);
    // this.info.open(marker_map, this);
    // Note: If you call open() without passing a marker, the InfoWindow will use the position specified upon construction through the InfoWindowOptions object literal.
});

how to get login option for phpmyadmin in xampp

Step 1:

Locate phpMyAdmin installation path.

Step 2:

Open phpMyAdmin/config.inc.php in your favourite text editor. Copy config.sample.inc.php to config.inc.php if it's missing.

Step 3:

Search for $cfg['Servers'][$i]['auth_type'] = 'config';

Replace it with $cfg['Servers'][$i]['auth_type'] = 'cookie';

How do you enable mod_rewrite on any OS?

In my case, issue was occured even after all these configurations have done (@Pekka has mentioned changes in httpd.conf & .htaccess files). It was resolved only after I add

<Directory "project/path">
  Order allow,deny
  Allow from all
  AllowOverride All
</Directory>

to virtual host configuration in vhost file

Edit on 29/09/2017 (For Apache 2.4 <) Refer this answer

<VirtualHost dropbox.local:80>
DocumentRoot "E:/Documenten/Dropbox/Dropbox/dummy-htdocs"
ServerName dropbox.local
ErrorLog "logs/dropbox.local-error.log"
CustomLog "logs/dropbox.local-access.log" combined
<Directory "E:/Documenten/Dropbox/Dropbox/dummy-htdocs">
    # AllowOverride All      # Deprecated
    # Order Allow,Deny       # Deprecated
    # Allow from all         # Deprecated

    # --New way of doing it
    Require all granted    
</Directory>

jQuery UI Tabs - How to Get Currently Selected Tab Index

Another way to get the selected tab index is:

var index = jQuery('#tabs').data('tabs').options.selected;

How do I load the contents of a text file into a javascript variable?

XMLHttpRequest, i.e. AJAX, without the XML.

The precise manner you do this is dependent on what JavaScript framework you're using, but if we disregard interoperability issues, your code will look something like:

var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = function() {
  alert(client.responseText);
}
client.send();

Normally speaking, though, XMLHttpRequest isn't available on all platforms, so some fudgery is done. Once again, your best bet is to use an AJAX framework like jQuery.

One extra consideration: this will only work as long as foo.txt is on the same domain. If it's on a different domain, same-origin security policies will prevent you from reading the result.

Which keycode for escape key with jQuery

Try with the keyup event:

$(document).keyup(function(e) {
  if (e.keyCode === 13) $('.save').click();     // enter
  if (e.keyCode === 27) $('.cancel').click();   // esc
});

Regex select all text between tags

In Javascript (among others), this is simple. It covers attributes and multiple lines:

/<pre[^>]*>([\s\S]*?)<\/pre>/

Case insensitive std::string.find()

Since you're doing substring searches (std::string) and not element (character) searches, there's unfortunately no existing solution I'm aware of that's immediately accessible in the standard library to do this.

Nevertheless, it's easy enough to do: simply convert both strings to upper case (or both to lower case - I chose upper in this example).

std::string upper_string(const std::string& str)
{
    string upper;
    transform(str.begin(), str.end(), std::back_inserter(upper), toupper);
    return upper;
}

std::string::size_type find_str_ci(const std::string& str, const std::string& substr)
{
    return upper(str).find(upper(substr) );
}

This is not a fast solution (bordering into pessimization territory) but it's the only one I know of off-hand. It's also not that hard to implement your own case-insensitive substring finder if you are worried about efficiency.

Additionally, I need to support std::wstring/wchar_t. Any ideas?

tolower/toupper in locale will work on wide-strings as well, so the solution above should be just as applicable (simple change std::string to std::wstring).

[Edit] An alternative, as pointed out, is to adapt your own case-insensitive string type from basic_string by specifying your own character traits. This works if you can accept all string searches, comparisons, etc. to be case-insensitive for a given string type.

JavaScript console.log causes error: "Synchronous XMLHttpRequest on the main thread is deprecated..."

I have been looking at the answers all impressive. I think He should provide the code that is giving him a problem. Given the example below, If you have a script to link to jquery in page.php then you get that notice.

$().ready(function () {
    $.ajax({url: "page.php",
        type: 'GET',
        success: function (result) {
        $("#page").html(result);
   }});
 });

Android get Current UTC time

System.currentTimeMillis() does give you the number of milliseconds since January 1, 1970 00:00:00 UTC. The reason you see local times might be because you convert a Date instance to a string before using it. You can use DateFormats to convert Dates to Strings in any timezone:

DateFormat df = DateFormat.getTimeInstance();
df.setTimeZone(TimeZone.getTimeZone("gmt"));
String gmtTime = df.format(new Date());

Also see this related question.

How do I test if a variable does not equal either of two values?

This can be done with a switch statement as well. The order of the conditional is reversed but this really doesn't make a difference (and it's slightly simpler anyways).

switch(test) {
    case A:
    case B:
        do other stuff;
        break;
    default:
        do stuff;
}

How to programmatically set the layout_align_parent_right attribute of a Button in Relative Layout?

For adding a RelativeLayout attribute whose value is true or false use 0 for false and RelativeLayout.TRUE for true:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) button.getLayoutParams()
params.addRule(RelativeLayout.ALIGN_PARENT_RIGHT, RelativeLayout.TRUE)

It doesn't matter whether or not the attribute was already added, you still use addRule(verb, subject) to enable/disable it. However, post-API 17 you can use removeRule(verb) which is just a shortcut for addRule(verb, 0).

Python: 'ModuleNotFoundError' when trying to import module from imported package

For me when I created a file and saved it as python file, I was getting this error during importing. I had to create a filename with the type ".py" , like filename.py and then save it as a python file. post trying to import the file worked for me.

How to map a composite key with JPA and Hibernate?

The primary key class must define equals and hashCode methods

  1. When implementing equals you should use instanceof to allow comparing with subclasses. If Hibernate lazy loads a one to one or many to one relation, you will have a proxy for the class instead of the plain class. A proxy is a subclass. Comparing the class names would fail.
    More technically: You should follow the Liskows Substitution Principle and ignore symmetricity.
  2. The next pitfall is using something like name.equals(that.name) instead of name.equals(that.getName()). The first will fail, if that is a proxy.

http://www.laliluna.de/jpa-hibernate-guide/ch06s06.html

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

Swift 5.1:

let storyboard = UIStoryboard.init(name: "Main", bundle: Bundle.main)
let mainViewController = storyboard.instantiateViewController(withIdentifier: "ID")
let appDeleg = UIApplication.shared.delegate as! AppDelegate
let root = appDeleg.window?.rootViewController as! UINavigationController
root.pushViewController(mainViewController, animated: true)

how to set ulimit / file descriptor on docker container the image tag is phusion/baseimage-docker

Here is what I did.

set ulimit -n 32000 in the file /etc/init.d/docker

and restart the docker service

docker run -ti node:latest /bin/bash

run this command to verify

user@4d04d06d5022:/# ulimit -a

should see this in the result

open files (-n) 32000

[user@ip ec2-user]# docker run -ti node /bin/bash
user@4d04d06d5022:/# ulimit -a
core file size          (blocks, -c) 0
data seg size           (kbytes, -d) unlimited
scheduling priority             (-e) 0
file size               (blocks, -f) unlimited
pending signals                 (-i) 58729
max locked memory       (kbytes, -l) 64
max memory size         (kbytes, -m) unlimited
open files                      (-n) 32000
pipe size            (512 bytes, -p) 8
POSIX message queues     (bytes, -q) 819200
real-time priority              (-r) 0
stack size              (kbytes, -s) 10240
cpu time               (seconds, -t) unlimited
max user processes              (-u) 58729
virtual memory          (kbytes, -v) unlimited
file locks                      (-x) unlimited

How to enable PHP's openssl extension to install Composer?

I solved my problem a different way. The problem is that wamp's GUI was misleading: it claimed that I had php_openssl enabled.. and if I clicked on php.ini on the same GUI.. it actually showed that extension=php_openssl.dll was uncommented..

I'm not sure if i'm using the same installer version of composer of the OP, but it actually asks you at the beginning to specify the php.exe that you like to apply composer on (which basically ensures that no one tries to apply composer to the wrong php executable as what happened with the OP)..

The way I solved this was by going myself into the installation of php within the wamp package: C:\wamp\bin\php\php5.4.12 and looking php.in there.. when I opened it I was shocked that the line extension=php_openssl.dll was actually commented! I uncommented it and it worked just fine.

enter image description here

Aesthetics must either be length one, or the same length as the dataProblems

Similar to @joran's answer. Reshape the df so that the prices for each product are in different columns:

xx <- reshape(df, idvar=c("skew","version","color"),
              v.names="price", timevar="product", direction="wide")

xx will have columns price.p1, ... price.p4, so:

ggp <- ggplot(xx,aes(x=price.p1, y=price.p3, color=factor(skew))) +
       geom_point(shape=19, size=5)
ggp + facet_grid(color~version)

gives the result from your image.

How To Save Canvas As An Image With canvas.toDataURL()?

You cannot use the methods previously mentioned to download an image when running in Cordova. You will need to use the Cordova File Plugin. This will allow you to pick where to save it and leverage different persistence settings. Details here: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-file/

Alternatively, you can convert the image to base64 then store the string in localStorage but this will fill your quota pretty quickly if you have many images or high-res.

How to specify the port an ASP.NET Core application is hosted on?

Above .net core 2.2 the method Main support args with WebHost.CreateDefaultBuilder(args)

public class Program
{
    public static void Main(string[] args)
    {
        CreateWebHostBuilder(args).Build().Run();
    }

    public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>();
}

You can build your project and go to bin run command like this

dotnet <yours>.dll --urls=http://localhost:5001

or with multi-urls

dotnet <yours>.dll --urls="http://localhost:5001,https://localhost:5002"

Add User to Role ASP.NET Identity

I found good answer here Adding Role dynamically in new VS 2013 Identity UserManager

But in case to provide an example so you can check it I am gonna share some default code.

First make sure you have Roles inserted.

enter image description here

And second test it on user register method.

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName  };

        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            var currentUser = UserManager.FindByName(user.UserName); 

            var roleresult = UserManager.AddToRole(currentUser.Id, "Superusers");

            await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

And finally you have to get "Superusers" from the Roles Dropdown List somehow.

Creating a JSON dynamically with each input value using jquery

Like this:

function createJSON() {
    jsonObj = [];
    $("input[class=email]").each(function() {

        var id = $(this).attr("title");
        var email = $(this).val();

        item = {}
        item ["title"] = id;
        item ["email"] = email;

        jsonObj.push(item);
    });

    console.log(jsonObj);
}

Explanation

You are looking for an array of objects. So, you create a blank array. Create an object for each input by using 'title' and 'email' as keys. Then you add each of the objects to the array.

If you need a string, then do

jsonString = JSON.stringify(jsonObj);

Sample Output

[{"title":"QA","email":"a@b"},{"title":"PROD","email":"b@c"},{"title":"DEV","email":"c@d"}] 

Eclipse plugin for generating a class diagram

Try Amateras. It is a very good plugin for generating UML diagrams including class diagram.

How to process each output line in a loop?

You can do the following while read loop, that will be fed by the result of the grep command using the so called process substitution:

while IFS= read -r result
do
    #whatever with value $result
done < <(grep "xyz" abc.txt)

This way, you don't have to store the result in a variable, but directly "inject" its output to the loop.


Note the usage of IFS= and read -r according to the recommendations in BashFAQ/001: How can I read a file (data stream, variable) line-by-line (and/or field-by-field)?:

The -r option to read prevents backslash interpretation (usually used as a backslash newline pair, to continue over multiple lines or to escape the delimiters). Without this option, any unescaped backslashes in the input will be discarded. You should almost always use the -r option with read.

In the scenario above IFS= prevents trimming of leading and trailing whitespace. Remove it if you want this effect.

Regarding the process substitution, it is explained in the bash hackers page:

Process substitution is a form of redirection where the input or output of a process (some sequence of commands) appear as a temporary file.

Calling stored procedure from another stored procedure SQL Server

First of all, if table2's idProduct is an identity, you cannot insert it explicitly until you set IDENTITY_INSERT on that table

SET IDENTITY_INSERT table2 ON;

before the insert.

So one of two, you modify your second stored and call it with only the parameters productName and productDescription and then get the new ID

EXEC test2 'productName', 'productDescription'
SET @newID = SCOPE_IDENTIY()

or you already have the ID of the product and you don't need to call SCOPE_IDENTITY() and can make the insert on table1 with that ID

How to clear mysql screen console in windows?

I used the command line client prompt and to clear the screen I typed:-

system cls

Difference between left join and right join in SQL Server

Table from which you are taking data is 'LEFT'.
Table you are joining is 'RIGHT'.
LEFT JOIN: Take all items from left table AND (only) matching items from right table.
RIGHT JOIN: Take all items from right table AND (only) matching items from left table.
So:

Select * from Table1 left join Table2 on Table1.id = Table2.id  

gives:

Id     Name       
-------------  
1      A          
2      B      

but:

Select * from Table1 right join Table2 on Table1.id = Table2.id

gives:

Id     Name       
-------------  
1      A          
2      B   
3      C  

you were right joining table with less rows on table with more rows
AND
again, left joining table with less rows on table with more rows
Try:

 If Table1.Rows.Count > Table2.Rows.Count Then  
    ' Left Join  
 Else  
    ' Right Join  
 End If  

Debugging in Maven?

I thought I would expand on these answers for OSX and Linux folks (not that they need it):

I prefer to use mvnDebug too. But after OSX maverick destroyed my Java dev environment, I am starting from scratch and stubbled upon this post, and thought I would add to it.

$ mvnDebug vertx:runMod
-bash: mvnDebug: command not found

DOH! I have not set it up on this box after the new SSD drive and/or the reset of everything Java when I installed Maverick.

I use a package manager for OSX and Linux so I have no idea where mvn really lives. (I know for brief periods of time.. thanks brew.. I like that I don't know this.)

Let's see:

$ which mvn
/usr/local/bin/mvn

There you are... you little b@stard.

Now where did you get installed to:

$ ls -l /usr/local/bin/mvn

lrwxr-xr-x  1 root  wheel  39 Oct 31 13:00 /
                  /usr/local/bin/mvn -> /usr/local/Cellar/maven30/3.0.5/bin/mvn

Aha! So you got installed in /usr/local/Cellar/maven30/3.0.5/bin/mvn. You cheeky little build tool. No doubt by homebrew...

Do you have your little buddy mvnDebug with you?

$ ls /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug 
/usr/local/Cellar/maven30/3.0.5/bin/mvnDebug

Good. Good. Very good. All going as planned.

Now move that little b@stard where I can remember him more easily.

$ ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug
  ln: /usr/local/bin/mvnDebug: Permission denied

Darn you computer... You will submit to my will. Do you know who I am? I am SUDO! BOW!

$ sudo ln -s /usr/local/Cellar/maven30/3.0.5/bin/mvnDebug /usr/local/bin/mvnDebug

Now I can use it from Eclipse (but why would I do that when I have IntelliJ!!!!)

$ mvnDebug vertx:runMod
Preparing to Execute Maven in Debug Mode
Listening for transport dt_socket at address: 8000

Internally mvnDebug uses this:

MAVEN_DEBUG_OPTS="-Xdebug -Xnoagent -Djava.compiler=NONE  \
-Xrunjdwp:transport=dt_socket,server=y,suspend=y,address=8000"

So you could modify it (I usually debug on port 9090).

This blog explains how to setup Eclipse remote debugging (shudder)

http://javarevisited.blogspot.com/2011/02/how-to-setup-remote-debugging-in.html

Ditto Netbeans

https://blogs.oracle.com/atishay/entry/use_netbeans_to_debug_a

Ditto IntelliJ http://www.jetbrains.com/idea/webhelp/run-debug-configuration-remote.html

Here is some good docs on the -Xdebug command in general.

http://docs.oracle.com/cd/E13150_01/jrockit_jvm/jrockit/jrdocs/refman/optionX.html

"-Xdebug enables debugging capabilities in the JVM which are used by the Java Virtual Machine Tools Interface (JVMTI). JVMTI is a low-level debugging interface used by debuggers and profiling tools. With it, you can inspect the state and control the execution of applications running in the JVM."

"The subset of JVMTI that is most typically used by profilers is always available. However, the functionality used by debuggers to be able to step through the code and set breakpoints has some overhead associated with it and is not always available. To enable this functionality you must use the -Xdebug option."

-Xrunjdwp:transport=dt_socket,server=y,suspend=n myApp

Check out the docs on -Xrunjdwp too. You can enable it only when a certain exception is thrown for example. You can start it up suspended or running. Anyway.. I digress.

How can I change my default database in SQL Server without using MS SQL Server Management Studio?

If you use windows authentication, and you don't know a password to login as a user via username and password, you can do this: on the login-screen on SSMS click options at the bottom right, then go to the connection properties tab. Then you can type in manually the name of another database you have access to, over where it says , which will let you connect. Then follow the other advice for changing your default database

https://gyazo.com/c3d04c600311c08cb685bb668b569a67

ant build.xml file doesn't exist

Please install at ubuntu openjdk-7-jdk

sudo apt-get install openjdk-7-jdk

on Windows try find find openjdk

How to convert a String into an array of Strings containing one character each

You can use String.split(String regex):

String input = "aabbab";
String[] parts = input.split("(?!^)");

C# Lambda expressions: Why should I use them?

You can also find the use of lambda expressions in writing generic codes to act on your methods.

For example: Generic function to calculate the time taken by a method call. (i.e. Action in here)

public static long Measure(Action action)
{
    Stopwatch sw = new Stopwatch();
    sw.Start();
    action();
    sw.Stop();
    return sw.ElapsedMilliseconds;
}

And you can call the above method using the lambda expression as follows,

var timeTaken = Measure(() => yourMethod(param));

Expression allows you to get return value from your method and out param as well

var timeTaken = Measure(() => returnValue = yourMethod(param, out outParam));

Deserialize a json string to an object in python

While Alex's answer points us to a good technique, the implementation that he gave runs into a problem when we have nested objects.

class more_info
    string status

class payload
    string action
    string method
    string data
    class more_info

with the below code:

def as_more_info(dct):
    return MoreInfo(dct['status'])

def as_payload(dct):
    return Payload(dct['action'], dct['method'], dct['data'], as_more_info(dct['more_info']))

payload = json.loads(message, object_hook = as_payload)

payload.more_info will also be treated as an instance of payload which will lead to parsing errors.

From the official docs:

object_hook is an optional function that will be called with the result of any object literal decoded (a dict). The return value of object_hook will be used instead of the dict.

Hence, I would prefer to propose the following solution instead:

class MoreInfo(object):
    def __init__(self, status):
        self.status = status

    @staticmethod
    def fromJson(mapping):
        if mapping is None:
            return None

        return MoreInfo(
            mapping.get('status')
        )

class Payload(object):
    def __init__(self, action, method, data, more_info):
        self.action = action
        self.method = method
        self.data = data
        self.more_info = more_info

    @staticmethod
    def fromJson(mapping):
        if mapping is None:
            return None

        return Payload(
            mapping.get('action'),
            mapping.get('method'),
            mapping.get('data'),
            MoreInfo.fromJson(mapping.get('more_info'))
        )

import json
def toJson(obj, **kwargs):
    return json.dumps(obj, default=lambda j: j.__dict__, **kwargs)

def fromJson(msg, cls, **kwargs):
    return cls.fromJson(json.loads(msg, **kwargs))

info = MoreInfo('ok')
payload = Payload('print', 'onData', 'better_solution', info)
pl_json = toJson(payload)
l1 = fromJson(pl_json, Payload)

concatenate char array in C

I have a char array:

char* name = "hello";

No, you have a character pointer to a string literal. In many usages you could add the const modifier, depending on whether you are more interested in what name points to, or the string value, "hello". You shouldn't attempt to modify the literal ("hello"), because bad things can happen.

The major thing to convey is that C does not have a proper (or first-class) string type. "Strings" are typically arrays of chars (characters) with a terminating null ('\0' or decimal 0) character to signify end of a string, or pointers to arrays of characters.

I would suggest reading Character Arrays, section 1.9 in The C Programming Language (page 28 second edition). I strongly recommend reading this small book ( <300 pages), in order to learn C.

Further to your question, sections 6 - Arrays and Pointers and section 8 - Characters and Strings of the C FAQ might help. Question 6.5, and 8.4 might be good places to start.

I hope that helps you to understand why your excerpt doesn't work. Others have outlined what changes are needed to make it work. Basically you need an char array (an array of characters) big enough to store the entire string with a terminating (ending) '\0' character. Then you can use the standard C library function strcpy (or better yet strncpy) to copy the "Hello" into it, and then you want to concatenate using the standard C library strcat (or better yet strncat) function. You will want to include the string.h header file to declare the functions declarations.

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

int main( int argc, char *argv[] )
{
    char filename[128];
    char* name = "hello";
    char* extension = ".txt";

    if (sizeof(filename) < strlen(name) + 1 ) { /* +1 is for null character */
        fprintf(stderr, "Name '%s' is too long\n", name);
        return EXIT_FAILURE;
    }
    strncpy(filename, name, sizeof(filename));

    if (sizeof(filename) < (strlen(filename) + strlen(extension) + 1) ) {
        fprintf(stderr, "Final size of filename is too long!\n");
        return EXIT_FAILURE;
    }
    strncat(filename, extension, (sizeof(filename) - strlen(filename)) );
    printf("Filename is %s\n", filename);

    return EXIT_SUCCESS;
}

When to create variables (memory management)

Well, the JVM memory model works something like this: values are stored on one pile of memory stack and objects are stored on another pile of memory called the heap. The garbage collector looks for garbage by looking at a list of objects you've made and seeing which ones aren't pointed at by anything. This is where setting an object to null comes in; all nonprimitive (think of classes) variables are really references that point to the object on the stack, so by setting the reference you have to null the garbage collector can see that there's nothing else pointing at the object and it can decide to garbage collect it. All Java objects are stored on the heap so they can be seen and collected by the garbage collector.

Nonprimitive (ints, chars, doubles, those sort of things) values, however, aren't stored on the heap. They're created and stored temporarily as they're needed and there's not much you can do there, but thankfully the compilers nowadays are really efficient and will avoid needed to store them on the JVM stack unless they absolutely need to.

On a bytecode level, that's basically how it works. The JVM is based on a stack-based machine, with a couple instructions to create allocate objects on the heap as well, and a ton of instructions to manipulate, push and pop values, off the stack. Local variables are stored on the stack, allocated variables on the heap.* These are the heap and the stack I'm referring to above. Here's a pretty good starting point if you want to get into the nitty gritty details.

In the resulting compiled code, there's a bit of leeway in terms of implementing the heap and stack. Allocation's implemented as allocation, there's really not a way around doing so. Thus the virtual machine heap becomes an actual heap, and allocations in the bytecode are allocations in actual memory. But you can get around using a stack to some extent, since instead of storing the values on a stack (and accessing a ton of memory), you can stored them on registers on the CPU which can be up to a hundred times (maybe even a thousand) faster than storing it on memory. But there's cases where this isn't possible (look up register spilling for one example of when this may happen), and using a stack to implement a stack kind of makes a lot of sense.

And quite frankly in your case a few integers probably won't matter. The compiler will probably optimize them out by itself in this case anyways. Optimization should always happen after you get it running and notice it's a tad slower than you'd prefer it to be. Worry about making simple, elegant, working code first then later make it fast (and hopefully) simple, elegant, working code.

Java's actually very nicely made so that you shouldn't have to worry about nulling variables very often. Whenever you stop needing to use something, it will usually incidentally be disappearing from the scope of your program (and thus becoming eligible for garbage collection). So I guess the real lesson here is to use local variables as often as you can.

*There's also a constant pool, a local variable pool, and a couple other things in memory but you have close to no control over the size of those things and I want to keep this fairly simple.

File to import not found or unreadable: compass

If you're like me and came here looking for a way to make sass --watch work with compass, the answer is to use Compass' version of watch, simply:

compass watch

If you're on a Mac and don't yet have the gem installed, you might run into errors when you try to install the Compass gem, due to permission problems that arise on OSX versions later than 10.11. Install ruby with Homebrew to get around this. See this answer for how to do that.

Alternatively you could just use CodeKit, but if you're stubborn like me and want to use Sublime Text and command line, this is the route to go.

Error: Could not create the Java Virtual Machine Mac OSX Mavericks

There can be one more reason for such behavior - you delete current working directory.

For example:

# in terminal #1
cd /home/user/myJavaApp

# in terminal #2
rm -rf /home/user/myJavaApp

# in terminal #1
java -jar myJar.jar

Error: Could not create the Java Virtual Machine.
Error: A fatal exception has occurred. Program will exit.

How can I specify a display?

When you are connecting to another machine over SSH, you can enable X-Forwarding in SSH, so that X windows are forwarded encrypted through the SSH tunnel back to your machine. You can enable X forwarding by appending -X to the ssh command line or setting ForwardX11 yes in your SSH config file.

To check if the X-Forwarding was set up successfully (the server might not allow it), just try if echo $DISPLAY outputs something like localhost:10.0.

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

python location on mac osx

Run this in your interactive terminal

import os
os.path

It will give you the folder where python is installed

The opposite of Intersect()

/// <summary>
/// Given two list, compare and extract differences
/// http://stackoverflow.com/questions/5620266/the-opposite-of-intersect
/// </summary>
public class CompareList
{
    /// <summary>
    /// Returns list of items that are in initial but not in final list.
    /// </summary>
    /// <param name="listA"></param>
    /// <param name="listB"></param>
    /// <returns></returns>
    public static IEnumerable<string> NonIntersect(
        List<string> initial, List<string> final)
    {
        //subtracts the content of initial from final
        //assumes that final.length < initial.length
        return initial.Except(final);
    }

    /// <summary>
    /// Returns the symmetric difference between the two list.
    /// http://en.wikipedia.org/wiki/Symmetric_difference
    /// </summary>
    /// <param name="initial"></param>
    /// <param name="final"></param>
    /// <returns></returns>
    public static IEnumerable<string> SymmetricDifference(
        List<string> initial, List<string> final)
    {
        IEnumerable<string> setA = NonIntersect(final, initial);
        IEnumerable<string> setB = NonIntersect(initial, final);
        // sum and return the two set.
        return setA.Concat(setB);
    }
}

Perform curl request in javascript?

You can use JavaScripts Fetch API (available in your browser) to make network requests.

If using node, you will need to install the node-fetch package.

const url = "https://api.wit.ai/message?v=20140826&q=";

const options = {
  headers: {
    Authorization: "Bearer 6Q************"
  }
};

fetch(url, options)
  .then( res => res.json() )
  .then( data => console.log(data) );

Show Error on the tip of the Edit Text Android

You can show error as PopUp of EditText

if (editText.getText().toString().trim().equalsIgnoreCase("")) {
      editText.setError("This field can not be blank");
}

and that will be look a like as follows

enter image description here

firstName.addTextChangedListener(new TextWatcher()  {

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void afterTextChanged(Editable s)  {
        if (firstName.getText().toString().length <= 0) {
            firstName.setError("Enter FirstName");
        } else {
            firstName.setError(null);
        }
    }
 });

Shell script to set environment variables

Please show us more parts of the script and tell us what commands you had to individually execute and want to simply.

Meanwhile you have to use double quotes not single quote to expand variables:

export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"

Semicolons at the end of a single command are also unnecessary.

So far:

#!/bin/sh
echo "Perform Operation in su mode"
export ARCH=arm
echo "Export ARCH=arm Executed"
export PATH="/home/linux/Practise/linux-devkit/bin/:$PATH"
echo "Export path done"
export CROSS_COMPILE='/home/linux/Practise/linux-devkit/bin/arm-arago-linux-gnueabi-' ## What's next to -?
echo "Export CROSS_COMPILE done"
# continue your compilation commands here
...

For su you can run it with:

su -c 'sh /path/to/script.sh'

Note: The OP was not explicitly asking for steps on how to create export variables in an interactive shell using a shell script. He only asked his script to be assessed at most. He didn't mention details on how his script would be used. It could have been by using . or source from the interactive shell. It could have been a standalone scipt, or it could have been source'd from another script. Environment variables are not specific to interactive shells. This answer solved his problem.

Writing an mp4 video using python opencv

Anyone who's looking for most convenient and robust way of writing MP4 files with OpenCV or FFmpeg, can see my state-of-the-art VidGear Video-Processing Python library's WriteGear API that works with both OpenCV backend and FFmpeg backend and even supports GPU encoders. Here's an example to encode with H264 encoder in WriteGear with FFmpeg backend:

# import required libraries
from vidgear.gears import WriteGear
import cv2

# define suitable (Codec,CRF,preset) FFmpeg parameters for writer
output_params = {"-vcodec":"libx264", "-crf": 0, "-preset": "fast"}

# Open suitable video stream, such as webcam on first index(i.e. 0)
stream = cv2.VideoCapture(0) 

# Define writer with defined parameters and suitable output filename for e.g. `Output.mp4`
writer = WriteGear(output_filename = 'Output.mp4', logging = True, **output_params)

# loop over
while True:

    # read frames from stream
    (grabbed, frame) = stream.read()

    # check for frame if not grabbed
    if not grabbed:
      break

    # {do something with the frame here}
    # lets convert frame to gray for this example
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

    # write gray frame to writer
    writer.write(gray)

    # Show output window
    cv2.imshow("Output Gray Frame", gray)

    # check for 'q' key if pressed
    key = cv2.waitKey(1) & 0xFF
    if key == ord("q"):
        break

# close output window
cv2.destroyAllWindows()

# safely close video stream
stream.release()

# safely close writer
writer.close() 

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

getResourceAsStream() vs FileInputStream

I am here by separating both the usages by marking them as File Read(java.io) and Resource Read(ClassLoader.getResourceAsStream()).

File Read - 1. Works on local file system. 2. Tries to locate the file requested from current JVM launched directory as root 3. Ideally good when using files for processing in a pre-determined location like,/dev/files or C:\Data.

Resource Read - 1. Works on class path 2. Tries to locate the file/resource in current or parent classloader classpath. 3. Ideally good when trying to load files from packaged files like war or jar.

Create comma separated strings C#?

If you're using .Net 4 you can use the overload for string.Join that takes an IEnumerable if you have them in a List, too:

string.Join(", ", strings);

jQuery Ajax calls and the Html.AntiForgeryToken()

Slight improvement to 360Airwalk solution. This imbeds the Anti Forgery Token within the javascript function, so @Html.AntiForgeryToken() no longer needs to be included on every view.

$(document).ready(function () {
    var securityToken = $('@Html.AntiForgeryToken()').attr('value');
    $('body').bind('ajaxSend', function (elm, xhr, s) {
        if (s.type == 'POST' && typeof securityToken != 'undefined') {
            if (s.data.length > 0) {
                s.data += "&__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
            else {
                s.data = "__RequestVerificationToken=" + encodeURIComponent(securityToken);
            }
        }
    });
});

Quantile-Quantile Plot using SciPy

Using qqplot of statsmodels.api is another option:

Very basic example:

import numpy as np
import statsmodels.api as sm
import pylab

test = np.random.normal(0,1, 1000)

sm.qqplot(test, line='45')
pylab.show()

Result:

enter image description here

Documentation and more example are here

shared global variables in C

There is a cleaner way with just one header file so it is simpler to maintain. In the header with the global variables prefix each declaration with a keyword (I use common) then in just one source file include it like this

#define common
#include "globals.h"
#undef common

and any other source files like this

#define common extern
#include "globals.h"
#undef common

Just make sure you don't initialise any of the variables in the globals.h file or the linker will still complain as an initialised variable is not treated as external even with the extern keyword. The global.h file looks similar to this

#pragma once
common int globala;
common int globalb;
etc.

seems to work for any type of declaration. Don't use the common keyword on #define of course.

SQL Sum Multiple rows into one

I tried this, but the query won't run telling me my field is invalid in the select statement because it is not contained in either an aggregate function or the GROUP BY clause. It's forcing me to keep it there. Is there a way around this?

You need to do a self-join. You can't both aggregate and preserve non-aggregated data in the same subquery. E.g.

select q2.AccountNumber, q2.Bill, q2.BillDate, q1.BillSum
from
(
SELECT AccountNumber, SUM(Bill) as BillSum
FROM Table1
GROUP BY AccountNumber
) q1,
(
select AccountNumber, Bill, BillDate
from table1
) q2
where q1.AccountNumber = q2.AccountNumber

How to do a GitHub pull request

(In addition of the official "GitHub Help 'Using pull requests' page",
see also "Forking vs. Branching in GitHub", "What is the difference between origin and upstream in GitHub")

Couple tips on pull-requests:

Assuming that you have first forked a repo, here is what you should do in that fork that you own:

  • create a branch: isolate your modifications in a branch. Don't create a pull request from master, where you could be tempted to accumulate and mix several modifications at once.
  • rebase that branch: even if you already did a pull request from that branch, rebasing it on top of origin/master (making sure your patch is still working) will update the pull request automagically (no need to click on anything)
  • update that branch: if your pull request is rejected, you simply can add new commits, and/or redo your history completely: it will activate your existing pull request again.
  • "focus" that branch: i.e., make its topic "tight", don't modify thousands of class and the all app, only add or fix a well-defined feature, keeping the changes small.
  • delete that branch: once accepted, you can safely delete that branch on your fork (and git remote prune origin). The GitHub GUI will propose for you to delete your branch in your pull-request page.

Note: to write the Pull-Request itself, see "How to write the perfect pull request" (January 2015, GitHub)


March 2016: New PR merge button option: see "Github squash commits from web interface on pull request after review comments?".

squash

The maintainer of the repo can chose to merge --squash those PR commits.


After a Pull Request

Regarding the last point, since April, 10th 2013, "Redesigned merge button", the branch is deleted for you:

new merge button

Deleting branches after you merge has also been simplified.
Instead of confirming the delete with an extra step, we immediately remove the branch when you delete it and provide a convenient link to restore the branch in the event you need it again.

That confirms the best practice of deleting the branch after merging a pull request.


pull-request vs. request-pull


e-notes for "reposotory" (sic)

<humour>

That (pull request) isn't even defined properly by GitHub!

Fortunately, a true business news organization would know, and there is an e-note in order to replace pull-replace by 'e-note':

https://pbs.twimg.com/media/BT_5S-TCcAA-EF2.jpg:large

So if your reposotory needs a e-note... ask Fox Business. They are in the know.

</humour>

What does question mark and dot operator ?. mean in C# 6.0?

This is relatively new to C# which makes it easy for us to call the functions with respect to the null or non-null values in method chaining.

old way to achieve the same thing was:

var functionCaller = this.member;
if (functionCaller!= null)
    functionCaller.someFunction(var someParam);

and now it has been made much easier with just:

member?.someFunction(var someParam);

I strongly recommend this doc page.

Go Back to Previous Page

... By looking at Facebook code ... I found this

Go Back to Previous Page

Run php script as daemon process

I was looking for a simple solution without having to install additional stuff and compatible with common hostings that allow SSH access.

I've ended up with this setup for my chat server:

-rwxr-xr-x  1 crazypoems psacln   309 ene 30 14:01 checkChatServerRunning.sh
-rw-r--r--  1 crazypoems psacln  3018 ene 30 13:12 class.chathandler.php
-rw-r--r--  1 crazypoems psacln    29 ene 30 14:05 cron.log
-rw-r--r--  1 crazypoems psacln  2560 ene 29 08:04 index.php
-rw-r--r--  1 crazypoems psacln  2672 ene 30 13:29 php-socket.php
-rwxr-xr-x  1 crazypoems psacln   310 ene 30 14:04 restartChatServer.sh
-rwxr-xr-x  1 crazypoems psacln   122 ene 30 13:28 startChatServer.sh
-rwxr-xr-x  1 crazypoems psacln   224 ene 30 13:56 stopChatServer.sh

And the scripts:

startChatServer.sh

#!/bin/bash
nohup /opt/plesk/php/5.6/bin/php -q /var/www/vhosts/crazypoems.org/httpdocs/chat/php-socket.php > /dev/null &

stopChatServer.sh

#!/bin/bash
PID=`ps -eaf | grep '/var/www/vhosts/crazypoems.org/httpdocs/chat/php-socket.php' | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
  echo "killing $PID"
  kill -9 $PID
else
  echo "not running"
fi

restartChatServer.sh

#!/bin/bash
PID=`ps -eaf | grep '/var/www/vhosts/crazypoems.org/httpdocs/chat/php-socket.php' | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
  echo "killing $PID"
  kill -9 $PID
else
  echo "not running"
fi
echo "Starting again"
/var/www/vhosts/crazypoems.org/httpdocs/chat/startChatServer.sh

And last but not least, I have put this last script on a cron job, to check if the "chat server is running", and if not, to start it:

Cron job every minute

-bash-4.1$ crontab -l
*       *       *       *       * /var/www/vhosts/crazypoems.org/httpdocs/chat/checkChatServerRunning.sh > /var/www/vhosts/crazypoems.org/httpdocs/chat/cron.log

checkChatServerRunning.sh

#!/bin/bash
PID=`ps -eaf | grep '/var/www/vhosts/crazypoems.org/httpdocs/chat/php-socket.php' | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
  echo "Chat server running on $PID"
else
  echo "Not running, going to start it"
  /var/www/vhosts/crazypoems.org/httpdocs/chat/startChatServer.sh
fi

So with this setup:

  • I manually can control the service with the scripts when needed (eg: maintenance)
  • The cron job will start the server on reboot, or on crash

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

I had to be logged into Ubuntu as root in order to access Mariadb as root. It may have something to do with that "Harden ..." that it prompts you to do when you first install. So:

$ sudo su
[sudo] password for user: yourubunturootpassword
# mysql -r root -p
Enter password: yourmariadbrootpassword

and you're in.

Java compiler level does not match the version of the installed Java project facet

You can change project facet from Project --> Properties --> Project Facet --> Java --> {required JDK version}

What is the difference between Bootstrap .container and .container-fluid classes?

From a display perspective .container gives you more control over the what the users are seeing, and makes it easier to see what the users will see as you only have 4 variations of display (5 in the case of bootstrap 5) because the sizes relate to the same as the grid sizes. e.g. .col-xs, .col-sm, .col, and .col-lg.

What this means, is that when you are doing user testing if you test on a displays with the 4 different sizes you see all the veriations in display.

When using .container-fluid because the witdh is related to the viewport width the display is dynamic, so the varations are much greater and users with very large screens or uncommon screen widths may see results you weren't expecting.

Installing SciPy with pip

For gentoo, it's in the main repository: emerge --ask scipy

Getting the number of filled cells in a column (VBA)

You can also use

Cells.CurrentRegion

to give you a range representing the bounds of your data on the current active sheet

Msdn says on the topic

Returns a Range object that represents the current region. The current region is a range bounded by any combination of blank rows and blank columns. Read-only.

Then you can determine the column count via

Cells.CurrentRegion.Columns.Count

and the row count via

Cells.CurrentRegion.Rows.Count

Online SQL syntax checker conforming to multiple databases

I don't know of any such, and my experience is that it doesn't currently exist. Most are side by side comparisons of two databases. That information requires experts in all the databases encountered, which isn't common. Versions depend too, to know what is supported.

ANSI functions are making strides to ensure syntax is supported across databases, but it's dependent on vendors implementing the spec. And to date, they aren't implementing the entire ANSI spec at a time.

But you can crowd source on sites like this one by asking specific questions and including the databases involved and the versions used.

Can't connect Nexus 4 to adb: unauthorized

I think it has an error when the device tries to display the screen asking for permission, so it does not appear.

This works for me (commands are given in the adb shell):

  1. rm /data/misc/adb/adb_keys;
  2. I sent the public key (adbkey.pub in ~/.android/) from my computer to my device via email;
  3. Invoke stop adbd;
  4. cat adbkey.pub >> /data/misc/adb/adb_keys (authorize myself);
  5. start adbd (restart adb with new keys).

Are duplicate keys allowed in the definition of binary search trees?

Duplicate Keys • What happens if there's more than one data item with the same key? – This presents a slight problem in red-black trees. – It's important that nodes with the same key are distributed on both sides of other nodes with the same key. – That is, if keys arrive in the order 50, 50, 50, • you want the second 50 to go to the right of the first one, and the third 50 to go to the left of the first one. • Otherwise, the tree becomes unbalanced. • This could be handled by some kind of randomizing process in the insertion algorithm. – However, the search process then becomes more complicated if all items with the same key must be found. • It's simpler to outlaw items with the same key. – In this discussion we'll assume duplicates aren't allowed

One can create a linked list for each node of the tree that contains duplicate keys and store data in the list.

How can I append a query parameter to an existing URL?

An update to Adam's answer considering tryp's answer too. Don't have to instantiate a String in the loop.

public static URI appendUri(String uri, Map<String, String> parameters) throws URISyntaxException {
    URI oldUri = new URI(uri);
    StringBuilder queries = new StringBuilder();

    for(Map.Entry<String, String> query: parameters.entrySet()) {
        queries.append( "&" + query.getKey()+"="+query.getValue());
    }

    String newQuery = oldUri.getQuery();
    if (newQuery == null) {
        newQuery = queries.substring(1);
    } else {
        newQuery += queries.toString();
    }

    URI newUri = new URI(oldUri.getScheme(), oldUri.getAuthority(),
            oldUri.getPath(), newQuery, oldUri.getFragment());

    return newUri;
}

Get Android .apk file VersionName or VersionCode WITHOUT installing apk

I can now successfully retrieve the version of an APK file from its binary XML data.

This topic is where I got the key to my answer (I also added my version of Ribo's code): How to parse the AndroidManifest.xml file inside an .apk package

Additionally, here's the XML parsing code I wrote, specifically to fetch the version:

XML Parsing

/**
 * Verifies at Conductor APK path if package version if newer 
 * 
 * @return True if package found is newer, false otherwise
 */
public static boolean checkIsNewVersion(String conductorApkPath) {

    boolean newVersionExists = false;

    // Decompress found APK's Manifest XML
    // Source: https://stackoverflow.com/questions/2097813/how-to-parse-the-androidmanifest-xml-file-inside-an-apk-package/4761689#4761689
    try {

        if ((new File(conductorApkPath).exists())) {

            JarFile jf = new JarFile(conductorApkPath);
            InputStream is = jf.getInputStream(jf.getEntry("AndroidManifest.xml"));
            byte[] xml = new byte[is.available()];
            int br = is.read(xml);

            //Tree tr = TrunkFactory.newTree();
            String xmlResult = SystemPackageTools.decompressXML(xml);
            //prt("XML\n"+tr.list());

            if (!xmlResult.isEmpty()) {

                InputStream in = new ByteArrayInputStream(xmlResult.getBytes());

                // Source: http://developer.android.com/training/basics/network-ops/xml.html
                XmlPullParser parser = Xml.newPullParser();
                parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);

                parser.setInput(in, null);
                parser.nextTag();

                String name = parser.getName();
                if (name.equalsIgnoreCase("Manifest")) {

                    String pakVersion = parser.getAttributeValue(null, "versionName");
                            //NOTE: This is specific to my project. Replace with whatever is relevant on your side to fetch your project's version
                    String curVersion = SharedData.getPlayerVersion();

                    int isNewer = SystemPackageTools.compareVersions(pakVersion, curVersion); 

                    newVersionExists = (isNewer == 1); 
                }

            }
        }

    } catch (Exception ex) {
        android.util.Log.e(TAG, "getIntents, ex: "+ex);
        ex.printStackTrace();
    }

    return newVersionExists;
}

Version Comparison (seen as SystemPackageTools.compareVersions in previous snippet) NOTE: This code is inspired from the following topic: Efficient way to compare version strings in Java

/**
 * Compare 2 version strings and tell if the first is higher, equal or lower
 * Source: https://stackoverflow.com/questions/6701948/efficient-way-to-compare-version-strings-in-java
 * 
 * @param ver1 Reference version
 * @param ver2 Comparison version
 * 
 * @return 1 if ver1 is higher, 0 if equal, -1 if ver1 is lower
 */
public static final int compareVersions(String ver1, String ver2) {

    String[] vals1 = ver1.split("\\.");
    String[] vals2 = ver2.split("\\.");
    int i=0;
    while(i<vals1.length&&i<vals2.length&&vals1[i].equals(vals2[i])) {
      i++;
    }

    if (i<vals1.length&&i<vals2.length) {
        int diff = Integer.valueOf(vals1[i]).compareTo(Integer.valueOf(vals2[i]));
        return diff<0?-1:diff==0?0:1;
    }

    return vals1.length<vals2.length?-1:vals1.length==vals2.length?0:1;
}

I hope this helps.

PHP substring extraction. Get the string before the first '/' or the whole string

I think this should work?

substr($mystring, 0, (($pos = (strpos($mystring, '/') !== false)) ? $pos : strlen($mystring)));

How to save .xlsx data to file as a blob

I had the same problem as you. It turns out you need to convert the Excel data file to an ArrayBuffer.

var blob = new Blob([s2ab(atob(data))], {
    type: ''
});

href = URL.createObjectURL(blob);

The s2ab (string to array buffer) method (which I got from https://github.com/SheetJS/js-xlsx/blob/master/README.md) is:

function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}

jQuery input button click event listener

More on gdoron's answer, it can also be done this way:

$(window).on("click", "#filter", function() {
    alert('clicked!');
});

without the need to place them all into $(function(){...})

How to add conditional attribute in Angular 2?

in angular-2 attribute syntax is

<div [attr.role]="myAriaRole">

Binds attribute role to the result of expression myAriaRole.

so can use like

[attr.role]="myAriaRole ? true: null"