Programs & Examples On #Wcf ria services

Microsoft WCF RIA Services simplifies the traditional n-tier application pattern by bringing together the ASP.NET and Silverlight platforms.

Go to next item in ForEach-Object

I know this is an old post, but I wanted to add something I learned for the next folks who land here while googling.

In Powershell 5.1, you want to use continue to move onto the next item in your loop. I tested with 6 items in an array, had a foreach loop through, but put an if statement with:

foreach($i in $array){    
    write-host -fore green "hello $i"
    if($i -like "something"){
        write-host -fore red "$i is bad"
        continue
        write-host -fore red "should not see this"
    }
}

Of the 6 items, the 3rd one was something. As expected, it looped through the first 2, then the matching something gave me the red line where $i matched, I saw something is bad and then it went on to the next item in the array without saying should not see this. I tested with return and it exited the loop altogether.

SecurityError: Blocked a frame with origin from accessing a cross-origin frame

Same-origin policy

You can't access an <iframe> with different origin using JavaScript, it would be a huge security flaw if you could do it. For the same-origin policy browsers block scripts trying to access a frame with a different origin.

Origin is considered different if at least one of the following parts of the address isn't maintained:

protocol://hostname:port/...

Protocol, hostname and port must be the same of your domain if you want to access a frame.

NOTE: Internet Explorer is known to not strictly follow this rule, see here for details.

Examples

Here's what would happen trying to access the following URLs from http://www.example.com/home/index.html

URL                                             RESULT 
http://www.example.com/home/other.html       -> Success 
http://www.example.com/dir/inner/another.php -> Success 
http://www.example.com:80                    -> Success (default port for HTTP) 
http://www.example.com:2251                  -> Failure: different port 
http://data.example.com/dir/other.html       -> Failure: different hostname 
https://www.example.com/home/index.html:80   -> Failure: different protocol
ftp://www.example.com:21                     -> Failure: different protocol & port 
https://google.com/search?q=james+bond       -> Failure: different protocol, port & hostname 

Workaround

Even though same-origin policy blocks scripts from accessing the content of sites with a different origin, if you own both the pages, you can work around this problem using window.postMessage and its relative message event to send messages between the two pages, like this:

  • In your main page:

    const frame = document.getElementById('your-frame-id');
    frame.contentWindow.postMessage(/*any variable or object here*/, 'http://your-second-site.com');
    

    The second argument to postMessage() can be '*' to indicate no preference about the origin of the destination. A target origin should always be provided when possible, to avoid disclosing the data you send to any other site.

  • In your <iframe> (contained in the main page):

    window.addEventListener('message', event => {
        // IMPORTANT: check the origin of the data! 
        if (event.origin.startsWith('http://your-first-site.com')) { 
            // The data was sent from your site.
            // Data sent with postMessage is stored in event.data:
            console.log(event.data); 
        } else {
            // The data was NOT sent from your site! 
            // Be careful! Do not use it. This else branch is
            // here just for clarity, you usually shouldn't need it.
            return; 
        } 
    }); 
    

This method can be applied in both directions, creating a listener in the main page too, and receiving responses from the frame. The same logic can also be implemented in pop-ups and basically any new window generated by the main page (e.g. using window.open()) as well, without any difference.

Disabling same-origin policy in your browser

There already are some good answers about this topic (I just found them googling), so, for the browsers where this is possible, I'll link the relative answer. However, please remember that disabling the same-origin policy will only affect your browser. Also, running a browser with same-origin security settings disabled grants any website access to cross-origin resources, so it's very unsafe and should NEVER be done if you do not know exactly what you are doing (e.g. development purposes).

Wait for Angular 2 to load/resolve model before rendering view/template

Implement the routerOnActivate in your @Component and return your promise:

https://angular.io/docs/ts/latest/api/router/OnActivate-interface.html

EDIT: This explicitly does NOT work, although the current documentation can be a little hard to interpret on this topic. See Brandon's first comment here for more information: https://github.com/angular/angular/issues/6611

EDIT: The related information on the otherwise-usually-accurate Auth0 site is not correct: https://auth0.com/blog/2016/01/25/angular-2-series-part-4-component-router-in-depth/

EDIT: The angular team is planning a @Resolve decorator for this purpose.

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

Additionally, X-UA-Compatible must be the first meta tag in the head section

<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
</head>

By the way, the correct order or the main head tags are:

<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta charset="utf-8">
    <title>Site Title</title>
    <!-- other tags -->
</head>

This way

  1. we set the render engine to use before IExplorer begins to process
  2. the document then we set the encoding to use for all browser
  3. then we print the title, which will be processed with the already defined encoding.

Correct Semantic tag for copyright info - html5

Put it inside your <footer> by all means, but the most fitting element is the small element.

The HTML5 spec for this says:

Small print typically features disclaimers, caveats, legal restrictions, or copyrights. Small print is also sometimes used for attribution, or for satisfying licensing requirements.

Unicode characters in URLs

Use percent-encoded form. Some (mainly old) computers running Windows XP for example do not support Unicode, but rather ISO encodings. That is the reason percent-encoded URLs were invented. Also, if you give a URL printed on paper to a user, containing characters that cannot be easily typed, that user may have a hard time typing it (or just ignore it). Percent-encoded form can even be used in many of the oldest machines that ever existed (although they don't support internet of course).

There is a downside though, as percent-encoded characters are longer than the original ones, thus possibly resulting in really long URLs. But just try to ignore it, or use a URL shortener (I would recommend goo.gl in this case, which makes a 13-character long URL). Also, if you don't want to register for a Google account, try bit.ly (bit.ly makes slightly longer URLs, with the length being 14 characters).

How to compare if two structs, slices or maps are equal?

You can use reflect.DeepEqual, or you can implement your own function (which performance wise would be better than using reflection):

http://play.golang.org/p/CPdfsYGNy_

m1 := map[string]int{   
    "a":1,
    "b":2,
}
m2 := map[string]int{   
    "a":1,
    "b":2,
}
fmt.Println(reflect.DeepEqual(m1, m2))

Exception in thread "main" java.util.NoSuchElementException

The nextInt() method leaves the \n (end line) symbol and is picked up immediately by nextLine(), skipping over the next input. What you want to do is use nextLine() for everything, and parse it later:

String nextIntString = keyboard.nextLine(); //get the number as a single line
int nextInt = Integer.parseInt(nextIntString); //convert the string to an int

This is by far the easiest way to avoid problems--don't mix your "next" methods. Use only nextLine() and then parse ints or separate words afterwards.


Also, make sure you use only one Scanner if your are only using one terminal for input. That could be another reason for the exception.


Last note: compare a String with the .equals() function, not the == operator.

if (playAgain == "yes"); // Causes problems
if (playAgain.equals("yes")); // Works every time

How to find all occurrences of an element in a list

How about:

In [1]: l=[1,2,3,4,3,2,5,6,7]

In [2]: [i for i,val in enumerate(l) if val==3]
Out[2]: [2, 4]

How to find out which processes are using swap space in Linux?

I did notice this thread is rather old, but if you happen to stumble upon it, as I just did, another answer is: use smem.

Here is a link which tells you both how to install it and how to use it:

http://www.cyberciti.biz/faq/linux-which-process-is-using-swap/

Expand div to max width when float:left is set

This might work:

    div{
    display:inline-block;
    width:100%;
    float:left;
    }

How to split comma separated string using JavaScript?

Use

YourCommaSeparatedString.split(',');

How do I use the built in password reset/change views with my own templates

The documentation says that there only one context variable, form.

If you're having trouble with login (which is common), the documentation says there are three context variables:

  • form: A Form object representing the login form. See the forms documentation for more on Form objects.
  • next: The URL to redirect to after successful login. This may contain a query string, too.
  • site_name: The name of the current Site, according to the SITE_ID setting.

How to return a value from try, catch, and finally?

Here is another example that return's a boolean value using try/catch.

private boolean doSomeThing(int index){
    try {
        if(index%2==0) 
            return true; 
    } catch (Exception e) {
        System.out.println(e.getMessage()); 
    }finally {
        System.out.println("Finally!!! ;) ");
    }
    return false; 
}

How to delete a module in Android Studio

The "Mark as Excluded" option isn't there anymore.

The current (Android Studio 0.8.x - 2.2.x) way to do this is via the Project Structure dialog. It can be accessed via "File -> Project Structure" or by right-clicking on a Module and selecting "Module Settings".

enter image description here

Then select the module, and click the "minus" button to remove it.

enter image description here

The directory will still be visible in the "Project" view (though not in the "Android" view) since it's not actually deleted, but it will no longer be treated as a module.

If you want, you can then physically delete the files it by right-clicking on it and pressing "Delete".

Best approach to real time http streaming to HTML5 video client

Take a look at this solution. As I know, Flashphoner allows to play Live audio+video stream in the pure HTML5 page.

They use MPEG1 and G.711 codecs for playback. The hack is rendering decoded video to HTML5 canvas element and playing decoded audio via HTML5 audio context.

Excel Formula which places date/time in cell when data is entered in another cell in the same row

You can use If function Write in the cell where you want to input the date the following formula: =IF(MODIFIED-CELLNUMBER<>"",IF(CELLNUMBER-WHERE-TO-INPUT-DATE="",NOW(),CELLNUMBER-WHERE-TO-INPUT-DATE),"")

JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences?

The JSON spec requires UTF-8 support by decoders. As a result, all JSON decoders can handle UTF-8 just as well as they can handle the numeric escape sequences. This is also the case for Javascript interpreters, which means JSONP will handle the UTF-8 encoded JSON as well.

The ability for JSON encoders to use the numeric escape sequences instead just offers you more choice. One reason you may choose the numeric escape sequences would be if a transport mechanism in between your encoder and the intended decoder is not binary-safe.

Another reason you may want to use numeric escape sequences is to prevent certain characters appearing in the stream, such as <, & and ", which may be interpreted as HTML sequences if the JSON code is placed without escaping into HTML or a browser wrongly interprets it as HTML. This can be a defence against HTML injection or cross-site scripting (note: some characters MUST be escaped in JSON, including " and \).

Some frameworks, including PHP's implementation of JSON, always do the numeric escape sequences on the encoder side for any character outside of ASCII. This is intended for maximum compatibility with limited transport mechanisms and the like. However, this should not be interpreted as an indication that JSON decoders have a problem with UTF-8.

So, I guess you just could decide which to use like this:

  • Just use UTF-8, unless your method of storage or transport between encoder and decoder is not binary-safe.

  • Otherwise, use the numeric escape sequences.

How do I negate a test with regular expressions in a bash script?

You can also put the exclamation mark inside the brackets:

if [[ ! $PATH =~ $temp ]]

but you should anchor your pattern to reduce false positives:

temp=/mnt/silo/bin
pattern="(^|:)${temp}(:|$)"
if [[ ! "${PATH}" =~ ${pattern} ]]

which looks for a match at the beginning or end with a colon before or after it (or both). I recommend using lowercase or mixed case variable names as a habit to reduce the chance of name collisions with shell variables.

how do I check in bash whether a file was created more than x time ago?

Using the stat to figure out the last modification date of the file, date to figure out the current time and a liberal use of bashisms, one can do the test that you want based on the file's last modification time1.

if [ "$(( $(date +"%s") - $(stat -c "%Y" $somefile) ))" -gt "7200" ]; then
   echo "$somefile is older then 2 hours"
fi

While the code is a bit less readable then the find approach, I think its a better approach then running find to look at a file you already "found". Also, date manipulation is fun ;-)


  1. As Phil correctly noted creation time is not recorded, but use %Z instead of %Y below to get "change time" which may be what you want.

[Update]

For mac users, use stat -f "%m" $somefile instead of the Linux specific syntax above

How to call javascript function from asp.net button click event

If you don't need to initiate a post back when you press this button, then making the overhead of a server control isn't necesary.

<input id="addButton" type="button" value="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#addButton').click(function() 
         { 
             showDialog('#addPerson'); 
         });
     });
</script>

If you still need to be able to do a post back, you can conditionally stop the rest of the button actions with a little different code:

<asp:Button ID="buttonAdd" runat="server" Text="Add" />

<script type="text/javascript" language="javascript">
     $(document).ready(function()
     {
         $('#<%= buttonAdd.ClientID %>').click(function(e) 
         { 
             showDialog('#addPerson');

             if(/*Some Condition Is Not Met*/) 
                return false;
         });
     });
</script>

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

Is your type really arbitrary? If you know it is just going to be a int float or string you could just do

 if val.dtype == float and np.isnan(val):

assuming it is wrapped in numpy , it will always have a dtype and only float and complex can be NaN

How to get a div to resize its height to fit container?

Another one simple method is there. You don't need to code more in CSS. Just including a java script and entering the div "id" inside the script you can get equal height of columns so that you can have the height fit to container. It works in major browsers.

Source Code:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<meta http-equiv="Content-Script-Type" content="text/javascript" />
<title></title>
<style type="text/css">
*   {border:0; padding:0; margin:0;}/* Set everything to "zero" */
#container {
    margin-left: auto;
    margin-right: auto;
    border: 1px solid black;
    overflow: auto;
    width: 800px;       
}
#nav {
    width: 19%;
    border: 1px solid green;
    float:left; 
}
#content {
    width: 79%;
    border: 1px solid red;
    float:right;
}
</style>

<script language="javascript">
var ddequalcolumns=new Object()
//Input IDs (id attr) of columns to equalize. Script will check if each corresponding column actually exists:
ddequalcolumns.columnswatch=["nav", "content"]

ddequalcolumns.setHeights=function(reset){
var tallest=0
var resetit=(typeof reset=="string")? true : false
for (var i=0; i<this.columnswatch.length; i++){
if (document.getElementById(this.columnswatch[i])!=null){
if (resetit)
document.getElementById(this.columnswatch[i]).style.height="auto"
if (document.getElementById(this.columnswatch[i]).offsetHeight>tallest)
tallest=document.getElementById(this.columnswatch[i]).offsetHeight
}
}
if (tallest>0){
for (var i=0; i<this.columnswatch.length; i++){
if (document.getElementById(this.columnswatch[i])!=null)
document.getElementById(this.columnswatch[i]).style.height=tallest+"px"
}
}
}

ddequalcolumns.resetHeights=function(){
this.setHeights("reset")
}

ddequalcolumns.dotask=function(target, functionref, tasktype){ //assign a function to execute to an event handler (ie: onunload)
var tasktype=(window.addEventListener)? tasktype : "on"+tasktype
if (target.addEventListener)
target.addEventListener(tasktype, functionref, false)
else if (target.attachEvent)
target.attachEvent(tasktype, functionref)
}

ddequalcolumns.dotask(window, function(){ddequalcolumns.setHeights()}, "load")
ddequalcolumns.dotask(window, function(){if (typeof ddequalcolumns.timer!="undefined") clearTimeout(ddequalcolumns.timer); ddequalcolumns.timer=setTimeout("ddequalcolumns.resetHeights()", 200)}, "resize")


</script>

<div id=container>
    <div id=nav>
        <ul>
                <li>Menu</li>
                <li>Menu</li>
                <li>Menu</li>
                <li>Menu</li>
                <li>Menu</li>
        </ul>
    </div>
    <div id=content>
        <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam fermentum consequat ligula vitae posuere. Mauris dolor quam, consequat vel condimentum eget, aliquet sit amet sem. Nulla in lectus ac felis ultrices dignissim quis ac orci. Nam non tellus eget metus sollicitudin venenatis sit amet at dui. Quisque malesuada feugiat tellus, at semper eros mollis sed. In luctus tellus in magna condimentum sollicitudin. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur vel dui est. Aliquam vitae condimentum dui. Praesent vel mi at odio blandit pellentesque. Proin felis massa, vestibulum a hendrerit ut, imperdiet in nulla. Sed aliquam, dolor id congue porttitor, mauris turpis congue felis, vel luctus ligula libero in arcu. Pellentesque egestas blandit turpis ac aliquet. Sed sit amet orci non turpis feugiat euismod. In elementum tristique tortor ac semper.</p>
    </div>
</div>

</body>
</html>

You can include any no of divs in this script.

ddequalcolumns.columnswatch=["nav", "content"]

modify in the above line its enough.

Try this.

Spring RestTemplate timeout

I had a similar scenario, but was also required to set a Proxy. The simplest way I could see to do this was to extend the SimpleClientHttpRequestFactory for the ease of setting the proxy (different proxies for non-prod vs prod). This should still work even if you don't require the proxy though. Then in my extended class I override the openConnection(URL url, Proxy proxy) method, using the same as the source, but just setting the timeouts before returning.

@Override
protected HttpURLConnection openConnection(URL url, Proxy proxy) throws IOException {
    URLConnection urlConnection = proxy != null ? url.openConnection(proxy) : url.openConnection();
    Assert.isInstanceOf(HttpURLConnection.class, urlConnection);
    urlConnection.setConnectTimeout(5000);
    urlConnection.setReadTimeout(5000);
    return (HttpURLConnection) urlConnection;
}

How to unpublish an app in Google Play Developer Console

The new version is hard to find. Select the app, then look for "3 dot menu" in upper right corner. enter image description here

How can I get sin, cos, and tan to use degrees instead of radians?

Multiply the input by Math.PI/180 to convert from degrees to radians before calling the system trig functions.

You could also define your own functions:

function sinDegrees(angleDegrees) {
    return Math.sin(angleDegrees*Math.PI/180);
};

and so on.

MySQL Error 1215: Cannot add foreign key constraint

When this error occurrs because the referenced table uses the MyISAM engine this answer provides a quick way to convert your database so all Django model tables use InnoDB: https://stackoverflow.com/a/15389961/2950621

It's a Django management command called convert_to_innodb.

Attach parameter to button.addTarget action in Swift

For Swift 3.0 you can use following

button.addTarget(self, action: #selector(YourViewController.YourMethodName(_:)), for:.touchUpInside)

func YourMethodName(_ sender : UIButton) {
    print(sender.tag)

}

How to get df linux command output always in GB

If you also want it to be a command you can reference without remembering the arguments, you could simply alias it:

alias df-gb='df -BG'

So if you type:

df-gb

into a terminal, you'll get your intended output of the disk usage in GB.

EDIT: or even use just df -h to get it in a standard, human readable format.

http://www.thegeekstuff.com/2012/05/df-examples/

Group by multiple field names in java 8

You can use List as a classifier for many fields, but you need wrap null values into Optional:

Function<String, List> classifier = (item) -> List.of(
    item.getFieldA(),
    item.getFieldB(),
    Optional.ofNullable(item.getFieldC())
);

Map<List, List<Item>> grouped = items.stream()
    .collect(Collectors.groupingBy(classifier));

Oracle SQL Developer - tables cannot be seen

SQL Developer 3.1 fixes this issue. Its an early adopter release at the moment though.

How do I download the Android SDK without downloading Android Studio?

I downloaded Android Studio and installed it. The installer said:-

Android Studio => ( 500 MB )

Android SDK => ( 2.3 GB )

Android Studio installer is actually an "Android SDK Installer" along with a sometimes useful tool called "Android Studio".

Most importantly:- Android Studio Installer will not just install the SDK. It will also:-

  • Install the latest build-tools.
  • Install the latest platform-tools.
  • Install the latest AVD Manager which you cannot do without.

Things which you will have to do manually if you install the SDK from its zip file.

Just take it easy. Install the Android Studio.

****************************** Edit ******************************

So, being inspired by the responses in the comments I would like to update my answer.

The update is that only (and only) if 500MB of hard disk space does not matter much to you than you should go for Android Studio otherwise other answers would be better for you.

Android Studio worked for me as I had a 1TB hard disk which is 2000 times 500MB.

Also, note: that RAM sizse should not a restriction for you as you would not even be running Android Studio.

I came to this solution as I was myself stuck in this problem. I tried other answers but for some reason (maybe my in-competencies) they did not work for me. I decided to go for Android Studio and realized that it was merely 18% of the total installation and SDK was 82% of it. While I used to think otherwise. I am not deleting the answers inspite of negative rating as the answer worked for me. I might work for someone elese with a 1 TB hard disk (which is pretty common these days).

Warning as error - How to get rid of these

View -> Error list -> Right click on specific Error/Warning.

You can change Severity as You want.

return value after a promise

The best way to do this would be to use the promise returning function as it is, like this

lookupValue(file).then(function(res) {
    // Write the code which depends on the `res.val`, here
});

The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.

So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

Trimming text strings in SQL Server 2008

I know this is an old question but I just found a solution which creates a user defined function using LTRIM and RTRIM. It does not handle double spaces in the middle of a string.

The solution is however straight forward:

User Defined Trim Function

internal/modules/cjs/loader.js:582 throw err

For me "npm install" again from command prompt worked. Command Prompt must be "Run as Administrator"

How do I convert a Django QuerySet into list of dicts?

The .values() method will return you a result of type ValuesQuerySet which is typically what you need in most cases.

But if you wish, you could turn ValuesQuerySet into a native Python list using Python list comprehension as illustrated in the example below.

result = Blog.objects.values()             # return ValuesQuerySet object
list_result = [entry for entry in result]  # converts ValuesQuerySet into Python list
return list_result

I find the above helps if you are writing unit tests and need to assert that the expected return value of a function matches the actual return value, in which case both expected_result and actual_result must be of the same type (e.g. dictionary).

actual_result = some_function()
expected_result = {
    # dictionary content here ...
}
assert expected_result == actual_result

new DateTime() vs default(DateTime)

If you want to use default value for a DateTime parameter in a method, you can only use default(DateTime).

The following line will not compile:

    private void MyMethod(DateTime syncedTime = DateTime.MinValue)

This line will compile:

    private void MyMethod(DateTime syncedTime = default(DateTime))

Describe table structure

SELECT *
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = 'student'

Javascript - Append HTML to container element without innerHTML

This is what DocumentFragment was meant for.

var frag = document.createDocumentFragment();
var span = document.createElement("span");
span.innerHTML = htmldata;
for (var i = 0, ii = span.childNodes.length; i < ii; i++) {
    frag.appendChild(span.childNodes[i]);
}
element.appendChild(frag);

document.createDocumentFragment, .childNodes

Which characters are valid in CSS class names/selectors?

You can check directly at the CSS grammar.

Basically1, a name must begin with an underscore (_), a hyphen (-), or a letter(az), followed by any number of hyphens, underscores, letters, or numbers. There is a catch: if the first character is a hyphen, the second character must2 be a letter or underscore, and the name must be at least 2 characters long.

-?[_a-zA-Z]+[_a-zA-Z0-9-]*

In short, the previous rule translates to the following, extracted from the W3C spec.:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, or a hyphen followed by a digit. Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item). For instance, the identifier "B&W?" may be written as "B&W?" or "B\26 W\3F".

Identifiers beginning with a hyphen or underscore are typically reserved for browser-specific extensions, as in -moz-opacity.

1 It's all made a bit more complicated by the inclusion of escaped unicode characters (that no one really uses).

2 Note that, according to the grammar I linked, a rule starting with TWO hyphens, e.g. --indent1, is invalid. However, I'm pretty sure I've seen this in practice.

How can I test an AngularJS service from the console?

TLDR: In one line the command you are looking for:

angular.element(document.body).injector().get('serviceName')

Deep dive

AngularJS uses Dependency Injection (DI) to inject services/factories into your components,directives and other services. So what you need to do to get a service is to get the injector of AngularJS first (the injector is responsible for wiring up all the dependencies and providing them to components).

To get the injector of your app you need to grab it from an element that angular is handling. For example if your app is registered on the body element you call injector = angular.element(document.body).injector()

From the retrieved injector you can then get whatever service you like with injector.get('ServiceName')

More information on that in this answer: Can't retrieve the injector from angular
And even more here: Call AngularJS from legacy code


Another useful trick to get the $scope of a particular element. Select the element with the DOM inspection tool of your developer tools and then run the following line ($0 is always the selected element):
angular.element($0).scope()

Get GPS location via a service in Android

public class GPSService extends Service implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
    private LocationRequest mLocationRequest;
    private GoogleApiClient mGoogleApiClient;
    private static final String LOGSERVICE = "#######";

    @Override
    public void onCreate() {
        super.onCreate();
        buildGoogleApiClient();
        Log.i(LOGSERVICE, "onCreate");

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(LOGSERVICE, "onStartCommand");

        if (!mGoogleApiClient.isConnected())
            mGoogleApiClient.connect();
        return START_STICKY;
    }


    @Override
    public void onConnected(Bundle bundle) {
        Log.i(LOGSERVICE, "onConnected" + bundle);

        Location l = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (l != null) {
            Log.i(LOGSERVICE, "lat " + l.getLatitude());
            Log.i(LOGSERVICE, "lng " + l.getLongitude());

        }

        startLocationUpdate();
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(LOGSERVICE, "onConnectionSuspended " + i);

    }

    @Override
    public void onLocationChanged(Location location) {
        Log.i(LOGSERVICE, "lat " + location.getLatitude());
        Log.i(LOGSERVICE, "lng " + location.getLongitude());
        LatLng mLocation = (new LatLng(location.getLatitude(), location.getLongitude()));
        EventBus.getDefault().post(mLocation);

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(LOGSERVICE, "onDestroy - Estou sendo destruido ");

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(LOGSERVICE, "onConnectionFailed ");

    }

    private void initLocationRequest() {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(5000);
        mLocationRequest.setFastestInterval(2000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    }

    private void startLocationUpdate() {
        initLocationRequest();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    private void stopLocationUpdate() {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);

    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addOnConnectionFailedListener(this)
                .addConnectionCallbacks(this)
                .addApi(LocationServices.API)
                .build();
    }

}

Can you style html form buttons with css?

write the below style into same html file head section or write into a .css file

<style type="text/css">
.submit input
    {
    color: #000;
    background: #ffa20f;
    border: 2px outset #d7b9c9
    }
</style>

<input type="submit" class="submit"/>

.submit - in css . means class , so i created submit class with set of attributes
and applied that class to the submit tag, using class attribute

Is it better to use C void arguments "void foo(void)" or not "void foo()"?

C99 quotes

This answer aims to quote and explain the relevant parts of the C99 N1256 standard draft.

Definition of declarator

The term declarator will come up a lot, so let's understand it.

From the language grammar, we find that the following underline characters are declarators:

int f(int x, int y);
    ^^^^^^^^^^^^^^^

int f(int x, int y) { return x + y; }
    ^^^^^^^^^^^^^^^

int f();
    ^^^

int f(x, y) int x; int y; { return x + y; }
    ^^^^^^^

Declarators are part of both function declarations and definitions.

There are 2 types of declarators:

  • parameter type list
  • identifier list

Parameter type list

Declarations look like:

int f(int x, int y);

Definitions look like:

int f(int x, int y) { return x + y; }

It is called parameter type list because we must give the type of each parameter.

Identifier list

Definitions look like:

int f(x, y)
    int x;
    int y;
{ return x + y; }

Declarations look like:

int g();

We cannot declare a function with a non-empty identifier list:

int g(x, y);

because 6.7.5.3 "Function declarators (including prototypes)" says:

3 An identifier list in a function declarator that is not part of a definition of that function shall be empty.

It is called identifier list because we only give the identifiers x and y on f(x, y), types come after.

This is an older method, and shouldn't be used anymore. 6.11.6 Function declarators says:

1 The use of function declarators with empty parentheses (not prototype-format parameter type declarators) is an obsolescent feature.

and the Introduction explains what is an obsolescent feature:

Certain features are obsolescent, which means that they may be considered for withdrawal in future revisions of this International Standard. They are retained because of their widespread use, but their use in new implementations (for implementation features) or new programs (for language [6.11] or library features [7.26]) is discouraged

f() vs f(void) for declarations

When you write just:

void f();

it is necessarily an identifier list declaration, because 6.7.5 "Declarators" says defines the grammar as:

direct-declarator:
    [...]
    direct-declarator ( parameter-type-list )
    direct-declarator ( identifier-list_opt )

so only the identifier-list version can be empty because it is optional (_opt).

direct-declarator is the only grammar node that defines the parenthesis (...) part of the declarator.

So how do we disambiguate and use the better parameter type list without parameters? 6.7.5.3 Function declarators (including prototypes) says:

10 The special case of an unnamed parameter of type void as the only item in the list specifies that the function has no parameters.

So:

void f(void);

is the way.

This is a magic syntax explicitly allowed, since we cannot use a void type argument in any other way:

void f(void v);
void f(int i, void);
void f(void, int);

What can happen if I use an f() declaration?

Maybe the code will compile just fine: 6.7.5.3 Function declarators (including prototypes):

14 The empty list in a function declarator that is not part of a definition of that function specifies that no information about the number or types of the parameters is supplied.

So you can get away with:

void f();
void f(int x) {}

Other times, UB can creep up (and if you are lucky the compiler will tell you), and you will have a hard time figuring out why:

void f();
void f(float x) {}

See: Why does an empty declaration work for definitions with int arguments but not for float arguments?

f() and f(void) for definitions

f() {}

vs

f(void) {}

are similar, but not identical.

6.7.5.3 Function declarators (including prototypes) says:

14 An empty list in a function declarator that is part of a definition of that function specifies that the function has no parameters.

which looks similar to the description of f(void).

But still... it seems that:

int f() { return 0; }
int main(void) { f(1); }

is conforming undefined behavior, while:

int f(void) { return 0; }
int main(void) { f(1); }

is non conforming as discussed at: Why does gcc allow arguments to be passed to a function defined to be with no arguments?

TODO understand exactly why. Has to do with being a prototype or not. Define prototype.

google chrome extension :: console.log() from background page?

To answer your question directly, when you call console.log("something") from the background, this message is logged, to the background page's console. To view it, you may go to chrome://extensions/ and click on that inspect view under your extension.

When you click the popup, it's loaded into the current page, thus the console.log should show log message in the current page.

How to write LDAP query to test if user is member of a group?

I would add one more thing to Marc's answer: The memberOf attribute can't contain wildcards, so you can't say something like "memberof=CN=SPS*", and expect it to find all groups that start with "SPS".

Accessing Websites through a Different Port?

You can run the web server on any port. 80 is just convention as are 8080 (web server on unprivileged port) and 443 (web server + ssl). However if you're looking to see some web site by pointing your browser to a different port you're probably out of luck. Unless the web server is being run on that port explicitly you'll just get an error message.

How to scroll to top of long ScrollView layout?

scrollView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
    @Override
    public void onGlobalLayout() {
        // Ready, move up
        scrollView.fullScroll(View.FOCUS_UP);
    }
});

HTML5 Video autoplay on iPhone

iOs 10+ allow video autoplay inline. but you have to turn off "Low power mode" on your iPhone.

How do I plot only a table in Matplotlib?

Not sure if this is already answered, but if you want only a table in a figure window, then you can hide the axes:

fig, ax = plt.subplots()

# Hide axes
ax.xaxis.set_visible(False) 
ax.yaxis.set_visible(False)

# Table from Ed Smith answer
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
ax.table(cellText=clust_data,colLabels=collabel,loc='center')

Element implicitly has an 'any' type because expression of type 'string' can't be used to index

This is what it worked for me. The tsconfig.json has an option noImplicitAny that it was set to true, I just simply set it to false and now I can access properties in objects using strings.

How can I get a JavaScript stack trace when I throw an exception?

one way to get a the real stack trace on Firebug is to create a real error like calling an undefined function:

function foo(b){
  if (typeof b !== 'string'){
    // undefined Error type to get the call stack
    throw new ChuckNorrisError("Chuck Norris catches you.");
  }
}

function bar(a){
  foo(a);
}

foo(123);

Or use console.error() followed by a throw statement since console.error() shows the stack trace.

How to count total lines changed by a specific author in a Git repository?

In addition to Charles Bailey's answer, you might want to add the -C parameter to the commands. Otherwise file renames count as lots of additions and removals (as many as the file has lines), even if the file content was not modified.

To illustrate, here is a commit with lots of files being moved around from one of my projects, when using the git log --oneline --shortstat command:

9052459 Reorganized project structure
 43 files changed, 1049 insertions(+), 1000 deletions(-)

And here the same commit using the git log --oneline --shortstat -C command which detects file copies and renames:

9052459 Reorganized project structure
 27 files changed, 134 insertions(+), 85 deletions(-)

In my opinion the latter gives a more realistic view of how much impact a person has had on the project, because renaming a file is a much smaller operation than writing the file from scratch.

How do I flush the PRINT buffer in TSQL?

Another better option is to not depend on PRINT or RAISERROR and just load your "print" statements into a ##Temp table in TempDB or a permanent table in your database which will give you visibility to the data immediately via a SELECT statement from another window. This works the best for me. Using a permanent table then also serves as a log to what happened in the past. The print statements are handy for errors, but using the log table you can also determine the exact point of failure based on the last logged value for that particular execution (assuming you track the overall execution start time in your log table.)

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

Automatic prune with Git fetch or pull

If you want to always prune when you fetch, I can suggest to use Aliases.

Just type git config -e to open your editor and change the configuration for a specific project and add a section like

[alias]
pfetch = fetch --prune   

the when you fetch with git pfetch the prune will be done automatically.

Show only two digit after decimal

Use DecimalFormat.

DecimalFormat is a concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features designed to make it possible to parse and format numbers in any locale, including support for Western, Arabic, and Indic digits. It also supports different kinds of numbers, including integers (123), fixed-point numbers (123.4), scientific notation (1.23E4), percentages (12%), and currency amounts ($123). All of these can be localized.

Code snippet -

double i2=i/60000;
tv.setText(new DecimalFormat("##.##").format(i2));

Output -

5.81

IBOutlet and IBAction

IBOutlet

  • It is a property.
  • When the nib(IB) file is loaded, it becomes part of encapsulated data which connects to an instance variable.
  • Each connection is unarchived and reestablished.

IBAction

  • Attribute indicates that the method is an action that you can connect to from your storyboard in Interface Builder.

@ - Dynamic pattern IB - Interface Builder

How to overcome TypeError: unhashable type: 'list'

As indicated by the other answers, the error is to due to k = list[0:j], where your key is converted to a list. One thing you could try is reworking your code to take advantage of the split function:

# Using with ensures that the file is properly closed when you're done
with open('filename.txt', 'rb') as f:
  d = {}
  # Here we use readlines() to split the file into a list where each element is a line
  for line in f.readlines():
    # Now we split the file on `x`, since the part before the x will be
    # the key and the part after the value
    line = line.split('x')
    # Take the line parts and strip out the spaces, assigning them to the variables
    # Once you get a bit more comfortable, this works as well:
    # key, value = [x.strip() for x in line] 
    key = line[0].strip()
    value = line[1].strip()
    # Now we check if the dictionary contains the key; if so, append the new value,
    # and if not, make a new list that contains the current value
    # (For future reference, this is a great place for a defaultdict :)
    if key in d:
      d[key].append(value)
    else:
      d[key] = [value]

print d
# {'AAA': ['111', '112'], 'AAC': ['123'], 'AAB': ['111']}

Note that if you are using Python 3.x, you'll have to make a minor adjustment to get it work properly. If you open the file with rb, you'll need to use line = line.split(b'x') (which makes sure you are splitting the byte with the proper type of string). You can also open the file using with open('filename.txt', 'rU') as f: (or even with open('filename.txt', 'r') as f:) and it should work fine.

"Debug only" code that should run only when "turned on"

What you're looking for is

[ConditionalAttribute("DEBUG")]

attribute.

If you for instance write a method like :

[ConditionalAttribute("DEBUG")]
public static void MyLovelyDebugInfoMethod(string message)
{
    Console.WriteLine("This message was brought to you by your debugger : ");
    Console.WriteLine(message);
}

any call you make to this method inside your own code will only be executed in debug mode. If you build your project in release mode, even call to the "MyLovelyDebugInfoMethod" will be ignored and dumped out of your binary.

Oh and one more thing if you're trying to determine whether or not your code is currently being debugged at the execution moment, it is also possible to check if the current process is hooked by a JIT. But this is all together another case. Post a comment if this is what you2re trying to do.

The type or namespace name 'DbContext' could not be found

For step-by-step instructions, see this new MVC / EF tutorial series: http://www.asp.net/entity-framework/tutorials/creating-an-entity-framework-data-model-for-an-asp-net-mvc-application The tutorial assumes you have installed the latest MVC 3 Tools Update and provides a link in case you haven't.

How many parameters are too many?

One more than necessary. I don't mean to be glib, but there are some functions that necessarily need quite a few options. For example:

void *
mmap(void *addr, size_t len, int prot, int flags, int fildes, off_t offset);

There are 6 arguments, and every one of them is essential. Furthermore, there's no common link between them to justify bundling them. Maybe you could define "struct mmapargs", but that would worse.

How to list AD group membership for AD users using input list?

The below code will return username group membership using the samaccountname. You can modify it to get input from a file or change the query to get accounts with non expiring passwords etc

$location = "c:\temp\Peace2.txt"
$users = (get-aduser -filter *).samaccountname
$le = $users.length
for($i = 0; $i -lt $le; $i++){
  $output = (get-aduser $users[$i] | Get-ADPrincipalGroupMembership).name
  $users[$i] + " " + $output 
  $z =  $users[$i] + " " + $output 
  add-content $location $z
}

Sample Output:

Administrator Domain Users Administrators Schema Admins Enterprise Admins Domain Admins Group Policy Creator Owners
Guest Domain Guests Guests
krbtgt Domain Users Denied RODC Password Replication Group
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production
Redacted Domain Users CompanyUsers Production

Looping through a Scripting.Dictionary using index/item number

Adding to assylias's answer - assylias shows us D.ITEMS is a method that returns an array. Knowing that, we don't need the variant array a(i) [See caveat below]. We just need to use the proper array syntax.

For i = 0 To d.Count - 1
    s = d.Items()(i)
    Debug.Print s
Next i()

KEYS works the same way

For i = 0 To d.Count - 1
    Debug.Print d.Keys()(i), d.Items()(i)
Next i

This syntax is also useful for the SPLIT function which may help make this clearer. SPLIT also returns an array with lower bounds at 0. Thus, the following prints "C".

Debug.Print Split("A,B,C,D", ",")(2)

SPLIT is a function. Its parameters are in the first set of parentheses. Methods and Functions always use the first set of parentheses for parameters, even if no parameters are needed. In the example SPLIT returns the array {"A","B","C","D"}. Since it returns an array we can use a second set of parentheses to identify an element within the returned array just as we would any array.

Caveat: This shorter syntax may not be as efficient as using the variant array a() when iterating through the entire dictionary since the shorter syntax invokes the dictionary's Items method with each iteration. The shorter syntax is best for plucking a single item by number from a dictionary.

Width equal to content

I set width as max-content and it worked for me.

width: max-content;

Convert string to decimal number with 2 decimal places in Java

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

System.out.println("liters of petrol before putting in editor : "+litersOfPetrol);

You print Float here, that has no format at all.

To print formatted float, just use

String formatted = df.format(litersOfPetrol);
System.out.println("liters of petrol before putting in editor : " + formatted);

'this' is undefined in JavaScript class methods

This question has been answered, but maybe this might someone else coming here.

I also had an issue where this is undefined, when I was foolishly trying to destructure the methods of a class when initialising it:

import MyClass from "./myClass"

// 'this' is not defined here:
const { aMethod } = new MyClass()
aMethod() // error: 'this' is not defined

// So instead, init as you would normally:
const myClass = new MyClass()
myClass.aMethod() // OK

Is there any way to start with a POST request using Selenium?

One very practical way to do this is to create a dummy start page for your tests that is simply a form with POST that has a single "start test" button and a bunch of <input type="hidden"... elements with the appropriate post data.

For example you might create a SeleniumTestStart.html page with these contents:

<body>
  <form action="/index.php" method="post">
    <input id="starttestbutton" type="submit" value="starttest"/>
    <input type="hidden" name="stageid" value="stage-you-need-your-test-to-start-at"/>
  </form>
</body>

In this example, index.php is where your normal web app is located.

The Selenium code at the start of your tests would then include:

open /SeleniumTestStart.html
clickAndWait starttestbutton

This is very similar to other mock and stub techniques used in automated testing. You are just mocking the entry point to the web app.

Obviously there are some limitations to this approach:

  1. data cannot be too large (e.g. image data)
  2. security might be an issue so you need to make sure that these test files don't end up on your production server
  3. you may need to make your entry points with something like php instead of html if you need to set cookies before the Selenium test gets going
  4. some web apps check the referrer to make sure someone isn't hacking the app - in this case this approach probably won't work - you may be able to loosen this checking in a dev environment so it allows referrers from trusted hosts (not self, but the actual test host)

Please consider reading my article about the Qualities of an Ideal Test

How to pass a parameter like title, summary and image in a Facebook sharer URL

This works at the moment (Oct. 2016), but I can't guarantee how long it will last:

https://www.facebook.com/sharer.php?caption=[caption]&description=[description]&u=[website]&picture=[image-url]

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

highlight the navigation menu for the current page

JavaScript:

<script type="text/javascript">
    $(function() { 
        var url = window.location;
        $('ul.nav a').filter(function() {
            return this.href == url;
        }).parent().parent().parent().addClass('active');
    });   
</script>

CSS:

.active{
    color: #fff;
    background-color: #080808;
}

HTML:

<ul class="nav navbar-nav">
                        <li class="dropdown">
                            <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="true"><i class="glyphicon glyphicon-user icon-white"></i> MY ACCOUNT <span class="caret"></span></a>
                            <ul class="dropdown-menu" role="menu">
                                <li>
                                    <?php echo anchor('myaccount', 'HOME', 'title="HOME"'); ?>
                                </li>
                                <li>
                                    <?php echo anchor('myaccount/credithistory', 'CREDIT HISTORY', 'title="CREDIT HISTORY"'); ?>
                                </li>
                          </ul>
                     </li>
</ul>

Git push error: "origin does not appear to be a git repository"

May be you forgot to run "git --bare init" on the remote? That was my problem

flutter remove back button on appbar

  appBar: new AppBar(title: new Text("SmartDocs SPAY"),backgroundColor: Colors.blueAccent, automaticallyImplyLeading:false,
        leading: new Container(),
      ),

It is working Fine

How to get the selected value from RadioButtonList?

string radioListValue = RadioButtonList.Text;

How can I select an element by name with jQuery?

You forgot the second set of quotes, which makes the accepted answer incorrect:

$('td[name="tcol1"]') 

How to print Two-Dimensional Array like table

Iliya,

Sorry for that.

you code is work. but its had some problem with Array row and columns

here i correct your code this work correctly, you can try this ..

public static void printMatrix(int size, int row, int[][] matrix) {

    for (int i = 0; i < 7 * matrix[row].length; i++) {
        System.out.print("-");
    }
    System.out.println("-");

    for (int i = 1; i <= matrix[row].length; i++) {
        System.out.printf("| %4d ", matrix[row][i - 1]);
    }
    System.out.println("|");

    if (row == size - 1) {

        // when we reach the last row,
        // print bottom line "---------"

        for (int i = 0; i < 7 * matrix[row].length; i++) {
            System.out.print("-");
        }
        System.out.println("-");

    }
}

public static void length(int[][] matrix) {

    int rowsLength = matrix.length;

    for (int k = 0; k < rowsLength; k++) {

        printMatrix(rowsLength, k, matrix);

    }

}

public static void main(String[] args) {

    int[][] matrix = { { 1, 2, 5 }, { 3, 4, 6 }, { 7, 8, 9 }

    };

    length(matrix);

}

and out put look like

----------------------
|    1 |    2 |    5 |
----------------------
|    3 |    4 |    6 |
----------------------
|    7 |    8 |    9 |
----------------------

SQL update trigger only when column is modified

You have two way for your question :

1- Use Update Command in your Trigger.

ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
   ON [dbo].[SCHEDULE]
   AFTER UPDATE
AS BEGIN
    SET NOCOUNT ON;
    IF UPDATE (QtyToRepair) 
    BEGIN
        UPDATE SCHEDULE 
        SET modified = GETDATE()
           , ModifiedUser = SUSER_NAME()
           , ModifiedHost = HOST_NAME()
        FROM SCHEDULE S INNER JOIN Inserted I 
        ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
        WHERE S.QtyToRepair <> I.QtyToRepair
    END 
END

2- Use Join between Inserted table and deleted table

ALTER TRIGGER [dbo].[tr_SCHEDULE_Modified]
   ON [dbo].[SCHEDULE]
   AFTER UPDATE
AS BEGIN
    SET NOCOUNT ON;    

    UPDATE SCHEDULE 
    SET modified = GETDATE()
       , ModifiedUser = SUSER_NAME()
       , ModifiedHost = HOST_NAME()
    FROM SCHEDULE S 
    INNER JOIN Inserted I ON S.OrderNo = I.OrderNo and S.PartNumber = I.PartNumber
    INNER JOIN Deleted D ON S.OrderNo = D.OrderNo and S.PartNumber = D.PartNumber                  
    WHERE S.QtyToRepair <> I.QtyToRepair
    AND D.QtyToRepair <> I.QtyToRepair
END

When you use update command for table SCHEDULE and Set QtyToRepair Column to new value, if new value equal to old value in one or multi row, solution 1 update all updated row in Schedule table but solution 2 update only schedule rows that old value not equal to new value.

How to retrieve Request Payload

Also you can setup extJs writer with encode: true and it will send data regularly (and, hence, you will be able to retrieve data via $_POST and $_GET).

... the values will be sent as part of the request parameters as opposed to a raw post (via docs for encode config of Ext.data.writer.Json)

UPDATE

Also docs say that:

The encode option should only be set to true when a root is defined

So, probably, writer's root config is required.

Where does gcc look for C and C++ header files?

These are the directories that gcc looks in by default for the specified header files ( given that the header files are included in chevrons <>); 1. /usr/local/include/ --used for 3rd party header files. 2. /usr/include/ -- used for system header files.

If in case you decide to put your custom header file in a place other than the above mentioned directories, you can include them as follows: 1. using quotes ("./custom_header_files/foo.h") with files path, instead of chevrons in the include statement. 2. using the -I switch when compiling the code. gcc -I /home/user/custom_headers/ -c foo.c -p foo.o Basically the -I switch tells the compiler to first look in the directory specified with the -I switch ( before it checks the standard directories).When using the -I switch the header files may be included using chevrons.

String contains another two strings

So what is that you are really after? If you want to make sure that something has hit for damage (in this case), why are you not using string.Format

string a = string.Format("You hit someone for {d} damage", damage);

In this way, you have the ability to have the damage qualifier that you are looking for, and are able to calculate that for other parts.

Checking if an input field is required using jQuery

You don't need jQuery to do this. Here's an ES2015 solution:

// Get all input fields
const inputs = document.querySelectorAll('#register input');

// Get only the required ones
const requiredFields = Array.from(inputs).filter(input => input.required);

// Do your stuff with the required fields
requiredFields.forEach(field => /* do what you want */);

Or you could just use the :required selector:

Array.from(document.querySelectorAll('#register input:required'))
    .forEach(field => /* do what you want */);

How to check if String is null

To sure, you should use function to check is null and empty as below:

string str = ...
if (!String.IsNullOrEmpty(str))
{
...
}

How to check the installed version of React-Native

The best practice for checking the react native environment information.

react-native info

which will give the information

React Native Environment Info:
System:
  OS: Linux 4.15 Ubuntu 18.04.1 LTS (Bionic Beaver)
  CPU: (8) x64 Intel(R) Core(TM) i7-3770 CPU @ 3.40GHz
  Memory: 2.08 GB / 7.67 GB
  Shell: 4.4.19 - /bin/bash
Binaries:
  Node: 8.10.0 - /usr/bin/node
  Yarn: 1.12.3 - /usr/bin/yarn
  npm: 3.5.2 - /usr/bin/npm
npmPackages:
  react: 16.4.1 => 16.4.1 
  react-native: 0.56.0 => 0.56.0 
npmGlobalPackages:
  react-native-cli: 2.0.1
  react-native: 0.57.8

Generate random int value from 3 to 6

Lamak's answer as a function:

-- Create RANDBETWEEN function
-- Usage: SELECT dbo.RANDBETWEEN(0,9,RAND(CHECKSUM(NEWID())))
CREATE FUNCTION dbo.RANDBETWEEN(@minval TINYINT, @maxval TINYINT, @random NUMERIC(18,10))
RETURNS TINYINT
AS
BEGIN
  RETURN (SELECT CAST(((@maxval + 1) - @minval) * @random + @minval AS TINYINT))
END
GO

How do I erase an element from std::vector<> by index?

Actually, the erase function works for two profiles:

  • Removing a single element

    iterator erase (iterator position);
    
  • Removing a range of elements

    iterator erase (iterator first, iterator last);
    

Since std::vec.begin() marks the start of container and if we want to delete the ith element in our vector, we can use:

vec.erase(vec.begin() + index);

If you look closely, vec.begin() is just a pointer to the starting position of our vector and adding the value of i to it increments the pointer to i position, so instead we can access the pointer to the ith element by:

&vec[i]

So we can write:

vec.erase(&vec[i]); // To delete the ith element

SQL Server: the maximum number of rows in table

Largest table I've encountered on SQL Server 8 on Windows2003 was 799 million with 5 columns. But whether or not it's good will is to be measured against the SLA and usage case - e.g. load 50-100,000,000 records and see if it still works.

Java creating .jar file

Sine you've mentioned you're using Eclipse... Eclipse can create the JARs for you, so long as you've run each class that has a main once. Right-click the project and click Export, then select "Runnable JAR file" under the Java folder. Select the class name in the launch configuration, choose a place to save the jar, and make a decision how to handle libraries if necessary. Click finish, wipe hands on pants.

How to launch multiple Internet Explorer windows/tabs from batch file?

You can use either of these two scripts to open the URLs in separate tabs in a (single) new IE window. You can call either of these scripts from within your batch script (or at the command prompt):

JavaScript
Create a file with a name like: "urls.js":

var navOpenInNewWindow = 0x1;
var navOpenInNewTab = 0x800;
var navOpenInBackgroundTab = 0x1000;

var intLoop = 0;
var intArrUBound = 0;
var navFlags = navOpenInBackgroundTab;
var arrstrUrl = new Array(3);
var objIE;

    intArrUBound = arrstrUrl.length;

    arrstrUrl[0] = "http://bing.com/";
    arrstrUrl[1] = "http://google.com/";
    arrstrUrl[2] = "http://msn.com/";
    arrstrUrl[3] = "http://yahoo.com/";

    objIE = new ActiveXObject("InternetExplorer.Application");
    objIE.Navigate2(arrstrUrl[0]);

    for (intLoop=1;intLoop<=intArrUBound;intLoop++) {

        objIE.Navigate2(arrstrUrl[intLoop], navFlags);

    }

    objIE.Visible = true;
    objIE = null;


VB Script
Create a file with a name like: "urls.vbs":

Option Explicit

Const navOpenInNewWindow = &h1
Const navOpenInNewTab = &h800
Const navOpenInBackgroundTab = &h1000

Dim intLoop       : intLoop = 0
Dim intArrUBound  : intArrUBound = 0
Dim navFlags      : navFlags = navOpenInBackgroundTab

Dim arrstrUrl(3)
Dim objIE

    intArrUBound = UBound(arrstrUrl)

    arrstrUrl(0) = "http://bing.com/"
    arrstrUrl(1) = "http://google.com/"
    arrstrUrl(2) = "http://msn.com/"
    arrstrUrl(3) = "http://yahoo.com/"

    set objIE = CreateObject("InternetExplorer.Application")
    objIE.Navigate2 arrstrUrl(0)

    For intLoop = 1 to intArrUBound

        objIE.Navigate2 arrstrUrl(intLoop), navFlags

    Next

    objIE.Visible = True
    set objIE = Nothing


Once you decide on "JavaScript" or "VB Script", you have a few choices:

If your URLs are static:

1) You could write the "JS/VBS" script file (above) and then just call it from a batch script.

From within the batch script (or command prompt), call the "JS/VBS" script like this:

cscript //nologo urls.vbs
cscript //nologo urls.js


If the URLs change infrequently:

2) You could have the batch script write the "JS/VBS" script on the fly and then call it.


If the URLs could be different each time:

3) Use the "JS/VBS" scripts (below) and pass the URLs of the pages to open as command line arguments:

JavaScript
Create a file with a name like: "urls.js":

var navOpenInNewWindow = 0x1;
var navOpenInNewTab = 0x800;
var navOpenInBackgroundTab = 0x1000;

var intLoop = 0;
var navFlags = navOpenInBackgroundTab;
var objIE;
var intArgsLength = WScript.Arguments.Length;

    if (intArgsLength == 0) {

        WScript.Echo("Missing parameters");
        WScript.Quit(1);

    }

    objIE = new ActiveXObject("InternetExplorer.Application");
    objIE.Navigate2(WScript.Arguments(0));

    for (intLoop=1;intLoop<intArgsLength;intLoop++) {

        objIE.Navigate2(WScript.Arguments(intLoop), navFlags);

    }

    objIE.Visible = true;
    objIE = null;


VB Script
Create a file with a name like: "urls.vbs":

Option Explicit

Const navOpenInNewWindow = &h1
Const navOpenInNewTab = &h800
Const navOpenInBackgroundTab = &h1000

Dim intLoop
Dim navFlags      : navFlags = navOpenInBackgroundTab
Dim objIE

    If WScript.Arguments.Count = 0 Then

        WScript.Echo "Missing parameters"
        WScript.Quit(1)

    End If

    set objIE = CreateObject("InternetExplorer.Application")
    objIE.Navigate2 WScript.Arguments(0)

    For intLoop = 1 to (WScript.Arguments.Count-1)

        objIE.Navigate2 WScript.Arguments(intLoop), navFlags

    Next

    objIE.Visible = True
    set objIE = Nothing


If the script is called without any parameters, these will return %errorlevel%=1, otherwise they will return %errorlevel%=0. No checking is done regarding the "validity" or "availability" of any of the URLs.


From within the batch script (or command prompt), call the "JS/VBS" script like this:

cscript //nologo urls.js "http://bing.com/" "http://google.com/" "http://msn.com/" "http://yahoo.com/"
cscript //nologo urls.vbs "http://bing.com/" "http://google.com/" "http://msn.com/" "http://yahoo.com/"

OR even:

cscript //nologo urls.js "bing.com" "google.com" "msn.com" "yahoo.com"
cscript //nologo urls.vbs "bing.com" "google.com" "msn.com" "yahoo.com"


If for some reason, you wanted to run these with "wscript" instead, remember to use "start /w" so the exit codes (%errorlevel%) will be returned to your batch script:

start /w "" wscript //nologo urls.js "url1" "url2" ...
start /w "" wscript //nologo urls.vbs "url1" "url2" ...


Edit: 21-Sep-2016

There has been a comment that my solution is too complicated. I disagree. You pick the JavaScript solution, or the VB Script solution (not both), and each is only about 10 lines of actual code (less if you eliminate the error checking/reporting), plus a few lines to initialize constants and variables.

Once you have decided (JS or VB), you write that script one time, and then you call that script from batch, passing the URLs, anytime you want to use it, like:

cscript //nologo urls.vbs "bing.com" "google.com" "msn.com" "yahoo.com"

The reason I wrote this answer, is because all the other answers, which work for some people, will fail to work for others, depending on:

  1. The current Internet Explorer settings for "open popups in a new tab", "open in current/new window/tab", etc... Assuming you already have those setting set how you like them for general browsing, most people would find it undesirable to have change those settings back and forth in order to make the script work.
  2. Their behavior is (can be) inconsistent depending on whether or not there was an IE window already open before the "new" links were opened. If there was an IE window (perhaps with many open tabs) already open, then all the new tabs would be added there as well. This might not be desired.

The solution I provided doesn't have these issues and should behave the same, regardless of any IE Settings or any existing IE Windows. (Please let me know if I'm wrong about this and I'll try to address it.)

PHP Session timeout

<?php
session_start();
if($_SESSION['login'] != 'ok')
    header('location: /dashboard.php?login=0');

if(isset($_SESSION['last-activity']) && time() - $_SESSION['last-activity'] > 600) {
    // session inactive more than 10 min
    header('location: /logout.php?timeout=1');
}

$_SESSION['last-activity'] = time(); // update last activity time stamp

if(time() - $_SESSION['created'] > 600) {
    // session started more than 10 min ago
    session_regenerate_id(true); // change session id and invalidate old session
    $_SESSION['created'] = time(); // update creation time
}
?>

Adding a line break in MySQL INSERT INTO text

If you're OK with a SQL command that spreads across multiple lines, then oedo's suggestion is the easiest:

INSERT INTO mytable (myfield) VALUES ('hi this is some text
and this is a linefeed.
and another');

I just had a situation where it was preferable to have the SQL statement all on one line, so I found that a combination of CONCAT_WS() and CHAR() worked for me.

INSERT INTO mytable (myfield) VALUES (CONCAT_WS(CHAR(10 using utf8), 'hi this is some text', 'and this is a linefeed.', 'and another'));

Why am I seeing "TypeError: string indices must be integers"?

This can happen if a comma is missing. I ran into it when I had a list of two-tuples, each of which consisted of a string in the first position, and a list in the second. I erroneously omitted the comma after the first component of a tuple in one case, and the interpreter thought I was trying to index the first component.

How can I get my webapp's base URL in ASP.NET MVC?

You can use the following script in view:

<script type="text/javascript">
    var BASE_URL = '<%= ResolveUrl("~/") %>';
</script>

How to use SSH to run a local shell script on a remote machine?

Also, don't forget to escape variables if you want to pick them up from the destination host.

This has caught me out in the past.

For example:

user@host> ssh user2@host2 "echo \$HOME"

prints out /home/user2

while

user@host> ssh user2@host2 "echo $HOME"

prints out /home/user

Another example:

user@host> ssh user2@host2 "echo hello world | awk '{print \$1}'"

prints out "hello" correctly.

Browser: Identifier X has already been declared

The problem solved when I don't use any declaration like var, let or const

How do I get whole and fractional parts from double in JSP/Java?

double value = 3.25;
double fractionalPart = value % 1;
double integralPart = value - fractionalPart;

Get string between two strings in a string

If you are looking for a 1 line solution, this is it:

s.Substring(s.IndexOf("eT") + "eT".Length).Split("97".ToCharArray()).First()

The whole 1 line solution, with System.Linq:

using System;
using System.Linq;

class OneLiner
{
    static void Main()
    {
        string s = "TextHereTisImortant973End"; //Between "eT" and "97"
        Console.WriteLine(s.Substring(s.IndexOf("eT") + "eT".Length)
                           .Split("97".ToCharArray()).First());
    }
}

Split a vector into chunks

A one-liner splitting d into chunks of size 20:

split(d, ceiling(seq_along(d)/20))

More details: I think all you need is seq_along(), split() and ceiling():

> d <- rpois(73,5)
> d
 [1]  3  1 11  4  1  2  3  2  4 10 10  2  7  4  6  6  2  1  1  2  3  8  3 10  7  4
[27]  3  4  4  1  1  7  2  4  6  0  5  7  4  6  8  4  7 12  4  6  8  4  2  7  6  5
[53]  4  5  4  5  5  8  7  7  7  6  2  4  3  3  8 11  6  6  1  8  4
> max <- 20
> x <- seq_along(d)
> d1 <- split(d, ceiling(x/max))
> d1
$`1`
 [1]  3  1 11  4  1  2  3  2  4 10 10  2  7  4  6  6  2  1  1  2

$`2`
 [1]  3  8  3 10  7  4  3  4  4  1  1  7  2  4  6  0  5  7  4  6

$`3`
 [1]  8  4  7 12  4  6  8  4  2  7  6  5  4  5  4  5  5  8  7  7

$`4`
 [1]  7  6  2  4  3  3  8 11  6  6  1  8  4

How to reshape data from long to wide format

much easier way!

devtools::install_github("yikeshu0611/onetree") #install onetree package

library(onetree)
widedata=reshape_toWide(data = dat1,id = "name",j = "numbers",value.var.prefix = "value")
widedata

        name     value1     value2     value3     value4
   firstName  0.3407997 -0.7033403 -0.3795377 -0.7460474
  secondName -0.8981073 -0.3347941 -0.5013782 -0.1745357

if you want to go back from wide to long, only change Wide to Long, and no changes in objects.

reshape_toLong(data = widedata,id = "name",j = "numbers",value.var.prefix = "value")

        name numbers      value
   firstName       1  0.3407997
  secondName       1 -0.8981073
   firstName       2 -0.7033403
  secondName       2 -0.3347941
   firstName       3 -0.3795377
  secondName       3 -0.5013782
   firstName       4 -0.7460474
  secondName       4 -0.1745357

pip connection failure: cannot fetch index base URL http://pypi.python.org/simple/

I tried almost all answers and nothing fix my error, so I just reinstall python (in my case I have version 2.7.9 and I install 2.7.15) and the error finally fixed. No need to uninstall python first, the installer do it for you.

Specified cast is not valid?

htmlStr is string then You need to Date and Time variables to string

while (reader.Read())
                {
                    DateTime Date = reader.GetDateTime(0);
                    DateTime Time = reader.GetDateTime(1);
                    htmlStr += "<tr><td>" + Date.ToString() + "</td><td>"  + 
                    Time.ToString() + "</td></tr>";                  
                }

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

Here is a regex_subst() function. Examples:

=regex_subst("watermellon", "[aeiou]", "")
---> wtrmlln
=regex_subst("watermellon", "[^aeiou]", "")
---> aeeo

Here is the simplified code (simpler for me, anyway). I couldn't figure out how to build a suitable output pattern using the above to work like my examples:

Function regex_subst( _
     strInput As String _
   , matchPattern As String _
   , Optional ByVal replacePattern As String = "" _
) As Variant
    Dim inputRegexObj As New VBScript_RegExp_55.RegExp

    With inputRegexObj
        .Global = True
        .MultiLine = True
        .IgnoreCase = False
        .Pattern = matchPattern
    End With

    regex_subst = inputRegexObj.Replace(strInput, replacePattern)
End Function

How to use android emulator for testing bluetooth application?

Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux instead of Other.

After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.

Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.

Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.

Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.

In VirtualBox screen, go to Devices>USB devices. Select your dongle.

Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.

Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.

Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .

Source

Linq to Sql: Multiple left outer joins

I am using this linq query for my application. if this match your requirement you can refer this. here i have joined(Left outer join) with 3 tables.

 Dim result = (From csL In contractEntity.CSLogin.Where(Function(cs) cs.Login = login AndAlso cs.Password = password).DefaultIfEmpty
                   From usrT In contractEntity.UserType.Where(Function(uTyp) uTyp.UserTypeID = csL.UserTyp).DefaultIfEmpty ' <== makes join left join
                   From kunD In contractEntity.EmployeeMaster.Where(Function(kunDat) kunDat.CSLoginID = csL.CSLoginID).DefaultIfEmpty
                   Select New With {
                  .CSLoginID = csL.CSLoginID,
                  .UserType = csL.UserTyp}).ToList()

Singleton in Android

answer suggested by rakesh is great but still with some discription Singleton in Android is the same as Singleton in Java: The Singleton design pattern addresses all of these concerns. With the Singleton design pattern you can:

1) Ensure that only one instance of a class is created

2) Provide a global point of access to the object

3) Allow multiple instances in the future without affecting a singleton class's clients

A basic Singleton class example:

public class MySingleton
{
    private static MySingleton _instance;

    private MySingleton()
    {

    }

    public static MySingleton getInstance()
    {
        if (_instance == null)
        {
            _instance = new MySingleton();
        }
        return _instance;
    }
}

How to do a newline in output

Use "\n" instead of '\n'

Unable to install Maven on Windows: "JAVA_HOME is set to an invalid directory"

The JDK has switched locations of java.exe between 1.6 and 1.7!!!

In my case I found that the JAVA_HOME for the JDK had to add the \jre on the end. The mvn bat file is looking for java.exe and it looks for it in JAVA_HOME\bin. Its not there for JDK 1.7; it is in JAVA_HOME\jre\bin. In JDK 1.6 such it IS in JAVA_HOME\bin.

Hope this helps somebody.

Java String.split() Regex

    String str = "a + b - c * d / e < f > g >= h <= i == j";
    String reg = "\\s*[a-zA-Z]+";

    String[] res = str.split(reg);
    for (String out : res) {
        if (!"".equals(out)) {
            System.out.print(out);
        }
    }

Output : + - * / < > >= <= ==

How does Access-Control-Allow-Origin header work?

Nginx and Appache

As addition to apsillers answer I would like to add wiki graph which shows when request is simple or not (and OPTIONS pre-flight request is send or not)

Enter image description here

For simple request (e.g. hotlinking images) you don't need to change your server configuration files but you can add headers in application (hosted on server, e.g. in php) like Melvin Guerrero mention in his answer - but remember: if you add full cors headers in you server (config) and at same time you allow simple cors on application (e.g. php) this will not work at all.

And here are configurations for two popular servers

  • turn on CORS on Nginx (nginx.conf file)

    _x000D_
    _x000D_
    location ~ ^/index\.php(/|$) {
       ...
        add_header 'Access-Control-Allow-Origin' "$http_origin" always; # if you change "$http_origin" to "*" you shoud get same result - allow all domain to CORS (but better change it to your particular domain)
        add_header 'Access-Control-Allow-Credentials' 'true' always;
        if ($request_method = OPTIONS) {
            add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)
            add_header 'Access-Control-Allow-Credentials' 'true';
            add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days
            add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';  # arbitrary methods
            add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin'; # arbitrary headers
            add_header 'Content-Length' 0;
            add_header 'Content-Type' 'text/plain charset=UTF-8';
            return 204;
        }
    }
    _x000D_
    _x000D_
    _x000D_

  • turn on CORS on Appache (.htaccess file)

    _x000D_
    _x000D_
    # ------------------------------------------------------------------------------
    # | Cross-domain Ajax requests                                                 |
    # ------------------------------------------------------------------------------
    
    # Enable cross-origin Ajax requests.
    # http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity
    # http://enable-cors.org/
    
    # change * (allow any domain) below to your domain
    Header set Access-Control-Allow-Origin "*"
    Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"
    Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"
    Header always set Access-Control-Allow-Credentials "true"
    _x000D_
    _x000D_
    _x000D_

How do I remove leading whitespace in Python?

The function strip will remove whitespace from the beginning and end of a string.

my_str = "   text "
my_str = my_str.strip()

will set my_str to "text".

jQuery - disable selected options

pls try this,

$('#select_id option[value="'+value+'"]').attr("disabled", true);

Inserting the iframe into react component

You can use property dangerouslySetInnerHTML, like this

_x000D_
_x000D_
const Component = React.createClass({_x000D_
  iframe: function () {_x000D_
    return {_x000D_
      __html: this.props.iframe_x000D_
    }_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe> tag and pass it to new <iframe> tag, like that

_x000D_
_x000D_
/**_x000D_
 * getAttrs_x000D_
 * returns all attributes from TAG string_x000D_
 * @return Object_x000D_
 */_x000D_
const getAttrs = (iframeTag) => {_x000D_
  var doc = document.createElement('div');_x000D_
  doc.innerHTML = iframeTag;_x000D_
_x000D_
  const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
  return [].slice_x000D_
    .call(iframe.attributes)_x000D_
    .reduce((attrs, element) => {_x000D_
      attrs[element.name] = element.value;_x000D_
      return attrs;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <iframe {...getAttrs(this.props.iframe) } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
_x000D_
_x000D_

Why does 2 mod 4 = 2?

For:

2 mod 4

We can use this little formula I came up with after thinking a bit, maybe it's already defined somewhere I don't know but works for me, and its really useful.

A mod B = C where C is the answer

K * B - A = |C| where K is how many times B fits in A

2 mod 4 would be:

0 * 4 - 2 = |C|

C = |-2| => 2

Hope it works for you :)

How to subtract date/time in JavaScript?

You can use getTime() method to convert the Date to the number of milliseconds since January 1, 1970. Then you can easy do any arithmetic operations with the dates. Of course you can convert the number back to the Date with setTime(). See here an example.

What is the purpose of Looper and how to use it?

A Looper has a synchronized MessageQueue that's used to process Messages placed on the queue.

It implements a Thread Specific Storage Pattern.

Only one Looper per Thread. Key methods include prepare(),loop() and quit().

prepare() initializes the current Thread as a Looper. prepare() is static method that uses the ThreadLocal class as shown below.

   public static void prepare(){
       ...
       sThreadLocal.set
       (new Looper());
   }
  1. prepare() must be called explicitly before running the event loop.
  2. loop() runs the event loop which waits for Messages to arrive on a specific Thread's messagequeue. Once the next Message is received,the loop() method dispatches the Message to its target handler
  3. quit() shuts down the event loop. It doesn't terminate the loop,but instead it enqueues a special message

Looper can be programmed in a Thread via several steps

  1. Extend Thread

  2. Call Looper.prepare() to initialize Thread as a Looper

  3. Create one or more Handler(s) to process the incoming messages

  4. Call Looper.loop() to process messages until the loop is told to quit().

How to get the Facebook user id using the access token

With the newest API, here's the code I used for it

/*params*/
NSDictionary *params = @{
                         @"access_token": [[FBSDKAccessToken currentAccessToken] tokenString],
                         @"fields": @"id"
                         };
/* make the API call */
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
                              initWithGraphPath:@"me"
                              parameters:params
                              HTTPMethod:@"GET"];

[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
                                      id result,
                                      NSError *error) {
    NSDictionary *res = result;
    //res is a dict that has the key
    NSLog([res objectForKey:@"id"]);

How can I change the font size using seaborn FacetGrid?

You can scale up the fonts in your call to sns.set().

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
x = np.random.normal(size=37)
y = np.random.lognormal(size=37)

# defaults
sns.set()
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='small')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.1))

enter image description here

sns.set(font_scale=5)  # crazy big
fig, ax = plt.subplots()
ax.plot(x, y, marker='s', linestyle='none', label='big')
ax.legend(loc='upper left', bbox_to_anchor=(0, 1.3))

enter image description here

jQuery fade out then fade in

This might help: http://jsfiddle.net/danielredwood/gBw9j/
Basically $(this).fadeOut().next().fadeIn(); is what you require

How can I loop over entries in JSON?

Actually, to query the team_name, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.

from urllib2 import urlopen
import json

url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)

for i in json_obj['team']:
    print i['team_name']

When is it acceptable to call GC.Collect?

This isn't that relevant to the question, but for XSLT transforms in .NET (XSLCompiledTranform) then you might have no choice. Another candidate is the MSHTML control.

npm install from Git in a specific version

This command installs npm package username/package from specific git commit:

npm install https://github.com/username/package#3d0a21cc

Here 3d0a21cc is first 8 characters of commit hash.

Splitting string into multiple rows in Oracle

REGEXP_COUNT wasn't added until Oracle 11i. Here's an Oracle 10g solution, adopted from Art's solution.

SELECT trim(regexp_substr('Err1, Err2, Err3', '[^,]+', 1, LEVEL)) str_2_tab
  FROM dual
CONNECT BY LEVEL <=
  LENGTH('Err1, Err2, Err3')
    - LENGTH(REPLACE('Err1, Err2, Err3', ',', ''))
    + 1;

Writing a string to a cell in excel

replace Range("A1") = "Asdf" with Range("A1").value = "Asdf"

What is causing ImportError: No module named pkg_resources after upgrade of Python on os X?

I realize this is not related to OSX, but on an embedded system (Beagle Bone Angstrom) I had the exact same error message. Installing the following ipk packages solved it.

opkg install python-setuptools
opkg install python-pip

get original element from ng-click

Not a direct answer to this question but rather to the "issue" of $event.currentTarget apparently be set to null.

This is due to the fact that console.log shows deep mutable objects at the last state of execution, not at the state when console.log was called.

You can check this for more information: Consecutive calls to console.log produce inconsistent results

If statement in select (ORACLE)

use the variable, Oracle does not support SQL in that context without an INTO. With a properly named variable your code will be more legible anyway.

mysql query result into php array

I think you wanted to do this:

while( $row = mysql_fetch_assoc( $result)){
    $new_array[] = $row; // Inside while loop
}

Or maybe store id as key too

 $new_array[ $row['id']] = $row;

Using the second ways you would be able to address rows directly by their id, such as: $new_array[ 5].

Best way to encode text data for XML in Java?

As others have mentioned, using an XML library is the easiest way. If you do want to escape yourself, you could look into StringEscapeUtils from the Apache Commons Lang library.

How can I convert this one line of ActionScript to C#?

There is collection of Func<...> classes - Func that is probably what you are looking for:

 void MyMethod(Func<int> param1 = null) 

This defines method that have parameter param1 with default value null (similar to AS), and a function that returns int. Unlike AS in C# you need to specify type of the function's arguments.

So if you AS usage was

MyMethod(function(intArg, stringArg) { return true; }) 

Than in C# it would require param1 to be of type Func<int, siring, bool> and usage like

MyMethod( (intArg, stringArg) => { return true;} ); 

Select the top N values by group

There are at least 4 ways to do this thing, however,each has some difference. We using u_id to group and using lift value to order/sort

1 dplyr traditional way

library(dplyr)
top10_final_subset1 = final_subset %>% arrange(desc(lift)) %>% group_by(u_id) %>% slice(1:10)

and if you switch the order of arrange(desc(lift)) and group_by(u_id) the result is essential the same.And if there is tie for equal lift value,it will slice to make sure each group has no more than 10 values, if you only have 5 lift value in the group, it will only gives you 5 results for that group.

2 dplyr topN way

library(dplyr)
top10_final_subset2 = final_subset %>% group_by(u_id) %>% top_n(10,lift)

this one if you have tie in lift value, say 15 same lift for the same u_id, you will got all 15 observations

3 data.table tail way

library(data.table)
final_subset = data.table(final_subset,key = "lift")
top10_final_subset3 = final_subset[,tail(.SD,10),,by = c("u_id")]

It has the same row numbers as the first way, however, there are some rows are different, I guess they are using diff random algorithm dealing with tie.

4 data.table .SD way

library(data.table)
top10_final_subset4 = final_subset[,.SD[order(lift,decreasing = TRUE),][1:10],by = "u_id"]

This way is the most "uniform" way,if in a group there are only 5 observation it will repeat value to make it to 10 observations and if there are ties it will still slice and only hold for 10 observations.

How do you uninstall a python package that was installed using distutils?

In ubuntu 12.04, I have found that the only place you need to look by default is under

/usr/local/lib/python2.7/

And simply remove the associated folder and file, if there is one!

How can I run a PHP script inside a HTML file?

Simply you cant !! but you have some possbile options :

1- Excute php page as external page.

2- write your html code inside the php page itself.

3- use iframe to include the php within the html page.

to be more specific , unless you wanna edit your htaccess file , you may then consider this:

http://php.about.com/od/advancedphp/p/html_php.htm

WPF checkbox binding

if you have the property "MyProperty" on your data-class, then you bind the IsChecked like this.... (the converter is optional, but sometimes you need that)

<Window.Resources>
<local:MyBoolConverter x:Key="MyBoolConverterKey"/>
</Window.Resources>
<checkbox IsChecked="{Binding Path=MyProperty, Converter={StaticResource MyBoolConverterKey}}"/>

jQuery datepicker years shown

If you look down the demo page a bit, you'll see a "Restricting Datepicker" section. Use the dropdown to specify the "Year dropdown shows last 20 years" demo , and hit view source:

$("#restricting").datepicker({ 
    yearRange: "-20:+0", // this is the option you're looking for
    showOn: "both", 
    buttonImage: "templates/images/calendar.gif", 
    buttonImageOnly: true 
});

You'll want to do the same (obviously changing -20 to -100 or something).

What are -moz- and -webkit-?

These are the vendor-prefixed properties offered by the relevant rendering engines (-webkit for Chrome, Safari; -moz for Firefox, -o for Opera, -ms for Internet Explorer). Typically they're used to implement new, or proprietary CSS features, prior to final clarification/definition by the W3.

This allows properties to be set specific to each individual browser/rendering engine in order for inconsistencies between implementations to be safely accounted for. The prefixes will, over time, be removed (at least in theory) as the unprefixed, the final version, of the property is implemented in that browser.

To that end it's usually considered good practice to specify the vendor-prefixed version first and then the non-prefixed version, in order that the non-prefixed property will override the vendor-prefixed property-settings once it's implemented; for example:

.elementClass {
    -moz-border-radius: 2em;
    -ms-border-radius: 2em;
    -o-border-radius: 2em;
    -webkit-border-radius: 2em;
    border-radius: 2em;
}

Specifically, to address the CSS in your question, the lines you quote:

-webkit-column-count: 3;
-webkit-column-gap: 10px;
-webkit-column-fill: auto;
-moz-column-count: 3;
-moz-column-gap: 10px;
-moz-column-fill: auto;

Specify the column-count, column-gap and column-fill properties for Webkit browsers and Firefox.

References:

How do I multiply each element in a list by a number?

I found it interesting to use list comprehension or map with just one object name x. Note that whenever x is reassigned, its id(x) changes, i.e. points to a different object.

x = [1, 2, 3]
id(x)
2707834975552
x = [1.5 * x for x in x]
id(x)
2707834976576
x
[1.5, 3.0, 4.5]
list(map(lambda x : 2 * x / 3, x))
[1.0, 2.0, 3.0]
id(x) # not reassigned
2707834976576
x = list(map(lambda x : 2 * x / 3, x))
x
[1.0, 2.0, 3.0]
id(x)
2707834980928

Create list or arrays in Windows Batch

@echo off
setlocal
set "list=a b c d"
(
 for %%i in (%list%) do (
  echo(%%i
  echo(
 )
)>file.txt

You don't need - actually, can't "declare" variables in batch. Assigning a value to a variable creates it, and assigning an empty string deletes it. Any variable name that doesn't have an assigned value HAS a value of an empty string. ALL variables are strings - WITHOUT exception. There ARE operations that appear to perform (integer) mathematical functions, but they operate by converting back and forth from strings.

Batch is sensitive to spaces in variable names, so your assignment as posted would assign the string "A B C D" - including the quotes, to the variable "list " - NOT including the quotes, but including the space. The syntax set "var=string" is used to assign the value string to var whereas set var=string will do the same thing. Almost. In the first case, any stray trailing spaces after the closing quote are EXCLUDED from the value assigned, in the second, they are INCLUDED. Spaces are a little hard to see when printed.

ECHO echoes strings. Clasically, it is followed by a space - one of the default separators used by batch (the others are TAB, COMMA, SEMICOLON - any of these do just as well BUT TABS often get transformed to a space-squence by text-editors and the others have grown quirks of their own over the years.) Other characters following the O in ECHO have been found to do precisely what the documented SPACE should do. DOT is common. Open-parenthesis ( is probably the most useful since the command

ECHO.%emptyvalue%

will produce a report of the ECHO state (ECHO is on/off) whereas

ECHO(%emptyvalue%

will produce an empty line.

The problem with ECHO( is that the result "looks" unbalanced.

Python 3 Float Decimal Points/Precision

In a word, you can't.

3.65 cannot be represented exactly as a float. The number that you're getting is the nearest number to 3.65 that has an exact float representation.

The difference between (older?) Python 2 and 3 is purely due to the default formatting.

I am seeing the following both in Python 2.7.3 and 3.3.0:

In [1]: 3.65
Out[1]: 3.65

In [2]: '%.20f' % 3.65
Out[2]: '3.64999999999999991118'

For an exact decimal datatype, see decimal.Decimal.

How to delete/remove nodes on Firebase

As others have noted the call to .remove() is asynchronous. We should all be aware nothing happens 'instantly', even if it is at the speed of light.

What you mean by 'instantly' is that the next line of code should be able to execute after the call to .remove(). With asynchronous operations the next line may be when the data has been removed, it may not - it is totally down to chance and the amount of time that has elapsed.

.remove() takes one parameter a callback function to help deal with this situation to perform operations after we know that the operation has been completed (with or without an error). .push() takes two params, a value and a callback just like .remove().

Here is your example code with modifications:

ref = new Firebase("myfirebase.com")

ref.push({key:val}, function(error){
  //do stuff after push completed
});

// deletes all data pushed so far
ref.remove(function(error){
  //do stuff after removal
});

How to add anchor tags dynamically to a div in Javascript?

With jquery

  $("div#id").append('<a href=#>Your LINK TITLE</a>')

With javascript

   var new_a = document.createElement('a');
   new_a.setAttribute("href", "link url here");
   new_a.innerHTML = "your link text";
   //add new link to the DOM
   document.appendChild(new_a);

How to declare a global variable in a .js file

Just define your variables in global.js outside a function scope:

// global.js
var global1 = "I'm a global!";
var global2 = "So am I!";

// other js-file
function testGlobal () {
    alert(global1);
}

To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file:

<html>
    <head>
        <!-- Include global.js first -->
        <script src="/YOUR_PATH/global.js" type="text/javascript"></script>
        <!-- Now we can reference variables, objects, functions etc. 
             defined in global.js -->
        <script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script>
    </head>
    [...]
</html>

You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.

Remove Null Value from String array in java

Those are zero-length strings, not null. But if you want to remove them:

firstArray[0] refers to the first element
firstArray[1] refers to the second element

You can move the second into the first thusly:

firstArray[0]  = firstArray[1]

If you were to do this for elements [1,2], then [2,3], etc. you would eventually shift the entire contents of the array to the left, eliminating element 0. Can you see how that would apply?

What is the difference between gravity and layout_gravity in Android?

Just thought I'd add my own explanation here - coming from a background on iOS, this is how I've internalized the two in iOS terms: "Layout Gravity" affects your position in the superview. "Gravity" affects the position of your subviews within you. Said another way, Layout Gravity positions you yourself while gravity positions your children.

changing visibility using javascript

If you just want to display it when you get a response add this to your loadpage()

function loadpage(page_request, containerid){
   if (page_request.readyState == 4 && page_request.status==200) { 
      var container = document.getElementById(containerid);
      container.innerHTML=page_request.responseText;
      container.style.visibility = 'visible';
      // or 
      container.style.display = 'block';
}

but this depend entirely on how you hid the div in the first place

Is it wrong to place the <script> tag after the </body> tag?

Yes. But if you do add the code outside it most likely will not be the end of the world since most browsers will fix it, but it is still a bad practice to get into.

Writing a dict to txt file and reading it back?

Hi there is a way to write and read the dictionary to file you can turn your dictionary to JSON format and read and write quickly just do this :

To write your date:

 import json

 your_dictionary = {"some_date" : "date"}
 f = open('destFile.txt', 'w+')
 f.write(json.dumps(your_dictionary))

and to read your data:

 import json

 f = open('destFile.txt', 'r')
 your_dictionary = json.loads(f.read())

Can Selenium WebDriver open browser windows silently in the background?

I used this code for Firefox in Windows and got answer(reference here):

from selenium import webdriver
from selenium.webdriver.firefox.options import Options

Options = Options()
Options.headless = True

Driver = webdriver.Firefox(options=Options, executable_path='geckodriver.exe')
Driver.get(...)
...

But I didn't test it for other browsers.

Algorithm: efficient way to remove duplicate integers from an array

A solution suggested by my girlfriend is a variation of merge sort. The only modification is that during the merge step, just disregard duplicated values. This solution would be as well O(n log n). In this approach, the sorting/duplication removal are combined together. However, I'm not sure if that makes any difference, though.

Declaring and using MySQL varchar variables

In Mysql, We can declare and use variables with set command like below

mysql> set @foo="manjeet";
mysql> select * from table where name = @foo;

How do I set a JLabel's background color?

You must set the setOpaque(true) to true other wise the background will not be painted to the form. I think from reading that if it is not set to true that it will paint some or not any of its pixels to the form. The background is transparent by default which seems odd to me at least but in the way of programming you have to set it to true as shown below.

      JLabel lb = new JLabel("Test");
      lb.setBackground(Color.red);
      lb.setOpaque(true); <--This line of code must be set to true or otherwise the 

From the JavaDocs

setOpaque

public void setOpaque(boolean isOpaque)
  If true the component paints every pixel within its bounds. Otherwise, 
  the component may not paint some or all of its pixels, allowing the underlying 
  pixels to show through.
  The default value of this property is false for JComponent. However, 
  the default value for this property on most standard JComponent subclasses 
   (such as JButton and JTree) is look-and-feel dependent.

Parameters:
isOpaque - true if this component should be opaque
See Also:
isOpaque()

jquery how to use multiple ajax calls one after the end of the other

Wrap each ajax call in a named function and just add them to the success callbacks of the previous call:

function callA() {
    $.ajax({
    ...
    success: function() {
      //do stuff
      callB();
    }
    });
}

function callB() {
    $.ajax({
    ...
    success: function() {
        //do stuff
        callC();
    }
    });
}

function callC() {
    $.ajax({
    ...
    });
}


callA();

WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Since .NET 4.5 the Validators use data-attributes and bounded Javascript to do the validation work, so .NET expects you to add a script reference for jQuery.

There are two possible ways to solve the error:


Disable UnobtrusiveValidationMode:

Add this to web.config:

<configuration>
    <appSettings>
        <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
    </appSettings>
</configuration>

It will work as it worked in previous .NET versions and will just add the necessary Javascript to your page to make the validators work, instead of looking for the code in your jQuery file. This is the common solution actually.


Another solution is to register the script:

In Global.asax Application_Start add mapping to your jQuery file path:

void Application_Start(object sender, EventArgs e) 
{
    // Code that runs on application startup
    ScriptManager.ScriptResourceMapping.AddDefinition("jquery", 
    new ScriptResourceDefinition
    {
        Path = "~/scripts/jquery-1.7.2.min.js",
        DebugPath = "~/scripts/jquery-1.7.2.js",
        CdnPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.min.js",
        CdnDebugPath = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.1.js"
    });
}

Some details from MSDN:

ValidationSettings:UnobtrusiveValidationMode Specifies how ASP.NET globally enables the built-in validator controls to use unobtrusive JavaScript for client-side validation logic.

If this key value is set to "None" [default], the ASP.NET application will use the pre-4.5 behavior (JavaScript inline in the pages) for client-side validation logic.

If this key value is set to "WebForms", ASP.NET uses HTML5 data-attributes and late bound JavaScript from an added script reference for client-side validation logic.

INSTALL_FAILED_MISSING_SHARED_LIBRARY error in Android

To get past INSTALL_FAILED_MISSING_SHARED_LIBRARY error with Google Maps for Android:

  1. Install Google map APIs. This can be done in Eclipse Windows/Android SDK and AVD Manager -> Available Packages -> Third Party Add-ons -> Google Inc. -> Google APIs by Google Inc., Android API X

  2. From command line create new AVD. This can be done by listing targets (android list targets), then android create avd -n new_avd_api_233 -t "Google Inc.:Google APIs:X"

  3. Then create AVD (Android Virtual Device) in Eclipse Windows/Android SDK and AVD Manager -> New... -> (Name: new_avd_X, Target: Google APIs (Google Inc.) - API Level X)

    IMPORTANT : You must create your AVD with Target as Google APIs (Google Inc.) otherwise it will again failed.

  4. Create Android Project in Eclipse File/New/Android Project and select Google APIs Build Target.

  5. add <uses-library android:name="com.google.android.maps" /> between <application> </application> tags.

  6. Run Project as Android Application.

If error persists, then you still have problems, if it works, then this error is forever behind you.

Altering user-defined table types in SQL Server

If you can use a Database project in Visual Studio, you can make your changes in the project and use schema compare to synchronize the changes to your database.

This way, dropping and recreating the dependent objects is handled by the change script.

Putting images with options in a dropdown list

This is exactly what you need. See it in action here 8FydL/445

Example's Code below:

_x000D_
_x000D_
     $(".dropdown img.flag").addClass("flagvisibility");_x000D_
        $(".dropdown dt a").click(function() {_x000D_
            $(".dropdown dd ul").toggle();_x000D_
        });_x000D_
                    _x000D_
        $(".dropdown dd ul li a").click(function() {_x000D_
            var text = $(this).html();_x000D_
            $(".dropdown dt a span").html(text);_x000D_
            $(".dropdown dd ul").hide();_x000D_
            $("#result").html("Selected value is: " + getSelectedValue("sample"));_x000D_
        });_x000D_
                    _x000D_
        function getSelectedValue(id) {_x000D_
            return $("#" + id).find("dt a span.value").html();_x000D_
        }_x000D_
    _x000D_
        $(document).bind('click', function(e) {_x000D_
            var $clicked = $(e.target);_x000D_
            if (! $clicked.parents().hasClass("dropdown"))_x000D_
                $(".dropdown dd ul").hide();_x000D_
        });_x000D_
    _x000D_
        $(".dropdown img.flag").toggleClass("flagvisibility");
_x000D_
    .desc { color:#6b6b6b;}_x000D_
    .desc a {color:#0092dd;}_x000D_
    _x000D_
    .dropdown dd, .dropdown dt, .dropdown ul { margin:0px; padding:0px; }_x000D_
    .dropdown dd { position:relative; }_x000D_
    .dropdown a, .dropdown a:visited { color:#816c5b; text-decoration:none; outline:none;}_x000D_
    .dropdown a:hover { color:#5d4617;}_x000D_
    .dropdown dt a:hover { color:#5d4617; border: 1px solid #d0c9af;}_x000D_
    .dropdown dt a {background:#e4dfcb url('http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/arrow.png') no-repeat scroll right center; display:block; padding-right:20px;_x000D_
                    border:1px solid #d4ca9a; width:150px;}_x000D_
    .dropdown dt a span {cursor:pointer; display:block; padding:5px;}_x000D_
    .dropdown dd ul { background:#e4dfcb none repeat scroll 0 0; border:1px solid #d4ca9a; color:#C5C0B0; display:none;_x000D_
                      left:0px; padding:5px 0px; position:absolute; top:2px; width:auto; min-width:170px; list-style:none;}_x000D_
    .dropdown span.value { display:none;}_x000D_
    .dropdown dd ul li a { padding:5px; display:block;}_x000D_
    .dropdown dd ul li a:hover { background-color:#d0c9af;}_x000D_
    _x000D_
    .dropdown img.flag { border:none; vertical-align:middle; margin-left:10px; }_x000D_
    .flagvisibility { display:none;}
_x000D_
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>_x000D_
        <dl id="sample" class="dropdown">_x000D_
            <dt><a href="#"><span>Please select the country</span></a></dt>_x000D_
            <dd>_x000D_
                <ul>_x000D_
                    <li><a href="#">Brazil<img class="flag" src="http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/br.png" alt="" /><span class="value">BR</span></a></li>_x000D_
                    <li><a href="#">France<img class="flag" src="http://www.jankoatwarpspeed.com/wp-content/uploads/examples/reinventing-drop-down/fr.png" alt="" /><span class="value">FR</span></a></li>_x000D_
                   _x000D_
                </ul>_x000D_
            </dd>_x000D_
        </dl>_x000D_
        <span id="result"></span>
_x000D_
_x000D_
_x000D_

SQL UPDATE all values in a field with appended string CONCAT not working

CONCAT with a null value returns null, so the easiest solution is:

UPDATE myTable SET spares = IFNULL (CONCAT( spares , "string" ), "string")

Getting all types in a namespace via reflection

Following code prints names of classes in specified namespace defined in current assembly.
As other guys pointed out, a namespace can be scattered between different modules, so you need to get a list of assemblies first.

string nspace = "...";

var q = from t in Assembly.GetExecutingAssembly().GetTypes()
        where t.IsClass && t.Namespace == nspace
        select t;
q.ToList().ForEach(t => Console.WriteLine(t.Name));

PostgreSQL: role is not permitted to log in

The role you have created is not allowed to log in. You have to give the role permission to log in.

One way to do this is to log in as the postgres user and update the role:

psql -U postgres

Once you are logged in, type:

ALTER ROLE "asunotest" WITH LOGIN;

Here's the documentation http://www.postgresql.org/docs/9.0/static/sql-alterrole.html

Insert current date into a date column using T-SQL?

You could use getdate() in a default as this SO question's accepted answer shows. This way you don't provide the date, you just insert the rest and that date is the default value for the column.

You could also provide it in the values list of your insert and do it manually if you wish.

What is the difference between server side cookie and client side cookie?

All cookies are client and server

There is no difference. A regular cookie can be set server side or client side. The 'classic' cookie will be sent back with each request. A cookie that is set by the server, will be sent to the client in a response. The server only sends the cookie when it is explicitly set or changed, while the client sends the cookie on each request.

But essentially it's the same cookie.

But, behavior can change

A cookie is basically a name=value pair, but after the value can be a bunch of semi-colon separated attributes that affect the behavior of the cookie if it is so implemented by the client (or server). Those attributes can be about lifetime, context and various security settings.

HTTP-only (is not server-only)

One of those attributes can be set by a server to indicate that it's an HTTP-only cookie. This means that the cookie is still sent back and forth, but it won't be available in JavaScript. Do note, though, that the cookie is still there! It's only a built in protection in the browser, but if somebody would use a ridiculously old browser like IE5, or some custom client, they can actually read the cookie!

So it seems like there are 'server cookies', but there are actually not. Those cookies are still sent to the client. On the client there is no way to prevent a cookie from being sent to the server.

Alternatives to achieve 'only-ness'

If you want to store a value only on the server, or only on the client, then you'd need some other kind of storage, like a file or database on the server, or Local Storage on the client.

how to re-format datetime string in php?

why not use date() just like below,try this

$t = strtotime('20130409163705');
echo date('d/m/y H:i:s',$t);

and will be output

09/04/13 16:37:05

Using margin / padding to space <span> from the rest of the <p>

Use div instead of span, or add display: block; to your css style for the span tag.

Overriding a JavaScript function while referencing the original

You can override a function using a construct like:

function override(f, g) {
    return function() {
        return g(f);
    };
}

For example:

 a = override(a, function(original_a) {
      if (condition) { new_code(); original_a(); }
      else { original_a(); other_new_code(); }
 });

Edit: Fixed a typo.

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

The class attribute can be used with multiple HTML elements/tags and all will take the effect. Where as the id is meant for a single element/tag and is considered unique.

Moreoever the id has a higher specificity value than the class.

How to list npm user-installed packages?

npm list -g --depth=0
  • npm: the Node package manager command line tool
  • list -g: display a tree of every package found in the user’s folders (without the -g option it only shows the current directory’s packages)
  • depth 0 / — depth=0: avoid including every package’s dependencies in the tree view

Regex for 1 or 2 digits, optional non-alphanumeric, 2 known alphas

^\d{1,2}[\W_]?po$

\d defines a number and {1,2} means 1 or two of the expression before, \W defines a non word character.

nvm is not compatible with the npm config "prefix" option:

Let me describe my situation.

First, check the current config

$ nvm use --delete-prefix v10.7.0
$ npm config list

Then, I found the error config in output:

; project config /mnt/c/Users/paul/.npmrc
prefix = "/mnt/c/Users/paul/C:\\Program Files\\nodejs"

So, I deleted the C:\\Program Files\\nodejs in /mnt/c/Users/paul/.npmrc.

Efficient iteration with index in Scala

How about this?

val a = Array("One", "Two", "Three")
a.foldLeft(0) ((i, x) => {println(i + ": " + x); i + 1;} )

Output:

0: One
1: Two
2: Three

How do I remove the file suffix and path portion from a path string in Bash?

The basename does that, removes the path. It will also remove the suffix if given and if it matches the suffix of the file but you would need to know the suffix to give to the command. Otherwise you can use mv and figure out what the new name should be some other way.

Uninstall all installed gems, in OSX?

I did that not too long ago (same poster-child RVM switcher situation):

gem list | cut -d" " -f1 | sudo xargs gem uninstall -Iax

Takes the list of all gems (incl. version stuff), cuts it to keep only the gem name, then uninstalls all versions of such gems.

The sudo is only useful if you had gems installed system-wide, and should not be included unless necessary.

Django: List field in model?

I think it will help you.

from django.db import models
import ast

class ListField(models.TextField):
    __metaclass__ = models.SubfieldBase
    description = "Stores a python list"

    def __init__(self, *args, **kwargs):
        super(ListField, self).__init__(*args, **kwargs)

    def to_python(self, value):
        if not value:
            value = []

        if isinstance(value, list):
            return value

        return ast.literal_eval(value)

    def get_prep_value(self, value):
        if value is None:
            return value

        return unicode(value)

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

class ListModel(models.Model):
    test_list = ListField()

Example :

>>> ListModel.objects.create(test_list= [[1,2,3], [2,3,4,4]])

>>> ListModel.objects.get(id=1)

>>> o = ListModel.objects.get(id=1)
>>> o.id
1L
>>> o.test_list
[[1, 2, 3], [2, 3, 4, 4]]
>>> 

Installation of VB6 on Windows 7 / 8 / 10

VB6 Installs just fine on Windows 7 (and Windows 8 / Windows 10) with a few caveats.

Here is how to install it:

  • Before proceeding with the installation process below, create a zero-byte file in C:\Windows called MSJAVA.DLL. The setup process will look for this file, and if it doesn't find it, will force an installation of old, old Java, and require a reboot. By creating the zero-byte file, the installation of moldy Java is bypassed, and no reboot will be required.
  • Turn off UAC.
  • Insert Visual Studio 6 CD.
  • Exit from the Autorun setup.
  • Browse to the root folder of the VS6 CD.
  • Right-click SETUP.EXE, select Run As Administrator.
  • On this and other Program Compatibility Assistant warnings, click Run Program.
  • Click Next.
  • Click "I accept agreement", then Next.
  • Enter name and company information, click Next.
  • Select Custom Setup, click Next.
  • Click Continue, then Ok.
  • Setup will "think to itself" for about 2 minutes. Processing can be verified by starting Task Manager, and checking the CPU usage of ACMSETUP.EXE.
  • On the options list, select the following:
    • Microsoft Visual Basic 6.0
    • ActiveX
    • Data Access
    • Graphics
    • All other options should be unchecked.
  • Click Continue, setup will continue.
  • Finally, a successful completion dialog will appear, at which click Ok. At this point, Visual Basic 6 is installed.
  • If you do not have the MSDN CD, clear the checkbox on the next dialog, and click next. You'll be warned of the lack of MSDN, but just click Yes to accept.
  • Click Next to skip the installation of Installshield. This is a really old version you don't want anyway.
  • Click Next again to skip the installation of BackOffice, VSS, and SNA Server. Not needed!
  • On the next dialog, clear the checkbox for "Register Now", and click Finish.
  • The wizard will exit, and you're done. You can find VB6 under Start, All Programs, Microsoft Visual Studio 6. Enjoy!
  • Turn On UAC again

  • You might notice after successfully installing VB6 on Windows 7 that working in the IDE is a bit, well, sluggish. For example, resizing objects on a form is a real pain.
  • After installing VB6, you'll want to change the compatibility settings for the IDE executable.
  • Using Windows Explorer, browse the location where you installed VB6. By default, the path is C:\Program Files\Microsoft Visual Studio\VB98\
  • Right click the VB6.exe program file, and select properties from the context menu.
  • Click on the Compatibility tab.
  • Place a check in each of these checkboxes:
  • Run this program in compatibility mode for Windows XP (Service Pack 3)
    • Disable Visual Themes
    • Disable Desktop Composition
    • Disable display scaling on high DPI settings
    • If you have UAC turned on, it is probably advisable to check the 'Run this program as an Administrator' box

After changing these settings, fire up the IDE, and things should be back to normal, and the IDE is no longer sluggish.

Edit: Updated dead link to point to a different page with the same instructions

Edit: Updated the answer with the actual instructions in the post as the link kept dying

Pandas read in table without headers

Previous answers were good and correct, but in my opinion, an extra names parameter will make it perfect, and it should be the recommended way, especially when the csv has no headers.

Solution

Use usecols and names parameters

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'])

Additional reading

or use header=None to explicitly tells people that the csv has no headers (anyway both lines are identical)

df = pd.read_csv(file_path, usecols=[3,6], names=['colA', 'colB'], header=None)

So that you can retrieve your data by

# with `names` parameter
df['colA']
df['colB'] 

instead of

# without `names` parameter
df[0]
df[1]

Explain

Based on read_csv, when names are passed explicitly, then header will be behaving like None instead of 0, so one can skip header=None when names exist.

What is the difference between Swing and AWT?

The base difference that which already everyone mentioned is that one is heavy weight and other is light weight. Let me explain, basically what the term heavy weight means is that when you're using the awt components the native code used for getting the view component is generated by the Operating System, thats why it the look and feel changes from OS to OS. Where as in swing components its the responsibility of JVM to generate the view for the components. Another statement which i saw is that swing is MVC based and awt is not.

Bootstrap 4, how to make a col have a height of 100%?

I have tried over a half-dozen solutions suggested on Stack Overflow, and the only thing that worked for me was this:

<div class="row" style="display: flex; flex-wrap: wrap">
    <div class="col-md-6">
        Column A
    </div>
    <div class="col-md-6">
        Column B
    </div>
</div>

I got the solution from https://codepen.io/ondrejsvestka/pen/gWPpPo

Note that it seems to affect the column margins. I had to apply adjustments to those.

Perl - If string contains text?

If you just need to search for one string within another, use the index function (or rindex if you want to start scanning from the end of the string):

if (index($string, $substring) != -1) {
   print "'$string' contains '$substring'\n";
}

To search a string for a pattern match, use the match operator m//:

if ($string =~ m/pattern/) {
    print "'$string' matches the pattern\n";       
}

How to set thousands separator in Java?

try this code to format as used in Brazil:

    DecimalFormat df = new DecimalFormat(
      "#,##0.00", 
      new DecimalFormatSymbols(new Locale("pt", "BR")));

    BigDecimal value = new BigDecimal(123456.00);

    System.out.println(df.format(value.floatValue()));

    // results: "123.456,00"

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

For more solution i have completed the solution of (the great) Tiago Gouvêa exposed before only for strings and arrays

i used md_convert_encoding() function instead of utf8_encode(), it works for me : (12 hours loosed ...)

// this object return me a big array who have multiple arrays imbricated

$get_days = program::get_days($ARR, $client);

// and i use this function for well parsing what the server return *

                function convert_to_utf8_recursively($dat){
                      if( is_string($dat) ){
                         return mb_convert_encoding($dat, 'UTF-8', 'UTF-8');
                      }
                      elseif( is_array($dat) ){
                         $ret = [];
                         foreach($dat as $i => $d){
                           $ret[$i] = convert_to_utf8_recursively($d);
                         }
                         return $ret;
                      }
                      else{
                         return $dat;
                      }
                }

                // use 
                $data = convert_to_utf8_recursively($get_days);
  • what the server return * i talk to that because i test the same code in two different servers the first return me a well formatted json , without any function, as we usually do BUT the second server does not send me back anything if I do not apply this function ...

How do I remove a MySQL database?

From the MySQL prompt:

mysql> drop database <db_name>;

How to make a <svg> element expand or contract to its parent container?

What's worked for me recently is to remove all height="" and width="" attributes from the <svg> tag and all child tags. Then you can use scaling using a percentage of the parent container's height or width.

Before:

<svg width="3212" height="3212" viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
   circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>

After:

<svg viewBox="0 0 3212 3212" fill="none" xmlns="http://www.w3.org/2000/svg">
   circle cx="1606" cy="1606" r="1387" stroke="black" stroke-width="438"/>
</svg>

Selecting data frame rows based on partial string match in a column

LIKE should work in sqlite:

require(sqldf)
df <- data.frame(name = c('bob','robert','peter'),id=c(1,2,3))
sqldf("select * from df where name LIKE '%er%'")
    name id
1 robert  2
2  peter  3

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

Convert comma separated string to array in PL/SQL

declare 
    v_str varchar2(100) := '1,2,3,4,6,7,8,9,0,';
    v_str1 varchar2(100); 
    v_comma_pos number := 0;    
    v_start_pos number := 1;
begin             
    loop        
    v_comma_pos := instr(v_str,',',v_start_pos);   
    v_str1 := substr(v_str,v_start_pos,(v_comma_pos - v_start_pos)); 
    dbms_output.put_line(v_str1);     
    if  v_comma_pos = 0 then     
    v_str1 := substr(v_str,v_start_pos);  
    dbms_output.put_line(v_str1);    
    exit;
    end if;    
    v_start_pos := v_comma_pos + 1;  
    if  v_comma_pos = 0 then    
    exit;
    end if;       
    end loop; 
end;

Installing a specific version of angular with angular cli

Specify the version you want in the 'dependencies' section of your package.json, then from your root project folder in the console/terminal run this:

npm install

For example, the following will specifically install v4.3.4

"dependencies": {
    "@angular/common": "4.3.4",
    "@angular/compiler": "4.3.4",
    "@angular/core": "4.3.4",
    "@angular/forms": "4.3.4",
    "@angular/http": "4.3.4",
    "@angular/platform-browser": "4.3.4",
    "@angular/platform-browser-dynamic": "4.3.4",
    "@angular/router": "4.3.4",
  }

You can also add the following modifiers to the version number to vary how specific you need the version to be:

caret ^

Updates you to the most recent major version, as specified by the first number:

^4.3.0

will load the latest 4.x.x release, but will not load 5.x.x

tilde ~

Update you to the most recent minor version, as specified by the second number:

~4.3.0

will load the latest 4.3.x release, but will not load 4.4.x

How to create a md5 hash of a string in C?

I don't know this particular library, but I've used very similar calls. So this is my best guess:

unsigned char digest[16];
const char* string = "Hello World";
struct MD5Context context;
MD5Init(&context);
MD5Update(&context, string, strlen(string));
MD5Final(digest, &context);

This will give you back an integer representation of the hash. You can then turn this into a hex representation if you want to pass it around as a string.

char md5string[33];
for(int i = 0; i < 16; ++i)
    sprintf(&md5string[i*2], "%02x", (unsigned int)digest[i]);

keycode 13 is for which key

That would be the Enter key.

Retrofit 2 - Dynamic URL

If you already have your code setup and you don’t want to make changes on the different interfaces you can, use the solution described in this link. The main point is the method changeApiBaseUrl that updates the URL and recreates the Retrofit builder.

public class ServiceGenerator {  
public static String apiBaseUrl = "http://futurestud.io/api";
private static Retrofit retrofit;

private static Retrofit.Builder builder =
        new Retrofit.Builder()
                .addConverterFactory(GsonConverterFactory.create())
                .baseUrl(apiBaseUrl);

private static OkHttpClient.Builder httpClient =
        new OkHttpClient.Builder();

// No need to instantiate this class.
private ServiceGenerator() {
}

public static void changeApiBaseUrl(String newApiBaseUrl) {
    apiBaseUrl = newApiBaseUrl;

    builder = new Retrofit.Builder()
                    .addConverterFactory(GsonConverterFactory.create())
                    .baseUrl(apiBaseUrl);
}

public static <S> S createService(Class<S> serviceClass, AccessToken token) {
    String authToken = token.getTokenType().concat(token.getAccessToken());
    return createService(serviceClass, authToken);
}

// more methods
// ...
}

You can use it as follows:

public class DynamicBaseUrlActivity extends AppCompatActivity {

public static final String TAG = "CallInstances";
private Callback<ResponseBody> downloadCallback;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_file_upload);

    downloadCallback = new Callback<ResponseBody>() {
        @Override
        public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
            Log.d(TAG, "server contacted at: " + call.request().url());
        }

        @Override
        public void onFailure(Call<ResponseBody> call, Throwable t) {
            Log.d(TAG, "call failed against the url: " + call.request().url());
        }
    };

    // first request
    FileDownloadService downloadService = ServiceGenerator.create(FileDownloadService.class);
    Call<ResponseBody> originalCall = downloadService.downloadFileWithFixedUrl();
    originalCall.enqueue(downloadCallback);

    // change base url
    ServiceGenerator.changeApiBaseUrl("http://development.futurestud.io/api");

    // new request against new base url
    FileDownloadService newDownloadService = ServiceGenerator.create(FileDownloadService.class);
    Call<ResponseBody> newCall = newDownloadService.downloadFileWithFixedUrl();
    newCall.enqueue(downloadCallback);
    }
}

Jump into interface implementation in Eclipse IDE

ctrl + mouse hover + click "Open Implementation"

On ctrl + hover, you should see the following menu:

enter image description here

Tested on Eclipse Mars.2 (4.5.2)

Getting "unixtime" in Java

Avoid the Date object creation w/ System.currentTimeMillis(). A divide by 1000 gets you to Unix epoch.

As mentioned in a comment, you typically want a primitive long (lower-case-l long) not a boxed object long (capital-L Long) for the unixTime variable's type.

long unixTime = System.currentTimeMillis() / 1000L;

Programmatically navigate using react router V4

I struggled with this for a while - something so simple, yet so complicated, because ReactJS is just a completely different way of writing web applications, it's very alien to us older folk!

I created a separate component to abstract the mess away:

// LinkButton.js

import React from "react";
import PropTypes from "prop-types";
import {Route} from 'react-router-dom';

export default class LinkButton extends React.Component {

    render() {
        return (
            <Route render={({history}) => (
                <button {...this.props}
                       onClick={() => {
                           history.push(this.props.to)
                       }}>
                    {this.props.children}
                </button>
            )}/>
        );
    }
}

LinkButton.propTypes = {
    to: PropTypes.string.isRequired
};

Then add it to your render() method:

<LinkButton className="btn btn-primary" to="/location">
    Button Text
</LinkButton>

How to set a variable to current date and date-1 in linux?

You can try:

#!/bin/bash
d=$(date +%Y-%m-%d)
echo "$d"

EDIT: Changed y to Y for 4 digit date as per QuantumFool's comment.

Image encryption/decryption using AES256 symmetric block ciphers

Here is simple code snippet working for AES Encryption and Decryption.

import android.util.Base64;

import java.io.UnsupportedEncodingException;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;

public class AESEncryptionClass {

    private static String INIT_VECTOR_PARAM = "#####";
    private static String PASSWORD = "#####";
    private static String SALT_KEY = "#####";

    private static SecretKeySpec generateAESKey() throws NoSuchAlgorithmException, InvalidKeySpecException {

        // Prepare password and salt key.
        char[] password = new String(Base64.decode(PASSWORD, Base64.DEFAULT)).toCharArray();
        byte[] salt = new String(Base64.decode(SALT_KEY, Base64.DEFAULT)).getBytes(StandardCharsets.UTF_8);

        // Create object of  [Password Based Encryption Key Specification] with required iteration count and key length.
        KeySpec spec = new PBEKeySpec(password, salt, 64, 256);

        // Now create AES Key using required hashing algorithm.
        SecretKey key = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1").generateSecret(spec);

        // Get encoded bytes of secret key.
        byte[] bytesSecretKey = key.getEncoded();

        // Create specification for AES Key.
        SecretKeySpec secretKeySpec = new SecretKeySpec(bytesSecretKey, "AES");
        return secretKeySpec;
    }

    /**
     * Call this method to encrypt the readable plain text and get Base64 of encrypted bytes.
     */
    public static String encryptMessage(String message) throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException {

        byte[] initVectorParamBytes = new String(Base64.decode(INIT_VECTOR_PARAM, Base64.DEFAULT)).getBytes(StandardCharsets.UTF_8);

        Cipher encryptionCipherBlock = Cipher.getInstance("AES/CBC/PKCS5Padding");
        encryptionCipherBlock.init(Cipher.ENCRYPT_MODE, generateAESKey(), new IvParameterSpec(initVectorParamBytes));

        byte[] messageBytes = message.getBytes();
        byte[] cipherTextBytes = encryptionCipherBlock.doFinal(messageBytes);
        String encryptedText = Base64.encodeToString(cipherTextBytes, Base64.DEFAULT);
        return encryptedText;
    }

    /**
     * Call this method to decrypt the Base64 of encrypted message and get readable plain text.
     */
    public static String decryptMessage(String base64Cipher) throws BadPaddingException, IllegalBlockSizeException, NoSuchPaddingException, NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException, InvalidAlgorithmParameterException, InvalidKeyException {

        byte[] initVectorParamBytes = new String(Base64.decode(INIT_VECTOR_PARAM, Base64.DEFAULT)).getBytes(StandardCharsets.UTF_8);

        Cipher decryptionCipherBlock = Cipher.getInstance("AES/CBC/PKCS5Padding");
        decryptionCipherBlock.init(Cipher.DECRYPT_MODE, generateAESKey(), new IvParameterSpec(initVectorParamBytes));

        byte[] cipherBytes = Base64.decode(base64Cipher, Base64.DEFAULT);
        byte[] messageBytes = decryptionCipherBlock.doFinal(cipherBytes);
        String plainText = new String(messageBytes);
        return plainText;
    }
}

Now, call encryptMessage() or decryptMessage() for desired AES Operation with required parameters.

Also, handle the exceptions during AES operations.

Hope it helped...

How can I check the size of a collection within a Django template?

If you tried myList|length and myList|length_is and its not getting desired results, then you should use myList.count

Is there any way to prevent input type="number" getting negative values?

_x000D_
_x000D_
<input type="number" name="credit_days" pattern="[^\-]+" _x000D_
    #credit_days="ngModel" class="form-control" _x000D_
    placeholder="{{ 'Enter credit days' | translate }}" min="0" _x000D_
    [(ngModel)]="provider.credit_days"_x000D_
    onkeypress="return (event.charCode == 8 || event.charCode == 0 || _x000D_
    event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= _x000D_
    57" onpaste="return false">
_x000D_
_x000D_
_x000D_

How can I convert an RGB image into grayscale in Python?

Using this formula

Y' = 0.299 R + 0.587 G + 0.114 B 

We can do

import imageio
import numpy as np
import matplotlib.pyplot as plt

pic = imageio.imread('(image)')
gray = lambda rgb : np.dot(rgb[... , :3] , [0.299 , 0.587, 0.114]) 
gray = gray(pic)  
plt.imshow(gray, cmap = plt.get_cmap(name = 'gray'))

However, the GIMP converting color to grayscale image software has three algorithms to do the task.

Can I use Homebrew on Ubuntu?

I just tried installing it using the ruby command but somehow the dependencies are not resolved hence brew does not completely install. But, try installing by cloning:

git clone https://github.com/Homebrew/linuxbrew.git ~/.linuxbrew

and then add the following to your .bash_profile:

export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"

It should work..

Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?

I've seen it used when the number of conditions can be variable.

You can concatenate conditions using an " AND " string. Then, instead of counting the number of conditions you're passing in, you place a "WHERE 1=1" at the end of your stock SQL statement and throw on the concatenated conditions.

Basically, it saves you having to do a test for conditions and then add a "WHERE" string before them.