Programs & Examples On #Streaming radio

Change Volley timeout duration

Another way of doing it is in custom JsonObjectRequest by:

@Override
public RetryPolicy getRetryPolicy() {
    // here you can write a custom retry policy and return it
    return super.getRetryPolicy();
}

Source: Android Volley Example

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

Disable browsers vertical and horizontal scrollbars

So far we have overflow:hidden on the body. However IE doesn't always honor that and you need to put scroll="no" on the body element as well and/or place overflow:hidden on the html element as well.

You can take this further when you need to 'take control' of the view port you can do this:-

<style>
 body {width:100%; height:100%; overflow:hidden; margin:0; }
 html {width:100%; height:100%; overflow:hidden; }
</style>

An element granted height 100% in the body has the full height of the window viewport, and element positioned absolutely using bottom:nnPX will be set nn pixels above the bottom edge of the window, etc.

Attributes / member variables in interfaces?

Fields in interfaces are implicitly public static final. (Also methods are implicitly public, so you can drop the public keyword.) Even if you use an abstract class instead of an interface, I strongly suggest making all non-constant (public static final of a primitive or immutable object reference) private. More generally "prefer composition to inheritance" - a Tile is-not-a Rectangle (of course, you can play word games with "is-a" and "has-a").

How to convert milliseconds to seconds with precision

Why don't you simply try

System.out.println(1500/1000.0);
System.out.println(500/1000.0);

How can I get the error message for the mail() function?

As the others have said, there is no error tracking for send mail it return the boolean result of adding the mail to the outgoing queue. If you want to track true success failure try using SMTP with a mail library like Swift Mailer, Zend_Mail, or phpmailer.

Is there a Wikipedia API?

JWPL - Java-based Wikipedia Library -- An application programming interface for Wikipedia

http://code.google.com/p/jwpl/

Modify XML existing content in C#

Forming a XML file

XmlTextWriter xmlw = new XmlTextWriter(@"C:\WINDOWS\Temp\exm.xml",System.Text.Encoding.UTF8);
xmlw.WriteStartDocument();            
xmlw.WriteStartElement("examtimes");
xmlw.WriteStartElement("Starttime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Changetime");
xmlw.WriteString(DateTime.Now.AddHours(0).ToString());
xmlw.WriteEndElement();
xmlw.WriteStartElement("Endtime");
xmlw.WriteString(DateTime.Now.AddHours(1).ToString());
xmlw.WriteEndElement();
xmlw.WriteEndElement();
xmlw.WriteEndDocument();  
xmlw.Close();           

To edit the Xml nodes use the below code

XmlDocument doc = new XmlDocument(); 
doc.Load(@"C:\WINDOWS\Temp\exm.xml"); 
XmlNode root = doc.DocumentElement["Starttime"]; 
root.FirstChild.InnerText = "First"; 
XmlNode root1 = doc.DocumentElement["Changetime"]; 
root1.FirstChild.InnerText = "Second"; 
doc.Save(@"C:\WINDOWS\Temp\exm.xml"); 

Try this. It's C# code.

How to set textColor of UILabel in Swift

The easiest workaround is create dummy labels in IB, give them the text the color you like and set to hidden. You can then reference this color in your code to set your label to the desired color.

yourLabel.textColor = hiddenLabel.textColor

The only way I could change the text color programmatically was by using the standard colors, UIColor.white, UIColor.green...

How do I get the total Json record count using JQuery?

The OP is trying to count the number of properties in a JSON object. This could be done with an incremented temp variable in the iterator, but he seems to want to know the count before the iteration begins. A simple function that meets the need is provided at the bottom of this page.

Here's a cut and paste of the code, which worked for me:

function countProperties(obj) {
  var prop;
  var propCount = 0;

  for (prop in obj) {
    propCount++;
  }
  return propCount;
}

This should work well for a JSON object. For other objects, which may derive properties from their prototype chain, you would need to add a hasOwnProperty() test.

How do I add a Maven dependency in Eclipse?

I have faced same problem with maven dependencies, eg: unfortunetly your maven dependencies deleted from your buildpath,then you people get lot of exceptions,if you follow below process you can easily resolve this issue.

 Right click on project >> maven >> updateProject >> selectProject >> OK

iPhone - Get Position of UIView within entire UIWindow

Swift 5+:

let globalPoint = aView.superview?.convert(aView.frame.origin, to: nil)

Can I give a default value to parameters or optional parameters in C# functions?

This is a feature of C# 4.0, but was not possible without using function overload prior to that version.

How to check if a file exists in a shell script

You're missing a required space between the bracket and -e:

#!/bin/bash
if [ -e x.txt ]
then
    echo "ok"
else
    echo "nok"
fi

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

how to load CSS file into jsp

I use this version

<style><%@include file="/WEB-INF/css/style.css"%></style>

How to query between two dates using Laravel and Eloquent?

If you want to check if current date exist in between two dates in db: =>here the query will get the application list if employe's application from and to date is exist in todays date.

$list=  (new LeaveApplication())
            ->whereDate('from','<=', $today)
            ->whereDate('to','>=', $today)
            ->get();

What is the argument for printf that formats a long?

On most platforms, long and int are the same size (32 bits). Still, it does have its own format specifier:

long n;
unsigned long un;
printf("%ld", n); // signed
printf("%lu", un); // unsigned

For 64 bits, you'd want a long long:

long long n;
unsigned long long un;
printf("%lld", n); // signed
printf("%llu", un); // unsigned

Oh, and of course, it's different in Windows:

printf("%l64d", n); // signed
printf("%l64u", un); // unsigned

Frequently, when I'm printing 64-bit values, I find it helpful to print them in hex (usually with numbers that big, they are pointers or bit fields).

unsigned long long n;
printf("0x%016llX", n); // "0x" followed by "0-padded", "16 char wide", "long long", "HEX with 0-9A-F"

will print:

0x00000000DEADBEEF

Btw, "long" doesn't mean that much anymore (on mainstream x64). "int" is the platform default int size, typically 32 bits. "long" is usually the same size. However, they have different portability semantics on older platforms (and modern embedded platforms!). "long long" is a 64-bit number and usually what people meant to use unless they really really knew what they were doing editing a piece of x-platform portable code. Even then, they probably would have used a macro instead to capture the semantic meaning of the type (eg uint64_t).

char c;       // 8 bits
short s;      // 16 bits
int i;        // 32 bits (on modern platforms)
long l;       // 32 bits
long long ll; // 64 bits 

Back in the day, "int" was 16 bits. You'd think it would now be 64 bits, but no, that would have caused insane portability issues. Of course, even this is a simplification of the arcane and history-rich truth. See wiki:Integer

How can I update window.location.hash without jumping the document?

The problem is you are setting the window.location.hash to an element's ID attribute. It is the expected behavior for the browser to jump to that element, regardless of whether you "preventDefault()" or not.

One way to get around this is to prefix the hash with an arbitrary value like so:

window.location.hash = 'panel-' + id.replace('#', '');

Then, all you need to do is to check for the prefixed hash on page load. As an added bonus, you can even smooth scroll to it since you are now in control of the hash value...

$(function(){
    var h = window.location.hash.replace('panel-', '');
    if (h) {
        $('#slider').scrollTo(h, 800);
    }
});

If you need this to work at all times (and not just on the initial page load), you can use a function to monitor changes to the hash value and jump to the correct element on-the-fly:

var foundHash;
setInterval(function() {
    var h = window.location.hash.replace('panel-', '');
    if (h && h !== foundHash) {
        $('#slider').scrollTo(h, 800);
        foundHash = h;
    }
}, 100);

What's the difference between setWebViewClient vs. setWebChromeClient?

WebViewClient provides the following callback methods, with which you can interfere in how WebView makes a transition to the next content.

void doUpdateVisitedHistory (WebView view, String url, boolean isReload)
void onFormResubmission (WebView view, Message dontResend, Message resend)
void onLoadResource (WebView view, String url)
void onPageCommitVisible (WebView view, String url)
void onPageFinished (WebView view, String url)
void onPageStarted (WebView view, String url, Bitmap favicon)
void onReceivedClientCertRequest (WebView view, ClientCertRequest request)
void onReceivedError (WebView view, int errorCode, String description, String failingUrl)
void onReceivedError (WebView view, WebResourceRequest request, WebResourceError error)
void onReceivedHttpAuthRequest (WebView view, HttpAuthHandler handler, String host, String realm)
void onReceivedHttpError (WebView view, WebResourceRequest request, WebResourceResponse errorResponse)
void onReceivedLoginRequest (WebView view, String realm, String account, String args)
void onReceivedSslError (WebView view, SslErrorHandler handler, SslError error)
boolean onRenderProcessGone (WebView view, RenderProcessGoneDetail detail)
void onSafeBrowsingHit (WebView view, WebResourceRequest request, int threatType, SafeBrowsingResponse callback)
void onScaleChanged (WebView view, float oldScale, float newScale)
void onTooManyRedirects (WebView view, Message cancelMsg, Message continueMsg)
void onUnhandledKeyEvent (WebView view, KeyEvent event)
WebResourceResponse shouldInterceptRequest (WebView view, WebResourceRequest request)
WebResourceResponse shouldInterceptRequest (WebView view, String url)
boolean shouldOverrideKeyEvent (WebView view, KeyEvent event)
boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request)
boolean shouldOverrideUrlLoading (WebView view, String url)

WebChromeClient provides the following callback methods, with which your Activity or Fragment can update the surroundings of WebView.

Bitmap getDefaultVideoPoster ()
View getVideoLoadingProgressView ()
void getVisitedHistory (ValueCallback<String[]> callback)
void onCloseWindow (WebView window)
boolean onConsoleMessage (ConsoleMessage consoleMessage)
void onConsoleMessage (String message, int lineNumber, String sourceID)
boolean onCreateWindow (WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg)
void onExceededDatabaseQuota (String url, String databaseIdentifier, long quota, long estimatedDatabaseSize, long totalQuota, WebStorage.QuotaUpdater quotaUpdater)
void onGeolocationPermissionsHidePrompt ()
void onGeolocationPermissionsShowPrompt (String origin, GeolocationPermissions.Callback callback)
void onHideCustomView ()
boolean onJsAlert (WebView view, String url, String message, JsResult result)
boolean onJsBeforeUnload (WebView view, String url, String message, JsResult result)
boolean onJsConfirm (WebView view, String url, String message, JsResult result)
boolean onJsPrompt (WebView view, String url, String message, String defaultValue, JsPromptResult result)
boolean onJsTimeout ()
void onPermissionRequest (PermissionRequest request)
void onPermissionRequestCanceled (PermissionRequest request)
void onProgressChanged (WebView view, int newProgress)
void onReachedMaxAppCacheSize (long requiredStorage, long quota, WebStorage.QuotaUpdater quotaUpdater)
void onReceivedIcon (WebView view, Bitmap icon)
void onReceivedTitle (WebView view, String title)
void onReceivedTouchIconUrl (WebView view, String url, boolean precomposed)
void onRequestFocus (WebView view)
void onShowCustomView (View view, int requestedOrientation, WebChromeClient.CustomViewCallback callback)
void onShowCustomView (View view, WebChromeClient.CustomViewCallback callback)
boolean onShowFileChooser (WebView webView, ValueCallback<Uri[]> filePathCallback, WebChromeClient.FileChooserParams fileChooserParams)

Pass Parameter to Gulp Task

@Ethan's answer would completely work. From my experience, the more node way is to use environment variables. It's a standard way to configure programs deployed on hosting platforms (e.g. Heroku or Dokku).

To pass the parameter from the command line, do it like this:

Development: gulp dev

Production: NODE_ENV=production gulp dev

The syntax is different, but very Unix, and it's compatible with Heroku, Dokku, etc.

You can access the variable in your code at process.env.NODE_ENV

MYAPP=something_else gulp dev

would set

process.env.MYAPP === 'something_else'

This answer might give you some other ideas.

Segmentation fault on large array sizes

In C or C++ local objects are usually allocated on the stack. You are allocating a large array on the stack, more than the stack can handle, so you are getting a stackoverflow.

Don't allocate it local on stack, use some other place instead. This can be achieved by either making the object global or allocating it on the global heap. Global variables are fine, if you don't use the from any other compilation unit. To make sure this doesn't happen by accident, add a static storage specifier, otherwise just use the heap.

This will allocate in the BSS segment, which is a part of the heap:

static int c[1000000];
int main()
{
   cout << "done\n";
   return 0;
}

This will allocate in the DATA segment, which is a part of the heap too:

int c[1000000] = {};
int main()
{
   cout << "done\n";
   return 0;
}

This will allocate at some unspecified location in the heap:

int main()
{
   int* c = new int[1000000];
   cout << "done\n";
   return 0;
}

Show loading gif after clicking form submit using jQuery

The show() method only affects the display CSS setting. If you want to set the visibility you need to do it directly. Also, the .load_button element is a button and does not raise a submit event. You would need to change your selector to the form for that to work:

$('#login_form').submit(function() {
    $('#gif').css('visibility', 'visible');
});

Also note that return true; is redundant in your logic, so it can be removed.

Auto-scaling input[type=text] to width of value?

Input elements do behave differently from other elements, which would do just about what you want if you give them float: left (see http://jsfiddle.net/hEvYj/5/). I do not think that is possible without calculating it in some way with JavaScript (i.e. add 5px to the width per letter in the box).

How do I clear the dropdownlist values on button click event using jQuery?

A shorter alternative to the first solution given by Russ Cam would be:

$('#mySelect').val('');

This assumes you want to retain the list, but make it so that no option is selected.

If you wish to select a particular default value, just pass that value instead of an empty string.

$('#mySelect').val('someDefaultValue');

or to do it by the index of the option, you could do:

$('#mySelect option:eq(0)').attr('selected','selected'); // Select first option

What is the use of System.in.read()?

system.in.read() method reads a byte and returns as an integer but if you enter a no between 1 to 9 ,it will return 48+ values because in ascii code table ,ascii values of 1-9 are 48-57 . hope , it will help.

C - split string into an array of strings

Here is an example of how to use strtok borrowed from MSDN.

And the relevant bits, you need to call it multiple times. The token char* is the part you would stuff into an array (you can figure that part out).

char string[] = "A string\tof ,,tokens\nand some  more tokens";
char seps[]   = " ,\t\n";
char *token;

int main( void )
{
    printf( "Tokens:\n" );
    /* Establish string and get the first token: */
    token = strtok( string, seps );
    while( token != NULL )
    {
        /* While there are tokens in "string" */
        printf( " %s\n", token );
        /* Get next token: */
        token = strtok( NULL, seps );
    }
}

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

Another potential cause for this error: Attempting to get permission for a Facebook app in sandbox mode when the Facebook user is not listed in the app's admins, developers or testers.

AngularJS: ng-show / ng-hide not working with `{{ }}` interpolation

If you want to show/hide an element based on the status of one {{expression}} you can use ng-switch:

<p ng-switch="foo.bar">I could be shown, or I could be hidden</p>

The paragraph will be displayed when foo.bar is true, hidden when false.

encrypt and decrypt md5

It's not possible to decrypt MD5 hash which created. You need all information to decrypt the MD5 value which was used during encryption.

You can use AES algorithm to encrypt and decrypt

JavaScript AES encryption and decryption (Advanced Encryption Standard)

Hibernate Criteria Query to get specific columns

I like this approach because it is simple and clean:

    String getCompaniesIdAndName = " select "
            + " c.id as id, "
            + " c.name as name "
            + " from Company c ";

    @Query(value = getCompaniesWithoutAccount)
    Set<CompanyIdAndName> findAllIdAndName();

    public static interface CompanyIdAndName extends DTO {
        Integer getId();

        String getName();

    }

Split large string in n-size chunks in JavaScript

Here's a solution I came up with for template strings after a little experimenting:

Usage:

chunkString(5)`testing123`

_x000D_
_x000D_
function chunkString(nSize) {_x000D_
    return (strToChunk) => {_x000D_
        let result = [];_x000D_
        let chars = String(strToChunk).split('');_x000D_
_x000D_
        for(let i = 0; i < (String(strToChunk).length / nSize); i++) {_x000D_
            result = result.concat(chars.slice(i*nSize,(i+1)*nSize).join(''));_x000D_
        }_x000D_
        return result_x000D_
    }_x000D_
}_x000D_
_x000D_
document.write(chunkString(5)`testing123`);_x000D_
// returns: testi,ng123_x000D_
_x000D_
document.write(chunkString(3)`testing123`);_x000D_
// returns: tes,tin,g12,3
_x000D_
_x000D_
_x000D_

TypeScript and field initializers

Here's a solution that:

  • doesn't force you to make all fields optional (unlike Partial<...>)
  • differentiates between class methods and fields of function type (unlike the OnlyData<...> solution)
  • provides a nice structure by defining a Params interface
  • doesn't need to repeat variable names & types more than once

The only drawback is that it looks more complicated at first.


// Define all fields here
interface PersonParams {
  id: string
  name?: string
  coolCallback: () => string
}

// extend the params interface with an interface that has
// the same class name as the target class
// (if you omit the Params interface, you will have to redeclare
// all variables in the Person class)
interface Person extends PersonParams { }

// merge the Person interface with Person class (no need to repeat params)
// person will have all fields of PersonParams
// (yes, this is valid TS)
class Person {
  constructor(params: PersonParams) {
    // could also do Object.assign(this, params);

    this.id = params.id;
    this.name = params.name;

    // intellisence will expect params
    // to have `coolCallback` but not `sayHello`
    this.coolCallback = params.coolCallback;
  }

  // compatible with functions
  sayHello() {
    console.log(`Hi ${this.name}!`);
  }
}

// you can only export on another line (not `export default class...`)
export default Person;

Setting the default active profile in Spring-boot

you can also have multiple listings in the @Profile annotation

@Profile({"dev","default"})

If you set "default" as an additional value, you don't have to specify spring.profiles.active

Generic htaccess redirect www to non-www

Here are the rules to redirect a www URL to no-www:

#########################
# redirect www to no-www
#########################

RewriteCond %{HTTP_HOST} ^www\.(.+) [NC]
RewriteRule ^(.*) http://%1/$1 [R=301,NE,L]

Here are the rules to redirect a no-www URL to www:

#########################
# redirect no-www to www
#########################

RewriteCond %{HTTP_HOST} ^(?!www\.)(.+) [NC]
RewriteRule ^(.*) http://www.%1/$1 [R=301,NE,L]

Note that I used NE flag to prevent apache from escaping the query string. Without this flag, apache will change the requested URL http://www.example.com/?foo%20bar to http://www.example.com/?foo%2250bar

Why is it said that "HTTP is a stateless protocol"?

I think somebody chose very unfortunate name for STATELESS concept and that's why the whole misunderstanding is caused. It's not about storing any kind of resources, but rather about the relationship between the client and the server.

Client: I'm keeping all the resources on my side and send you the "list" of all the important items which need to processed. Do your job.

Server: All right.. let me take the responsibility on filtering what's important to give you the proper response.

Which means that the server is the "slave" of the client and has to forget about his "master" after each request. Actually, STATELESS refers only to the state of the server.

https://www.ics.uci.edu/~fielding/pubs/dissertation/rest_arch_style.htm#sec_5_1_3

How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?

With $array being the contents of a PSCustomObject, this works:

$dataGridView1.DataSource=[collections.arraylist]($array)
$dataGridView1.Columns | Foreach-Object{$_.AutoSizeMode = [System.Windows.Forms.DataGridViewAutoSizeColumnMode]::AllCells}

How to track down access violation "at address 00000000"

When I've stumbled upon this problem I usually start looking at the places where I FreeAndNil() or just xxx := NIL; variables and the code after that.

When nothing else has helped I've added a Log() function to output messages from various suspect places during execution, and then later looked at that log to trace where in the code the access violation comes.

There are ofcourse many more elegant solutions available for tracing these violations, but if you do not have them at your disposal the old-fashioned trial & error method works fine.

C++ Redefinition Header Files (winsock2.h)

In my project (I use VS 2008 SP1) works next solution:

Header file:

//myclass.h
#pragma once
#define _WINSOCKAPI_
#include <windows.h>

Cpp class:

//myclass.cpp
#include "Util.h"
#include "winsock2class.h"
#pragma comment(lib, "Ws2_32.lib")

where #include "winsock2class.h" mean class which implemented winsock2.h :

//winsock2class.h
#include <winsock2.h>
#include <windows.h>
#pragma comment(lib, "Ws2_32.lib")

RSA Public Key format

Starting from the decoded base64 data of an OpenSSL rsa-ssh Key, i've been able to guess a format:

  • 00 00 00 07: four byte length prefix (7 bytes)
  • 73 73 68 2d 72 73 61: "ssh-rsa"
  • 00 00 00 01: four byte length prefix (1 byte)
  • 25: RSA Exponent (e): 25
  • 00 00 01 00: four byte length prefix (256 bytes)
  • RSA Modulus (n):

    7f 9c 09 8e 8d 39 9e cc d5 03 29 8b c4 78 84 5f
    d9 89 f0 33 df ee 50 6d 5d d0 16 2c 73 cf ed 46 
    dc 7e 44 68 bb 37 69 54 6e 9e f6 f0 c5 c6 c1 d9 
    cb f6 87 78 70 8b 73 93 2f f3 55 d2 d9 13 67 32 
    70 e6 b5 f3 10 4a f5 c3 96 99 c2 92 d0 0f 05 60 
    1c 44 41 62 7f ab d6 15 52 06 5b 14 a7 d8 19 a1 
    90 c6 c1 11 f8 0d 30 fd f5 fc 00 bb a4 ef c9 2d 
    3f 7d 4a eb d2 dc 42 0c 48 b2 5e eb 37 3c 6c a0 
    e4 0a 27 f0 88 c4 e1 8c 33 17 33 61 38 84 a0 bb 
    d0 85 aa 45 40 cb 37 14 bf 7a 76 27 4a af f4 1b 
    ad f0 75 59 3e ac df cd fc 48 46 97 7e 06 6f 2d 
    e7 f5 60 1d b1 99 f8 5b 4f d3 97 14 4d c5 5e f8 
    76 50 f0 5f 37 e7 df 13 b8 a2 6b 24 1f ff 65 d1 
    fb c8 f8 37 86 d6 df 40 e2 3e d3 90 2c 65 2b 1f 
    5c b9 5f fa e9 35 93 65 59 6d be 8c 62 31 a9 9b 
    60 5a 0e e5 4f 2d e6 5f 2e 71 f3 7e 92 8f fe 8b
    

The closest validation of my theory i can find it from RFC 4253:

The "ssh-rsa" key format has the following specific encoding:

  string    "ssh-rsa"
  mpint     e
  mpint     n

Here the 'e' and 'n' parameters form the signature key blob.

But it doesn't explain the length prefixes.


Taking the random RSA PUBLIC KEY i found (in the question), and decoding the base64 into hex:

30 82 01 0a 02 82 01 01 00 fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
63 02 03 01 00 01

From RFC3447 - Public-Key Cryptography Standards (PKCS) #1: RSA Cryptography Specifications Version 2.1:

A.1.1 RSA public key syntax

An RSA public key should be represented with the ASN.1 type RSAPublicKey:

  RSAPublicKey ::= SEQUENCE {
     modulus           INTEGER,  -- n
     publicExponent    INTEGER   -- e
  }

The fields of type RSAPublicKey have the following meanings:

  • modulus is the RSA modulus n.
  • publicExponent is the RSA public exponent e.

Using Microsoft's excellent (and the only real) ASN.1 documentation:

30 82 01 0a       ;SEQUENCE (0x010A bytes: 266 bytes)
|  02 82 01 01    ;INTEGER  (0x0101 bytes: 257 bytes)
|  |  00          ;leading zero because high-bit, but number is positive
|  |  fb 11 99 ff 07 33 f6 e8 05 a4 fd 3b 36 ca 68 
|  |  e9 4d 7b 97 46 21 16 21 69 c7 15 38 a5 39 37 2e 27 f3 f5 1d f3 b0 8b 2e 
|  |  11 1c 2d 6b bf 9f 58 87 f1 3a 8d b4 f1 eb 6d fe 38 6c 92 25 68 75 21 2d 
|  |  dd 00 46 87 85 c1 8a 9c 96 a2 92 b0 67 dd c7 1d a0 d5 64 00 0b 8b fd 80 
|  |  fb 14 c1 b5 67 44 a3 b5 c6 52 e8 ca 0e f0 b6 fd a6 4a ba 47 e3 a4 e8 94 
|  |  23 c0 21 2c 07 e3 9a 57 03 fd 46 75 40 f8 74 98 7b 20 95 13 42 9a 90 b0 
|  |  9b 04 97 03 d5 4d 9a 1c fe 3e 20 7e 0e 69 78 59 69 ca 5b f5 47 a3 6b a3 
|  |  4d 7c 6a ef e7 9f 31 4e 07 d9 f9 f2 dd 27 b7 29 83 ac 14 f1 46 67 54 cd 
|  |  41 26 25 16 e4 a1 5a b1 cf b6 22 e6 51 d3 e8 3f a0 95 da 63 0b d6 d9 3e 
|  |  97 b0 c8 22 a5 eb 42 12 d4 28 30 02 78 ce 6b a0 cc 74 90 b8 54 58 1f 0f 
|  |  fb 4b a3 d4 23 65 34 de 09 45 99 42 ef 11 5f aa 23 1b 15 15 3d 67 83 7a 
|  |  63 
|  02 03          ;INTEGER (3 bytes)
|     01 00 01

giving the public key modulus and exponent:

  • modulus = 0xfb1199ff0733f6e805a4fd3b36ca68...837a63
  • exponent = 65,537

Update: My expanded form of this answer in another question

Present and dismiss modal view controller

First of all, when you put that code in applicationDidFinishLaunching, it might be the case that controllers instantiated from Interface Builder are not yet linked to your application (so "red" and "blue" are still nil).

But to answer your initial question, what you're doing wrong is that you're calling dismissModalViewControllerAnimated: on the wrong controller! It should be like this:

[blue presentModalViewController:red animated:YES];
[red dismissModalViewControllerAnimated:YES];

Usually the "red" controller should decide to dismiss himself at some point (maybe when a "cancel" button is clicked). Then the "red" controller could call the method on self:

[self dismissModalViewControllerAnimated:YES];

If it still doesn't work, it might have something to do with the fact that the controller is presented in an animation fashion, so you might not be allowed to dismiss the controller so soon after presenting it.

Making PHP var_dump() values display one line per value

I didn't wanna stop using var_dump($variable);die(); and using pre tags and loops seems overkill to me, so since I am looking at the dump in a browser, I just right click the page and choose Inspect (I use Chrome). The Elements section of the Developer Tools show the variable in a very readable format.

Task vs Thread differences

Source

Thread

Thread represents an actual OS-level thread, with its own stack and kernel resources. (technically, a CLR implementation could use fibers instead, but no existing CLR does this) Thread allows the highest degree of control; you can Abort() or Suspend() or Resume() a thread (though this is a very bad idea), you can observe its state, and you can set thread-level properties like the stack size, apartment state, or culture.

The problem with Thread is that OS threads are costly. Each thread you have consumes a non-trivial amount of memory for its stack, and adds additional CPU overhead as the processor context-switch between threads. Instead, it is better to have a small pool of threads execute your code as work becomes available.

There are times when there is no alternative Thread. If you need to specify the name (for debugging purposes) or the apartment state (to show a UI), you must create your own Thread (note that having multiple UI threads is generally a bad idea). Also, if you want to maintain an object that is owned by a single thread and can only be used by that thread, it is much easier to explicitly create a Thread instance for it so you can easily check whether code trying to use it is running on the correct thread.

ThreadPool

ThreadPool is a wrapper around a pool of threads maintained by the CLR. ThreadPool gives you no control at all; you can submit work to execute at some point, and you can control the size of the pool, but you can't set anything else. You can't even tell when the pool will start running the work you submit to it.

Using ThreadPool avoids the overhead of creating too many threads. However, if you submit too many long-running tasks to the threadpool, it can get full, and later work that you submit can end up waiting for the earlier long-running items to finish. In addition, the ThreadPool offers no way to find out when a work item has been completed (unlike Thread.Join()), nor a way to get the result. Therefore, ThreadPool is best used for short operations where the caller does not need the result.

Task

Finally, the Task class from the Task Parallel Library offers the best of both worlds. Like the ThreadPool, a task does not create its own OS thread. Instead, tasks are executed by a TaskScheduler; the default scheduler simply runs on the ThreadPool.

Unlike the ThreadPool, Task also allows you to find out when it finishes, and (via the generic Task) to return a result. You can call ContinueWith() on an existing Task to make it run more code once the task finishes (if it's already finished, it will run the callback immediately). If the task is generic, ContinueWith() will pass you the task's result, allowing you to run more code that uses it.

You can also synchronously wait for a task to finish by calling Wait() (or, for a generic task, by getting the Result property). Like Thread.Join(), this will block the calling thread until the task finishes. Synchronously waiting for a task is usually bad idea; it prevents the calling thread from doing any other work, and can also lead to deadlocks if the task ends up waiting (even asynchronously) for the current thread.

Since tasks still run on the ThreadPool, they should not be used for long-running operations, since they can still fill up the thread pool and block new work. Instead, Task provides a LongRunning option, which will tell the TaskScheduler to spin up a new thread rather than running on the ThreadPool.

All newer high-level concurrency APIs, including the Parallel.For*() methods, PLINQ, C# 5 await, and modern async methods in the BCL, are all built on Task.

Conclusion

The bottom line is that Task is almost always the best option; it provides a much more powerful API and avoids wasting OS threads.

The only reasons to explicitly create your own Threads in modern code are setting per-thread options, or maintaining a persistent thread that needs to maintain its own identity.

IE Driver download location Link for Selenium

Use the below link to download IE Driver latest version

IE Driver

Font size relative to the user's screen resolution?

New Way

There are several ways to achieve this.

CSS3 supports new dimensions that are relative to view port. But this doesn't work in android.

  1. 3.2vw = 3.2% of width of viewport
  2. 3.2vh = 3.2% of height of viewport
  3. 3.2vmin = Smaller of 3.2vw or 3.2vh
  4. 3.2vmax = Bigger of 3.2vw or 3.2vh

    body
    {
        font-size: 3.2vw;
    }
    

see css-tricks.com/.... and also look at caniuse.com/....

Old Way

  1. Use media query but requires font sizes for several breakpoints

    body
    {
        font-size: 22px; 
    }
    h1
    {
       font-size:44px;
    }
    
    @media (min-width: 768px) 
    {
       body
       {
           font-size: 17px; 
       }
       h1
       {
           font-size:24px;
       }
    }
    
  2. Use dimensions in % or rem. Just change the base font size everything will change. Unlike previous one you could just change the body font and not h1 everytime or let base font size to default of the device and rest all in em.

    • “Root Ems”(rem): The “rem” is a scalable unit. 1rem is equal to the font-size of the body/html, for instance, if the font-size of the document is 12pt, 1em is equal to 12pt. Root Ems are scalable in nature, so 2em would equal 24pt, .5em would equal 6pt, etc..

    • Percent (%): The percent unit is much like the “em” unit, save for a few fundamental differences. First and foremost, the current font-size is equal to 100% (i.e. 12pt = 100%). While using the percent unit, your text remains fully scalable for mobile devices and for accessibility.

see kyleschaeffer.com/....

AngularJS directive does not update on scope variable changes

I needed a solution for this issue as well and I used the answers in this thread to come up with the following:

.directive('tpReport', ['$parse', '$http', '$compile', '$templateCache', function($parse, $http, $compile, $templateCache)
    {
        var getTemplateUrl = function(type)
        {
            var templateUrl = '';

            switch (type)
            {
                case 1: // Table
                    templateUrl = 'modules/tpReport/directives/table-report.tpl.html';
                    break;
                case 0:
                    templateUrl = 'modules/tpReport/directives/default.tpl.html';
                    break;
                default:
                    templateUrl = '';
                    console.log("Type not defined for tpReport");
                    break;
            }

            return templateUrl;
        };

        var linker = function (scope, element, attrs)
        {

            scope.$watch('data', function(){
                var templateUrl = getTemplateUrl(scope.data[0].typeID);
                var data = $templateCache.get(templateUrl);
                element.html(data);
                $compile(element.contents())(scope);

            });



        };

        return {
            controller: 'tpReportCtrl',
            template: '<div>{{data}}</div>',
            // Remove all existing content of the directive.
            transclude: true,
            restrict: "E",
            scope: {
                data: '='
            },
            link: linker
        };
    }])
    ;

Include in your html:

<tp-report data='data'></tp-report>

This directive is used for dynamically loading report templates based on the dataset retrieved from the server.

It sets a watch on the scope.data property and whenever this gets updated (when the users requests a new dataset from the server) it loads the corresponding directive to show the data.

How to get coordinates of an svg element?

The element.getBoundingClientRect() method will return the proper coordinates of an element relative to the viewport regardless of whether the svg has been scaled and/or translated.

See this question and answer.

While getBBox() works for an untransformed space, if scale and translation have been applied to the layout then it will no longer be accurate. The getBoundingClientRect() function has worked well for me in a force layout project when pan and zoom are in effect, where I wanted to attach HTML Div elements as labels to the nodes instead of using SVG Text elements.

ruby 1.9: invalid byte sequence in UTF-8

In Ruby 1.9.3 it is possible to use String.encode to "ignore" the invalid UTF-8 sequences. Here is a snippet that will work both in 1.8 (iconv) and 1.9 (String#encode) :

require 'iconv' unless String.method_defined?(:encode)
if String.method_defined?(:encode)
  file_contents.encode!('UTF-8', 'UTF-8', :invalid => :replace)
else
  ic = Iconv.new('UTF-8', 'UTF-8//IGNORE')
  file_contents = ic.iconv(file_contents)
end

or if you have really troublesome input you can do a double conversion from UTF-8 to UTF-16 and back to UTF-8:

require 'iconv' unless String.method_defined?(:encode)
if String.method_defined?(:encode)
  file_contents.encode!('UTF-16', 'UTF-8', :invalid => :replace, :replace => '')
  file_contents.encode!('UTF-8', 'UTF-16')
else
  ic = Iconv.new('UTF-8', 'UTF-8//IGNORE')
  file_contents = ic.iconv(file_contents)
end

C# 4.0 optional out/ref arguments

ICYMI: Included on the new features for C# 7.0 enumerated here, "discards" is now allowed as out parameters in the form of a _, to let you ignore out parameters you don’t care about:

p.GetCoordinates(out var x, out _); // I only care about x

P.S. if you're also confused with the part "out var x", read the new feature about "Out Variables" on the link as well.

Pylint "unresolved import" error in Visual Studio Code

My solution

This solution is only for the current project.

  1. In the project root, create folder .vscode

  2. Then create the file .vscode/settings.json

  3. In the file setting.json, add the line (this is for Python 3)

    {
        "python.pythonPath": "/usr/local/bin/python3",
    }
    
  4. This is the example for Python 2

    {
        "python.pythonPath": "/usr/local/bin/python",
    }
    
  5. If you don't know where your Python installation is located, just run the command which python or which python3 on the terminal. It will print the Python location.

  6. This example works for dockerized Python - Django.

force css grid container to fill full screen of device

If you want the .wrapper to be fullscreen, just add the following in the wrapper class:

position: absolute; width: 100%; height: 100%;

You can also add top: 0 and left:0

How to zoom div content using jquery?

 $('image').animate({ 'zoom': 1}, 400);

How to use SQL Select statement with IF EXISTS sub query?

Use CASE:

SELECT 
  TABEL1.Id, 
  CASE WHEN EXISTS (SELECT Id FROM TABLE2 WHERE TABLE2.ID = TABLE1.ID)
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1

If TABLE2.ID is Unique or a Primary Key, you could also use this:

SELECT 
  TABEL1.Id, 
  CASE WHEN TABLE2.ID IS NOT NULL
       THEN 'TRUE' 
       ELSE 'FALSE'
  END AS NewFiled  
FROM TABLE1
  LEFT JOIN Table2
    ON TABLE2.ID = TABLE1.ID

How to load local file in sc.textFile, instead of HDFS

This has been discussed into spark mailing list, and please refer this mail.

You should use hadoop fs -put <localsrc> ... <dst> copy the file into hdfs:

${HADOOP_COMMON_HOME}/bin/hadoop fs -put /path/to/README.md README.md

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

I don't think you need the trailing slash in the URL entry. Ie, put this instead:

(r'^led-tv$', filter_by_led ),

This is assuming you have trailing slashes enabled, which is the default.

Pattern matching using a wildcard

If you really do want to use wildcards to identify specific variables, then you can use a combination of ls() and grep() as follows:

l = ls()
vars.with.result <- l[grep("result", l)]

What is the difference between .text, .value, and .value2?

target.Value will give you a Variant type

target.Value2 will give you a Variant type as well but a Date is coerced to a Double

target.Text attempts to coerce to a String and will fail if the underlying Variant is not coercable to a String type

The safest thing to do is something like

Dim v As Variant
v = target.Value 'but if you don't want to handle date types use Value2

And check the type of the variant using VBA.VarType(v) before you attempt an explicit coercion.

How to get the ActionBar height?

A ready method to fulfill the most popular answer:

public static int getActionBarHeight(
  Activity activity) {

  int actionBarHeight = 0;
  TypedValue typedValue = new TypedValue();

  try {

    if (activity
      .getTheme()
      .resolveAttribute(
        android.R.attr.actionBarSize,
        typedValue,
        true)) {

      actionBarHeight =
        TypedValue.complexToDimensionPixelSize(
          typedValue.data,
          activity
            .getResources()
            .getDisplayMetrics());
    }

  } catch (Exception ignore) {
  }

  return actionBarHeight;
}

Disable Proximity Sensor during call

I found my solution here. Basically use an app called Proximity Screen Off Lite and set it as below:

  1. Screen On/Off Modes Check "Cover and hold to turn on Screen" Timeout: 1 second Check "Disable Accidentla Lock" Timeout: 4 seconds

  2. All settings Check "Disable in Lanscape" Check "Lock phone on screen ON"

  3. [Advanced] Configure Sensore Select sensor: Proximity sensor Value when sensor covered: 0 Value when sensor un-covered: 1

How to set Navigation Drawer to be opened from right to left

This answer is useful to set the navigation be open from right to left, but it has no solution to set its icon to be right side. This code can fix it. If you give it the drawer as its first param and ViewCompat.LAYOUT_DIRECTION_RTL as its second param, the entier layout will be set to RTL. It is a quick and simple solution, but I don't think it can be a correct solution for who that want to only set the menu to be opened from right to left and set its icon to be on right side. (Although, it's depended to your purpose.) However, I suggest giving the toolbar instead of the drawer. In this way just the toolbar has become RTL. So I think the combination of these 2 answers can exactly do what you want.

According to these descriptions, your code should be like this:

(Add these lines to onCreate method)

final DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout); // Set it final to fix the error that will be mention below.

    ViewCompat.setLayoutDirection(toolbar, ViewCompat.LAYOUT_DIRECTION_RTL);

    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (drawer.isDrawerOpen(Gravity.RIGHT))
                drawer.closeDrawer(Gravity.RIGHT);
            else
                drawer.openDrawer(Gravity.RIGHT);
        }
    });

Notice that you should make drawer final, otherwise you will get this error:

Variable 'drawer' is accessed from within inner class, needs to be declared final

And don't forget to use end instead of start in onNavigationItemSelected method:

drawer.closeDrawer(GravityCompat.END);

and in your activity_main.xml

<android.support.v4.widget.DrawerLayout 
   android:id="@+id/drawer_layout"
   tools:openDrawer="end">

   <android.support.design.widget.NavigationView
      android:id="@+id/nav_view"
      android:layout_gravity="end"/>
</android.support.v4.widget.DrawerLayout>

Discard all and get clean copy of latest revision?

hg up -C

This will remove all the changes and update to the latest head in the current branch.

And you can turn on purge extension to be able to remove all unversioned files too.

Using Html.ActionLink to call action on different controller

If you grab the MVC Futures assembly (which I would highly recommend) you can then use a generic when creating the ActionLink and a lambda to construct the route:

<%=Html.ActionLink<Product>(c => c.Action( o.Value ), "Details" ) %>

You can get the futures assembly here: http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471

Java: how can I split an ArrayList in multiple small ArrayLists?

    **Divide a list to lists of n size**

    import java.util.AbstractList;
    import java.util.ArrayList;
    import java.util.List;

    public final class PartitionUtil<T> extends AbstractList<List<T>> {

        private final List<T> list;
        private final int chunkSize;

        private PartitionUtil(List<T> list, int chunkSize) {
            this.list = new ArrayList<>(list);
            this.chunkSize = chunkSize;
        }

        public static <T> PartitionUtil<T> ofSize(List<T> list, int chunkSize) {
            return new PartitionUtil<>(list, chunkSize);
        }

        @Override
        public List<T> get(int index) {
            int start = index * chunkSize;
            int end = Math.min(start + chunkSize, list.size());

            if (start > end) {
                throw new IndexOutOfBoundsException("Index " + index + " is out of the list range <0," + (size() - 1) + ">");
            }

            return new ArrayList<>(list.subList(start, end));
        }

        @Override
        public int size() {
            return (int) Math.ceil((double) list.size() / (double) chunkSize);
        }
    }





Function call : 
              List<List<String>> containerNumChunks = PartitionUtil.ofSize(list, 999)

more details: https://e.printstacktrace.blog/divide-a-list-to-lists-of-n-size-in-Java-8/

Why doesn't logcat show anything in my Android?

What worked for me besides restarting eclipse is:

  • Remove custom filters

After removing all filters, logcat was filled with text again Hope this will be helpful to someone else

What is the default text size on Android?

You can find standard sizes for everything in Google's style guide.

Here are the values they use for for buttons:

Buttons

English: Medium 14sp, all caps

Dense: Medium 15sp, all caps

Tall: Bold 15sp

How to Apply Mask to Image in OpenCV?

Well, this question appears on top of search results, so I believe we need code example here. Here's the Python code:

import cv2

def apply_mask(frame, mask):
    """Apply binary mask to frame, return in-place masked image."""
    return cv2.bitwise_and(frame, frame, mask=mask)

Mask and frame must be the same size, so pixels remain as-is where mask is 1 and are set to zero where mask pixel is 0.

And for C++ it's a little bit different:

cv::Mat inFrame; // Original (non-empty) image
cv::Mat mask; // Original (non-empty) mask

// ...

cv::Mat outFrame;  // Result output
inFrame.copyTo(outFrame, mask);

How do I install a color theme for IntelliJ IDEA 7.0.x

Interesting I never spent too much time adjusting the colours in IntelliJ although tried once.

See link below with an already defined colour scheme you can import.

Where can I download IntelliJ IDEA 10 Color Schemes?

http://devnet.jetbrains.net/docs/DOC-1154

Download the jar file, file import the jar where you will see a what to import ;)

enter image description here

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

public Configuration()
{
    AutomaticMigrationsEnabled = false;

    // register mysql code generator

    SetSqlGenerator("MySql.Data.MySqlClient", new MySql.Data.Entity.MySqlMigrationSqlGenerator());
}

I find out that connector 6.6.4 will not work with Entity Framework 5 but with Entity Framework 4.3. So to downgrade issue the following commands in the package manager console:

Uninstall-Package EntityFramework

Install-Package EntityFramework -Version 4.3.1

Finally I do Update-Database -Verbose again and voila! The schema and tables are created. Wait for the next version of connector to use it with Entity Framework 5.

Incrementing in C++ - When to use x++ or ++x?

Postfix form of ++,-- operator follows the rule use-then-change ,

Prefix form (++x,--x) follows the rule change-then-use.

Example 1:

When multiple values are cascaded with << using cout then calculations(if any) take place from right-to-left but printing takes place from left-to-right e.g., (if val if initially 10)

 cout<< ++val<<" "<< val++<<" "<< val;

will result into

12    10    10 

Example 2:

In Turbo C++, if multiple occurrences of ++ or (in any form) are found in an expression, then firstly all prefix forms are computed then expression is evaluated and finally postfix forms are computed e.g.,

int a=10,b;
b=a++ + ++a + ++a + a;
cout<<b<<a<<endl;

It's output in Turbo C++ will be

48 13

Whereas it's output in modern day compiler will be (because they follow the rules strictly)

45 13
  • Note: Multiple use of increment/decrement operators on same variable in one expression is not recommended. The handling/results of such
    expressions vary from compiler to compiler.

Unable to create a constant value of type Only primitive types or enumeration types are supported in this context

It's worth adding, since the OP's code sample doesn't provide enough context to prove otherwise, but I received this error as well on the following code:

public RetailSale GetByRefersToRetailSaleId(Int32 refersToRetailSaleId)
{
    return GetQueryable()
        .FirstOrDefault(x => x.RefersToRetailSaleId.Equals(refersToRetailSaleId));
}

Apparently, I cannot use Int32.Equals in this context to compare an Int32 with a primitive int; I had to (safely) change to this:

public RetailSale GetByRefersToRetailSaleId(Int32 refersToRetailSaleId)
{
    return GetQueryable()
      .FirstOrDefault(x => x.RefersToRetailSaleId == refersToRetailSaleId);
}

Delete files or folder recursively on Windows CMD

After the blog post How Can I Use Windows PowerShell to Delete All the .TMP Files on a Drive?, you can use something like this to delete all .tmp for example from a folder and all subfolders in PowerShell:

get-childitem [your path/ or leave empty for current path] -include
*.tmp -recurse | foreach ($_) {remove-item $_.fullname}

element with the max height from a set of elements

If you were interested in sorting entirely in standard JavaScript, or without using forEach():

var panels = document.querySelectorAll("div.panel");

// You'll need to slice the node_list before using .map()
var heights = Array.prototype.slice.call(panels).map(function (panel) {
    // return an array to hold the item and its value
    return [panel, panel.offsetHeight];
}),

// Returns a sorted array
var sortedHeights = heights.sort(function(a, b) { return a[1] > b[1]});

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

The method tf.shape is a TensorFlow static method. However, there is also the method get_shape for the Tensor class. See

https://www.tensorflow.org/api_docs/python/tf/Tensor#get_shape

Correct way to write line to file?

This should be as simple as:

with open('somefile.txt', 'a') as the_file:
    the_file.write('Hello\n')

From The Documentation:

Do not use os.linesep as a line terminator when writing files opened in text mode (the default); use a single '\n' instead, on all platforms.

Some useful reading:

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

You are sending one parameter incorrectly; it should be a dictionary object:

  • Wrong: func(a=r)

  • Correct: func(a={'x':y})

Entity Framework: "Store update, insert, or delete statement affected an unexpected number of rows (0)."

This happened to me due to a mismatch between datetime and datetime2. Strangely, it worked fine prior to a tester discovering the issue. My Code First model included a DateTime as part of the primary key:

[Key, Column(Order = 2)]  
public DateTime PurchasedDate { get; set; } = (DateTime)SqlDateTime.MinValue;

The generated column is a datetime column. When calling SaveChanges, EF generated the following SQL:

-- Region Parameters
DECLARE @0 Int = 2
DECLARE @1 Int = 25
DECLARE @2 Int = 141051
DECLARE @3 DateTime2 = '2017-07-27 15:16:09.2630000' --(will not equal a datetime value)
-- EndRegion
UPDATE [dbo].[OrganizationSurvey]
SET [OrganizationSurveyStatusId] = @0
WHERE ((([SurveyID] = @1) AND ([OrganizationID] = @2)) AND ([PurchasedDate] = @3))

Because it was trying to match a datetime column with a datetime2 value, it returned no results. The only solution I could think of was to change the column to a datetime2:

[Key, Column(Order = 2, TypeName = "DateTime2")]  
public DateTime PurchasedDate { get; set; } = (DateTime)SqlDateTime.MinValue;

Giving height to table and row in Bootstrap

http://jsfiddle.net/isherwood/gfgux

html, body {
    height: 100%;
}
#table-row, #table-col, #table-wrapper {
    height: 80%;
}

<div id="content" class="container">
    <div id="table-row" class="row">
        <div id="table-col" class="col-md-7 col-xs-10 pull-left">
            <p>Hello</p>
            <div id="table-wrapper" class="table-responsive">
                <table class="table table-bordered ">

How to subscribe to an event on a service in Angular2?

Using alpha 28, I accomplished programmatically subscribing to event emitters by way of the eventEmitter.toRx().subscribe(..) method. As it is not intuitive, it may perhaps change in a future release.

mysql update multiple columns with same now()

You can store the value of a now() in a variable before running the update query and then use that variable to update both the fields last_update and last_monitor.

This will ensure the now() is executed only once and same value is updated on both columns you need.

How to create a List with a dynamic object type

It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.

Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.

DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj

...

The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.

var DyObjectsList = new List<dynamic>; 
if (condition1) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = true; 
    DyObj.Message = "Message 1"; 
    DyObjectsList .Add(DyObj); 
} 
if (condition2) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = false; 
    DyObj.Message = "Message 2"; 
    DyObjectsList .Add(DyObj); 
} 

your resulting List essentially looks like this

DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj

Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.

However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.

How to create a sticky navigation bar that becomes fixed to the top after scrolling

I have found this simple javascript snippet very useful.

$(document).ready(function()
{
    var navbar = $('#navbar');

    navbar.after('<div id="more-div" style="height: ' + navbar.outerHeight(true) + 'px" class="hidden"></div>');
    var afternavbar = $('#more-div');

    var abovenavbar = $('#above-navbar');

    $(window).on('scroll', function()
    {
        if ($(window).scrollTop() > abovenavbar.height())
        {
            navbar.addClass('navbar-fixed-top');
            afternavbar.removeClass('hidden');
        }
        else
        {
            navbar.removeClass('navbar-fixed-top');
            afternavbar.addClass('hidden');
        }
    });
});

Use sudo with password as parameter

One option is to use the -A flag to sudo. This runs a program to ask for the password. Rather than ask, you could have a script that just spits out the password so the program can continue.

What's the HTML to have a horizontal space between two objects?

Well, this is probably frowned upon but you can make a 1px transparent image, then size it as needed in between text.

Some text <img src="spacer.png" height="1px" width="10px"> Some more text

I've run into this issue when one or two spaces just wasn't enough for my design sensibilities.

What is the --save option for npm install?

npm i (Package name) --save

Simplily, using above command we ll not need to write package name in your package.json file it ll auto add its name and dependency with version that you ll need at time when you go for production or setup another time.

npm help install

Above command ll help find out more option and correct def.shown in pic enter image description here

open() in Python does not create a file if it doesn't exist

import os, platform
os.chdir('c:\\Users\\MS\\Desktop')

try :
    file = open("Learn Python.txt","a")
    print('this file is exist')
except:
    print('this file is not exist')
file.write('\n''Hello Ashok')

fhead = open('Learn Python.txt')

for line in fhead:

    words = line.split()
print(words)

How to get a tab character?

Sure there's an entity for tabs:

&#9;

(The tab is ASCII character 9, or Unicode U+0009.)

However, just like literal tabs (ones you type in to your text editor), all tab characters are treated as whitespace by HTML parsers and collapsed into a single space except those within a <pre> block, where literal tabs will be rendered as 8 spaces in a monospace font.

How to read values from properties file?

You need to put a PropertyPlaceholderConfigurer bean in your application context and set its location property.

See details here : http://www.zparacha.com/how-to-read-properties-file-in-spring/

You might have to modify your property file a bit for this thing to work.

Hope it helps.

Increase max execution time for php

There's probably a limit set in your webserver. Some browsers/proxies will also implement a timeout. Invoking long running processes via an HTTP request is just plain silly. The right way to solve the problem (assuming you can't make the processing any faster) is to use the HTTP request to trigger processing outside of the webserver session group then poll the status via HTTP until you've got a result set.

NPM clean modules

You can take advantage of the 'npm cache' command which downloads the package tarball and unpacks it into the npm cache directory.

The source can then be copied in.

Using ideas gleaned from https://groups.google.com/forum/?fromgroups=#!topic/npm-/mwLuZZkHkfU I came up with the following node script. No warranties, YMMV, etcetera.

var fs = require('fs'),
path = require('path'),
exec = require('child_process').exec,
util = require('util');

var packageFileName = 'package.json';
var modulesDirName = 'node_modules';
var cacheDirectory = process.cwd();
var npmCacheAddMask = 'npm cache add %s@%s; echo %s';
var sourceDirMask = '%s/%s/%s/package';
var targetDirMask = '%s/node_modules/%s';

function deleteFolder(folder) {
    if (fs.existsSync(folder)) {
        var files = fs.readdirSync(folder);
        files.forEach(function(file) {
            file = folder + "/" + file;
            if (fs.lstatSync(file).isDirectory()) {
                deleteFolder(file);
            } else {
                fs.unlinkSync(file);
            }
        });
        fs.rmdirSync(folder);
    }
}

function downloadSource(folder) {
    var packageFile = path.join(folder, packageFileName);
    if (fs.existsSync(packageFile)) {
        var data = fs.readFileSync(packageFile);
        var package = JSON.parse(data);

        function getVersion(data) {
            var version = data.match(/-([^-]+)\.tgz/);
            return version[1];
        }

        var callback = function(error, stdout, stderr) {
            var dependency = stdout.trim();
            var version = getVersion(stderr);
            var sourceDir = util.format(sourceDirMask, cacheDirectory, dependency, version);
            var targetDir = util.format(targetDirMask, folder, dependency);
            var modulesDir = folder + '/' + modulesDirName;

            if (!fs.existsSync(modulesDir)) {
                fs.mkdirSync(modulesDir);
            }

            fs.renameSync(sourceDir, targetDir);
            deleteFolder(cacheDirectory + '/' + dependency);
            downloadSource(targetDir);
        };

        for (dependency in package.dependencies) {
            var version = package.dependencies[dependency];
            exec(util.format(npmCacheAddMask, dependency, version, dependency), callback);
        }
    }
}

if (!fs.existsSync(path.join(process.cwd(), packageFileName))) {
    console.log(util.format("Unable to find file '%s'.", packageFileName));
    process.exit();
}

deleteFolder(path.join(process.cwd(), modulesDirName));
process.env.npm_config_cache = cacheDirectory;
downloadSource(process.cwd());

Android webview & localStorage

I've also had problem with data being lost after application is restarted. Adding this helped:

webView.getSettings().setDatabasePath("/data/data/" + webView.getContext().getPackageName() + "/databases/");

CSS: 100% font size - 100% of what?

As you showed convincingly, the font-size: 100%; will not render the same in all browsers. However, you will set your font face in your CSS file, so this will be the same (or a fallback) in all browsers.

I believe font-size: 100%; can be very useful when combining it with em-based design. As this article shows, this will create a very flexible website.

When is this useful? When your site needs to adapt to the visitors' wishes. Take for example an elderly man that puts his default font-size at 24 px. Or someone with a small screen with a large resolution that increases his default font-size because he otherwise has to squint. Most sites would break, but em-based sites are able to cope with these situations.

java.lang.RuntimeException: Uncompilable source code - what can cause this?

If it is Netbeans, try to uncheck "Compile on save" setting in the project properties (Build -> Compiling). This is the only thing which helped me in a similar situation.

Generic XSLT Search and Replace template

Here's one way in XSLT 2

<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;','''')"/>   </xsl:template> </xsl:stylesheet> 

Doing it in XSLT1 is a little more problematic as it's hard to get a literal containing a single apostrophe, so you have to resort to a variable:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">   <xsl:template match="@*|node()">     <xsl:copy>       <xsl:apply-templates select="@*|node()"/>     </xsl:copy>   </xsl:template>   <xsl:variable name="apos">'</xsl:variable>   <xsl:template match="text()">     <xsl:value-of select="translate(.,'&quot;',$apos)"/>   </xsl:template> </xsl:stylesheet> 

Differences between socket.io and websockets

Its advantages are that it simplifies the usage of WebSockets as you described in #2, and probably more importantly it provides fail-overs to other protocols in the event that WebSockets are not supported on the browser or server. I would avoid using WebSockets directly unless you are very familiar with what environments they don't work and you are capable of working around those limitations.

This is a good read on both WebSockets and Socket.IO.

http://davidwalsh.name/websocket

Android Studio : Failure [INSTALL_FAILED_OLDER_SDK]

One more place where minSdkVersion makes a sense is a flavor:

productFlavors {
    dev {
        minSdkVersion 22
    }
    prod {
        minSdkVersion 9
    }
}

minSdkVersion (22) will not install on development devices with API level older than 22.

Can the :not() pseudo-class have multiple arguments?

If you're using SASS in your project, I've built this mixin to make it work the way we all want it to:

@mixin not($ignorList...) {
    //if only a single value given
    @if (length($ignorList) == 1){
        //it is probably a list variable so set ignore list to the variable
        $ignorList: nth($ignorList,1);
    }
    //set up an empty $notOutput variable
    $notOutput: '';
    //for each item in the list
    @each $not in $ignorList {
        //generate a :not([ignored_item]) segment for each item in the ignore list and put them back to back
        $notOutput: $notOutput + ':not(#{$not})';
    }
    //output the full :not() rule including all ignored items
    &#{$notOutput} {
        @content;
    }
}

it can be used in 2 ways:

Option 1: list the ignored items inline

input {
  /*non-ignored styling goes here*/
  @include not('[type="radio"]','[type="checkbox"]'){
    /*ignored styling goes here*/
  }
}

Option 2: list the ignored items in a variable first

$ignoredItems:
  '[type="radio"]',
  '[type="checkbox"]'
;

input {
  /*non-ignored styling goes here*/
  @include not($ignoredItems){
    /*ignored styling goes here*/
  }
}

Outputted CSS for either option

input {
    /*non-ignored styling goes here*/
}

input:not([type="radio"]):not([type="checkbox"]) {
    /*ignored styling goes here*/
}

How do I find which transaction is causing a "Waiting for table metadata lock" state?

If you cannot find the process locking the table (cause it is alreay dead), it may be a thread still cleaning up like this

section TRANSACTION of

show engine innodb status;

at the end

---TRANSACTION 1135701157, ACTIVE 6768 sec
MySQL thread id 5208136, OS thread handle 0x7f2982e91700, query id 882213399 xxxIPxxx 82.235.36.49 my_user cleaning up

as mentionned in a comment in Clear transaction deadlock?

you can try killing the transaction thread directly, here with

 KILL 5208136;

worked for me.

Continue For loop

This can also be solved using a boolean.

For Each rngCol In rngAll.Columns
    doCol = False '<==== Resets to False at top of each column
    For Each cell In Selection
        If cell.row = 1 Then
            If thisColumnShouldBeProcessed Then doCol = True
        End If
        If doCol Then
            'Do what you want to do to each cell in this column
        End If
    Next cell
Next rngCol

For example, here is the full example that:
(1) Identifies range of used cells on worksheet
(2) Loops through each column
(3) IF column title is an accepted title, Loops through all cells in the column

Sub HowToSkipForLoopIfConditionNotMet()
    Dim rngCol, rngAll, cell As Range, cnt As Long, doCol, cellValType As Boolean
    Set rngAll = Range("A1").CurrentRegion
    'MsgBox R.Address(0, 0), , "All data"
    cnt = 0
    For Each rngCol In rngAll.Columns
        rngCol.Select
        doCol = False
        For Each cell In Selection
            If cell.row = 1 Then
                If cell.Value = "AnAllowedColumnTitle" Then doCol = True
            End If
            If doCol Then '<============== THIS LINE ==========
                cnt = cnt + 1
                Debug.Print ("[" & cell.Value & "]" & " / " & cell.Address & " / " & cell.Column & " / " & cell.row)
                If cnt > 5 Then End '<=== NOT NEEDED. Just prevents too much demo output.
            End If
        Next cell
    Next rngCol
End Sub

Note: If you didn't immediately catch it, the line If docol Then is your inverted CONTINUE. That is, if doCol remains False, the script CONTINUES to the next cell and doesn't do anything.

Certainly not as fast/efficient as a proper continue or next for statement, but the end result is as close as I've been able to get.

MySQL - ERROR 1045 - Access denied

If you actually have set a root password and you've just lost/forgotten it:

  1. Stop MySQL
  2. Restart it manually with the skip-grant-tables option: mysqld_safe --skip-grant-tables

  3. Now, open a new terminal window and run the MySQL client: mysql -u root

  4. Reset the root password manually with this MySQL command: UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; If you are using MySQL 5.7 (check using mysql --version in the Terminal) then the command is:

    UPDATE mysql.user SET authentication_string=PASSWORD('password')  WHERE  User='root';
    
  5. Flush the privileges with this MySQL command: FLUSH PRIVILEGES;

From http://www.tech-faq.com/reset-mysql-password.shtml

(Maybe this isn't what you need, Abs, but I figure it could be useful for people stumbling across this question in the future)

How can you flush a write using a file descriptor?

You have two choices:

  1. Use fileno() to obtain the file descriptor associated with the stdio stream pointer

  2. Don't use <stdio.h> at all, that way you don't need to worry about flush either - all writes will go to the device immediately, and for character devices the write() call won't even return until the lower-level IO has completed (in theory).

For device-level IO I'd say it's pretty unusual to use stdio. I'd strongly recommend using the lower-level open(), read() and write() functions instead (based on your later reply):

int fd = open("/dev/i2c", O_RDWR);
ioctl(fd, IOCTL_COMMAND, args);
write(fd, buf, length);

How to get current user who's accessing an ASP.NET application?

You can simply use a property of the page. And the interesting thing is that you can access that property anywhere in your code.

Use this:

HttpContext.Current.User.Identity.Name

How to change values in a tuple?

It is possible with a one liner:

values = ('275', '54000', '0.0', '5000.0', '0.0')
values = ('300', *values[1:])

How do servlets work? Instantiation, sessions, shared variables and multithreading

Session in Java servlets is the same as session in other languages such as PHP. It is unique to the user. The server can keep track of it in different ways such as cookies, url rewriting etc. This Java doc article explains it in the context of Java servlets and indicates that exactly how session is maintained is an implementation detail left to the designers of the server. The specification only stipulates that it must be maintained as unique to a user across multiple connections to the server. Check out this article from Oracle for more information about both of your questions.

Edit There is an excellent tutorial here on how to work with session inside of servlets. And here is a chapter from Sun about Java Servlets, what they are and how to use them. Between those two articles, you should be able to answer all of your questions.

How can I call controller/view helper methods from the console in Ruby on Rails?

In Ruby on Rails 3, try this:

session = ActionDispatch::Integration::Session.new(Rails.application)
session.get(url)
body = session.response.body

The body will contain the HTML of the URL.

How to route and render (dispatch) from a model in Ruby on Rails 3

How to make a dropdown readonly using jquery?

Simple jquery to remove not selected options.

$('#your_dropdown_id option:not(:selected)').remove();

PHP: How do you determine every Nth iteration of a loop?

It will not work for first position so better solution is :

if ($counter != 0 && $counter % 3 == 0) {
   echo 'image file';
}

Check it by yourself. I have tested it for adding class for every 4th element.

How do I determine scrollHeight?

scrollHeight is a regular javascript property so you don't need jQuery.

var test = document.getElementById("foo").scrollHeight;

Provisioning Profiles menu item missing from Xcode 5

For me, the refresh in xcode 5 prefs->accounts was doing nothing. At one point it showed me three profiles so I thought I was one refresh away, but after the next refresh it went back to just one profile, so I abandoned this method.

If anyone gets this far and is still struggling, here's what I did:

  1. Close xcode 5
  2. Open xcode 4.6.2
  3. Go to Window->Organizer->Provisioning Profiles
  4. Press Refresh arrow on bottom right

When I did this, everything synced up perfectly. It even told me what it was downloading each step of the way like good software does. After the sync completed, I closed xcode 4.6.2, re-opened xcode 5 and went to preferences->accounts and voila, all of my profiles are now available in xocde 5.

M_PI works with math.h but not with cmath in Visual Studio

Interestingly I checked this on an app of mine and I got the same error.

I spent a while checking through headers to see if there was anything undef'ing the _USE_MATH_DEFINES and found nothing.

So I moved the

#define _USE_MATH_DEFINES
#include <cmath>

to be the first thing in my file (I don't use PCHs so if you are you will have to have it after the #include "stdafx.h") and suddenly it compile perfectly.

Try moving it higher up the page. Totally unsure as to why this would cause issues though.

Edit: Figured it out. The #include <math.h> occurs within cmath's header guards. This means that something higher up the list of #includes is including cmath without the #define specified. math.h is specifically designed so that you can include it again with that define now changed to add M_PI etc. This is NOT the case with cmath. So you need to make sure you #define _USE_MATH_DEFINES before you include anything else. Hope that clears it up for you :)

Failing that just include math.h you are using non-standard C/C++ as already pointed out :)

Edit 2: Or as David points out in the comments just make yourself a constant that defines the value and you have something more portable anyway :)

How to set column header text for specific column in Datagridview C#

private void datagrid_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)
{
    string test = this.datagrid.Columns[e.ColumnIndex].HeaderText;
}

This code will get the HeaderText value.

How to Detect cause of 503 Service Temporarily Unavailable error and handle it?

There is of course some apache log files. Search in your apache configuration files for 'Log' keyword, you'll certainly find plenty of them. Depending on your OS and installation places may vary (in a Typical Linux server it would be /var/log/apache2/[access|error].log).

Having a 503 error in Apache usually means the proxied page/service is not available. I assume you're using tomcat and that means tomcat is either not responding to apache (timeout?) or not even available (down? crashed?). So chances are that it's a configuration error in the way to connect apache and tomcat or an application inside tomcat that is not even sending a response for apache.

Sometimes, in production servers, it can as well be that you get too much traffic for the tomcat server, apache handle more request than the proxyied service (tomcat) can accept so the backend became unavailable.

Mutex example / tutorial?

For those looking for the shortex mutex example:

#include <mutex>

int main() {
    std::mutex m;

    m.lock();
    // do thread-safe stuff
    m.unlock();
}

AngularJS - Access to child scope

Scopes in AngularJS use prototypal inheritance, when looking up a property in a child scope the interpreter will look up the prototype chain starting from the child and continue to the parents until it finds the property, not the other way around.

Check Vojta's comments on the issue https://groups.google.com/d/msg/angular/LDNz_TQQiNE/ygYrSvdI0A0J

In a nutshell: You cannot access child scopes from a parent scope.

Your solutions:

  1. Define properties in parents and access them from children (read the link above)
  2. Use a service to share state
  3. Pass data through events. $emit sends events upwards to parents until the root scope and $broadcast dispatches events downwards. This might help you to keep things semantically correct.

Multi-select dropdown list in ASP.NET

HTML does not support a dropdown list with checkboxes. You can have a dropdown list, or a checkbox list. You could possibly fake a dropdowncheckbox list using javascript and hiding divs, but that would be less reliable than just a standard checkbox list.

There are of course 3rd party controls that look like a dropdown checkboxlist, but they are using the div tricks.

you could also use a double listbox, which handles multi select by moving items back and forth between two lists. This has the added benefit of being easily to see all the selected items at once, even though the list of total items is long

(Imagine a list of every city in the world, with only the first and last selected)

how to show calendar on text box click in html

jQuery Mobile has a datepicker too. Source

Just include the following files,

  <script src="jQuery.ui.datepicker.js"></script>
  <script src="jquery.ui.datepicker.mobile.js"></script>

How can I get a specific number child using CSS?

For modern browsers, use td:nth-child(2) for the second td, and td:nth-child(3) for the third. Remember that these retrieve the second and third td for every row.

If you need compatibility with IE older than version 9, use sibling combinators or JavaScript as suggested by Tim. Also see my answer to this related question for an explanation and illustration of his method.

How do I use the JAVA_OPTS environment variable?

Actually, you can, even though accepted answer saying that you can't.

There is a _JAVA_OPTIONS environment variable, more about it here

PHP shorthand for isset()?

Update for PHP 7 (thanks shock_gone_wild)

PHP 7 introduces the so called null coalescing operator which simplifies the below statements to:

$var = $var ?? "default";

Before PHP 7

No, there is no special operator or special syntax for this. However, you could use the ternary operator:

$var = isset($var) ? $var : "default";

Or like this:

isset($var) ?: $var = 'default';

Set language for syntax highlighting in Visual Studio Code

Syntax Highlighting for custom file extension

Any custom file extension can be associated with standard syntax highlighting with custom files association in User Settings as follows.

Changing File Association settings for permanent Syntax Highlighting

Note that this will be a permanent setting. In order to set for the current session alone, type in the preferred language in Select Language Mode box (without changing file association settings)

Installing new Syntax Package

If the required syntax package is not available by default, you can add them via the Extension Marketplace (Ctrl+Shift+X) and search for the language package.

You can further reproduce the above steps to map the file extensions with the new syntax package.

Explicitly set column value to null SQL Developer

It is clear that most people who haven't used SQL Server Enterprise Manager don't understand the question (i.e. Justin Cave).

I came upon this post when I wanted to know the same thing.

Using SQL Server, when you are editing your data through the MS SQL Server GUI Tools, you can use a KEYBOARD SHORTCUT to insert a NULL rather than having just an EMPTY CELL, as they aren't the same thing. An empty cell can have a space in it, rather than being NULL, even if it is technically empty. The difference is when you intentionally WANT to put a NULL in a cell rather than a SPACE or to empty it and NOT using a SQL statement to do so.

So, the question really is, how do I put a NULL value in the cell INSTEAD of a space to empty the cell?

I think the answer is, that the way the Oracle Developer GUI works, is as Laniel indicated above, And THAT should be marked as the answer to this question.

Oracle Developer seems to default to NULL when you empty a cell the way the op is describing it.

Additionally, you can force Oracle Developer to change how your null cells look by changing the color of the background color to further demonstrate when a cell holds a null:

Tools->Preferences->Advanced->Display Null Using Background Color

or even the VALUE it shows when it's null:

Tools->Preferences->Advanced->Display Null Value As

Hope that helps in your transition.

Add an object to an Array of a custom class

The array declaration should be:

Car[] garage = new Car[100];

You can also just assign directly:

garage[1] = new Car("Blue");

get unique machine id

You can use WMI Code creator. I guess you can have a combination of "keys" (processorid,mac and software generated key).

using System.Management;
using System.Windows.Forms;

try
{
     ManagementObjectSearcher searcher = 
         new ManagementObjectSearcher("root\\CIMV2", "SELECT * FROM Win32_Processor"); 

     foreach (ManagementObject queryObj in searcher.Get())
     {
         Console.WriteLine("-----------------------------------");
         Console.WriteLine("Win32_Processor instance");
         Console.WriteLine("-----------------------------------");
         Console.WriteLine("Architecture: {0}", queryObj["Architecture"]);
         Console.WriteLine("Caption: {0}", queryObj["Caption"]);
         Console.WriteLine("Family: {0}", queryObj["Family"]);
         Console.WriteLine("ProcessorId: {0}", queryObj["ProcessorId"]);
     }
}
catch (ManagementException e)
{
    MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}

Win32_Processor

Retrieving Hardware Identifiers in C# with WMI by Peter Bromberg

What is the default root pasword for MySQL 5.7

I to was experiencing the same problem and the only thing I was able to do to make it work was to go this route:

drop user admin@localhost;
flush privileges;
create user admin@localhost identified by 'admins_password'

This allowed me to recreate my username and enter a password for the user name.

Should I use int or Int32

Also consider Int16. If you need to store an Integer in memory in your application and you are concerned about the amount of memory used, then you could go with Int16 since it uses less memeory and has a smaller min/max range than Int32 (which is what int is.)

import android packages cannot be resolved

RightClick on the Project > Properties > Android > Fix project properties

This solved it for me. easy.

Storing database records into array

$mysearch="Your Search Name";
$query = mysql_query("SELECT * FROM table");
$c=0;
// set array
$array = array();

// look through query
while($row = mysql_fetch_assoc($query)){

  // add each row returned into an array
  $array[] = $row;
  $c++;
}

for($i=0;$i=$c;$i++)
{
if($array[i]['username']==$mysearch)
{
// name found
}
}

EOFError: EOF when reading a line

width, height = map(int, input().split())
def rectanglePerimeter(width, height):
   return ((width + height)*2)
print(rectanglePerimeter(width, height))

Running it like this produces:

% echo "1 2" | test.py
6

I suspect IDLE is simply passing a single string to your script. The first input() is slurping the entire string. Notice what happens if you put some print statements in after the calls to input():

width = input()
print(width)
height = input()
print(height)

Running echo "1 2" | test.py produces

1 2
Traceback (most recent call last):
  File "/home/unutbu/pybin/test.py", line 5, in <module>
    height = input()
EOFError: EOF when reading a line

Notice the first print statement prints the entire string '1 2'. The second call to input() raises the EOFError (end-of-file error).

So a simple pipe such as the one I used only allows you to pass one string. Thus you can only call input() once. You must then process this string, split it on whitespace, and convert the string fragments to ints yourself. That is what

width, height = map(int, input().split())

does.

Note, there are other ways to pass input to your program. If you had run test.py in a terminal, then you could have typed 1 and 2 separately with no problem. Or, you could have written a program with pexpect to simulate a terminal, passing 1 and 2 programmatically. Or, you could use argparse to pass arguments on the command line, allowing you to call your program with

test.py 1 2

Local storage in Angular 2

We can easily use the localStorage for setting the data and receiving the data.

Note: it works with both angular2 and angular 4

//set the data
localStorage.setItem(key, value);   //syntax example
localStorage.setItem('tokenKey', response.json().token);

//get the data
localStorage.getItem('tokenKey')

//confirm if token is exist or not
return localStorage.getItem('tokenKey') != null;

How do I add target="_blank" to a link within a specified div?

Using jQuery:

 $('#link_other a').each(function(){
  $(this).attr('target', '_BLANK');
 });

How can I programmatically invoke an onclick() event from a anchor tag while keeping the ‘this’ reference in the onclick function?

If you're using this purely to reference the function in the onclick attribute, this seems like a very bad idea. Inline events are a bad idea in general.

I would suggest the following:

function addEvent(elm, evType, fn, useCapture) {
    if (elm.addEventListener) {
        elm.addEventListener(evType, fn, useCapture);
        return true;
    }
    else if (elm.attachEvent) {
        var r = elm.attachEvent('on' + evType, fn);
        return r;
    }
    else {
        elm['on' + evType] = fn;
    }
}

handler = function(){
   showHref(el);
}

showHref = function(el) {
   alert(el.href);
}

var el = document.getElementById('linkid');

addEvent(el, 'click', handler);

If you want to call the same function from other javascript code, simulating a click to call the function is not the best way. Consider:

function doOnClick() {
   showHref(document.getElementById('linkid'));
}

Check if a string is a valid date using DateTime.TryParse

[TestCase("11/08/1995", Result= true)]
[TestCase("1-1", Result = false)]
[TestCase("1/1", Result = false)]
public bool IsValidDateTimeTest(string dateTime)
{
    string[] formats = { "MM/dd/yyyy" };
    DateTime parsedDateTime;
    return DateTime.TryParseExact(dateTime, formats, new CultureInfo("en-US"),
                                   DateTimeStyles.None, out parsedDateTime);
}

Simply specify the date time formats that you wish to accept in the array named formats.

'module' has no attribute 'urlencode'

You use the Python 2 docs but write your program in Python 3.

cordova run with ios error .. Error code 65 for command: xcodebuild with args:

In my case it was the app icon PNG file... I mean, it took 1 day to go from the provided error

Error code 65 for command: xcodebuild with args:

to the human-readable one:

"the PNG file icon is no good for the picky Apple Xcode"

How to remove all namespaces from XML with C#?

And this is the perfect solution that will also remove XSI elements. (If you remove the xmlns and don't remove XSI, .Net shouts at you...)

string xml = node.OuterXml;
//Regex below finds strings that start with xmlns, may or may not have :and some text, then continue with =
//and ", have a streach of text that does not contain quotes and end with ". similar, will happen to an attribute
// that starts with xsi.
string strXMLPattern = @"xmlns(:\w+)?=""([^""]+)""|xsi(:\w+)?=""([^""]+)""";
xml = Regex.Replace(xml, strXMLPattern, "");

How to extract multiple JSON objects from one file?

Update: I wrote a solution that doesn't require reading the entire file in one go. It's too big for a stackoverflow answer, but can be found here jsonstream.

You can use json.JSONDecoder.raw_decode to decode arbitarily big strings of "stacked" JSON (so long as they can fit in memory). raw_decode stops once it has a valid object and returns the last position where wasn't part of the parsed object. It's not documented, but you can pass this position back to raw_decode and it start parsing again from that position. Unfortunately, the Python json module doesn't accept strings that have prefixing whitespace. So we need to search to find the first none-whitespace part of your document.

from json import JSONDecoder, JSONDecodeError
import re

NOT_WHITESPACE = re.compile(r'[^\s]')

def decode_stacked(document, pos=0, decoder=JSONDecoder()):
    while True:
        match = NOT_WHITESPACE.search(document, pos)
        if not match:
            return
        pos = match.start()
        
        try:
            obj, pos = decoder.raw_decode(document, pos)
        except JSONDecodeError:
            # do something sensible if there's some error
            raise
        yield obj

s = """

{"a": 1}  


   [
1
,   
2
]


"""

for obj in decode_stacked(s):
    print(obj)

prints:

{'a': 1}
[1, 2]

Python convert decimal to hex

Instead of printing everything in the function, you could just allow it to return the value in hex, and do whatever you want with it.

def ChangeHex(n):
    x = (n % 16)
    c = ""
    if (x < 10):
        c = x
    if (x == 10):
        c = "A"
    if (x == 11):
        c = "B"
    if (x == 12):
        c = "C"
    if (x == 13):
        c = "D"
    if (x == 14):
        c = "E"
    if (x == 15):
        c = "F"

    if (n - x != 0):
        return ChangeHex(n / 16) + str(c)
    else:
        return str(c)

print(ChangeHex(52))

There are probably more elegant ways of parsing the alphabetic components of the hex, instead of just using conditionals.

How to printf long long

    // acos(0.0) will return value of pi/2, inverse of cos(0) is pi/2 
    double pi = 2 * acos(0.0);
    int n; // upto 6 digit
    scanf("%d",&n); //precision with which you want the value of pi
    printf("%.*lf\n",n,pi); // * will get replaced by n which is the required precision

SQL Server: Error converting data type nvarchar to numeric

I was running into this error while converting from nvarchar to float.
What I had to do was to use the LEFT function on the nvarchar field.

Example: Left(Field,4)

Basically, the query will look like:

Select convert(float,left(Field,4)) from TABLE

Just ridiculous that SQL would complicate it to this extent, while with C# it's a breeze!
Hope it helps someone out there.

Referring to a table in LaTeX

You must place the label after a caption in order to for label to store the table's number, not the chapter's number.

\begin{table}
\begin{tabular}{| p{5cm} | p{5cm} | p{5cm} |}
  -- cut --
\end{tabular}
\caption{My table}
\label{table:kysymys}
\end{table}

Table \ref{table:kysymys} on page \pageref{table:kysymys} refers to the ...

How can I solve ORA-00911: invalid character error?

If a special character other than $, _, and # is used in the name of a column or table, the name must be enclosed in double quotations. Link

ImportError: No module named PyQt4.QtCore

I had the "No module named PyQt4.QtCore" error and installing the python-qt4 package fixed it only partially: I could run

from PyQt4.QtCore import SIGNAL

from a python interpreter but only without activating my virtualenv.

The only solution I've found till now to use a virtualenv is to copy the PyQt4 folder and the sip.so file into my virtualenv as explained here: Is it possible to add PyQt4/PySide packages on a Virtualenv sandbox?

How to add jQuery in JS file

The problem is you're using </script> within the script, which is ending the script tag. Try this:

document.writeln('<script src="/javascripts/jquery.js" type="text/javascript"></sc'+'ript>');
document.writeln('<script type="text/javascript" src="/javascripts/jquery.tablesorter.js"></sc'+'ript>');

Accessing post variables using Java Servlets

Here's a simple example. I didn't get fancy with the html or the servlet, but you should get the idea.

I hope this helps you out.

<html>
<body>
<form method="post" action="/myServlet">
<input type="text" name="username" />
<input type="password" name="password" />
<input type="submit" />
</form>
</body>
</html>

Now for the Servlet

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class MyServlet extends HttpServlet {
  public void doPost(HttpServletRequest request,
                    HttpServletResponse response)
      throws ServletException, IOException {

    String userName = request.getParameter("username");
    String password = request.getParameter("password");
    ....
    ....
  }
}

Loop through each cell in a range of cells when given a Range object

You could use Range.Rows, Range.Columns or Range.Cells. Each of these collections contain Range objects.

Here's how you could modify Dick's example so as to work with Rows:

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCell In rRng.Rows
        Debug.Print rCell.Address, rCell.Value
    Next rCell

End Sub

And Columns:

Sub LoopRange()

    Dim rCell As Range
    Dim rRng As Range

    Set rRng = Sheet1.Range("A1:A6")

    For Each rCol In rRng.Columns
        For Each rCell In rCol.Rows
            Debug.Print rCell.Address, rCell.Value
        Next rCell
    Next rCol

End Sub

XSLT getting last element

You need to put the last() indexing on the nodelist result, rather than as part of the selection criteria. Try:

(//element[@name='D'])[last()]

Malformed String ValueError ast.literal_eval() with String representation of Tuple

From the documentation for ast.literal_eval():

Safely evaluate an expression node or a string containing a Python expression. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

Decimal isn't on the list of things allowed by ast.literal_eval().

Update Git submodule to latest commit on origin

If you don't know the host branch, make this:

git submodule foreach git pull origin $(git rev-parse --abbrev-ref HEAD)

It will get a branch of the main Git repository and then for each submodule will make a pull of the same branch.

How can I get the name of an object in Python?

Note that while, as noted, objects in general do not and cannot know what variables are bound to them, functions defined with def do have names in the __name__ attribute (the name used in def). Also if the functions are defined in the same module (as in your example) then globals() will contain a superset of the dictionary you want.

def fun1:
  pass
def fun2:
  pass
def fun3:
  pass

fun_dict = {}
for f in [fun1, fun2, fun3]:
  fun_dict[f.__name__] = f

What is the meaning of "POSIX"?

Let me give the churlish "unofficial" explanation.

POSIX is a set of standards which attempts to distinguish "UNIX" and UNIX-like systems from those which are incompatible with them. It was created by the U.S. government for procurement purposes. The idea was that the U.S. federal procurements needed a way to legally specify the requirements for various sorts of bids and contracts in a way that could be used to exclude systems to which a given existing code base or programming staff would NOT be portable.

Since POSIX was written post facto ... to describe a loosely similar set of competing systems ... it was NOT written in a way that could be implemented.

So, for example, Microsoft's NT was written with enough POSIX conformance to qualify for some bids ... even though the POSIX subsystem was essentially useless in terms of practical portability and compatibility with UNIX systems.

Various other standards for UNIX have been written over the decades. Things like the SPEC1170 (specified eleven hundred and seventy function calls which had to be implemented compatibly) and various incarnations of the SUS (Single UNIX Specification).

For the most part these "standards" have been inadequate to any practical technical application. They most exist for argumentation, legal wrangling and other dysfunctional reasons.

Update Android SDK Tool to 22.0.4(Latest Version) from 22.0.1

You may need to go to Window -> Android SDK Manager -> Packages -> Reload to fetch latest updates and then update the SDK.

Remove row lines in twitter bootstrap

In Bootstrap 3 I've added a table-no-border class

.table-no-border>thead>tr>th, 
.table-no-border>tbody>tr>th, 
.table-no-border>tfoot>tr>th, 
.table-no-border>thead>tr>td, 
.table-no-border>tbody>tr>td, 
.table-no-border>tfoot>tr>td {
  border-top: none; 
}

SQL Delete Records within a specific Range

You gave a condition ID (>79 and < 296) then the answer is:

delete from tab
where id > 79 and id < 296

this is the same as:

delete from tab
where id between 80 and 295

if id is an integer.

All answered:

delete from tab
where id between 79 and 296

this is the same as:

delete from tab
where id => 79 and id <= 296

Mind the difference.

What is trunk, branch and tag in Subversion?

The "trunk", "branches", and "tags" directories are conventions in Subversion. Subversion does not require you to have these directories nor assign special meaning to them. However, this convention is very common and, unless you have a really good reason, you should follow the convention. The book links that other readers have given describe the convention and how to use it.

Launch Bootstrap Modal on page load

Update 2020 - Bootstrap 5

Building on the excellent responses from previous answers, in Bootstrap 5 with no jQuery, this has worked;

document.querySelector('[data-target="#exampleModal"]').click();

Full snippet:

_x000D_
_x000D_
window.onload = () => {
  document.querySelector('[data-target="#exampleModal"]').click();
}
_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/js/bootstrap.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/umd/popper.min.js"></script>
<link href="https://stackpath.bootstrapcdn.com/bootstrap/5.0.0-alpha1/css/bootstrap.min.css" rel="stylesheet" />


<div class="container py-3">

  <!-- Button trigger modal -->
  <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
    Launch demo modal
  </button>

  <!-- Modal -->
  <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
    <div class="modal-dialog">
      <div class="modal-content">
        <div class="modal-header">
          <h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
          <button type="button" class="close" data-dismiss="modal" aria-label="Close">
            <span aria-hidden="true">&times;</span>
          </button>
        </div>
        <div class="modal-body">
          ...
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
          <button type="button" class="btn btn-primary">Save changes</button>
        </div>
      </div>
    </div>
  </div>

</div>
_x000D_
_x000D_
_x000D_

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I had this error. Nothing worked for me until I opened the SQLServer log file in the "MSSQL10_50" Log folder. That clearly stated which file could not be overwritten. It turned out that the .mdf file was being written into the "MSSQL10" data folder. I made sure that folder had the same SQLServer user permissions as the "MSSQL10_50" equivalent folder. Then it all worked.

The issue here is that the error detail is logged but not reported, so check the logs.

How to convert numbers to words without using num2word library?

def nums_to_words(string):
    string = int(string) # Convert the string to an integer
    one_ten=['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 
    'eight', 'nine']
    ten_nineteen=['ten', 'eleven', 'twelve', 'thirteen', 'fourteen', 
    'fifteen',
    'sixteen', 'seventeen', 'eighteen', 'nineteen']
    twenty_ninety=[' ', ' ','twenty', 'thirty', 'forty', 'fifty', 'sixty', 
    'seventy', 'eighty',
    'ninety']
    temp_str = ""
    if string == 0: # If the string given equals to 0
        temp_str = 'zero ' # Assign the word zero to the var temp_str
    # Do the calculation to find each digit of the str given
    first_digit = string // 1000
    second_digit = (string % 1000) // 100
    third_digit = (string % 100) // 10
    fourth_digit = (string % 10)
    if first_digit > 0: 
        temp_str = temp_str + one_ten[first_digit] + ' thousand '
    # one_ten[first_digit] gets you the number you need from one_ten and you add thousand (since we're trying to convert to words ofc)
    # You do the same for the rest...
    if second_digit > 0:
        temp_str = temp_str + one_ten[second_digit] + ' hundred '
    if third_digit > 1:
        temp_str = temp_str + twenty_ninety[third_digit] + " "
    if third_digit == 1:
        temp_str = temp_str + ten_nineteen[fourth_digit] + " "
    else:
        if fourth_digit:
            temp_str = temp_str + one_ten[fourth_digit] + " "
    if temp_str[-1] == " ": # If the last index is a space
        temp_str = temp_str[0:-1] # Slice it 
return temp_str 

I hope you get the understanding of the code slightly better; If still not understood let me know so I can try to help as much as I can.

gridview data export to excel in asp.net

Your sheet is blank because your string writer in null. Here is what may help

System.Web.UI.HtmlTextWriter htmlWrite =
    new HtmlTextWriter(stringWrite);

    GridView1.RenderControl(htmlWrite);

Here is the full code

protected void Button1_Click(object sender, EventArgs e)
{
    Response.Clear();

    Response.AddHeader("content-disposition", "attachment;
    filename=FileName.xls");


    Response.ContentType = "application/vnd.xls";

    System.IO.StringWriter stringWrite = new System.IO.StringWriter();

    System.Web.UI.HtmlTextWriter htmlWrite =
    new HtmlTextWriter(stringWrite);

    GridView1.RenderControl(htmlWrite);

    Response.Write(stringWrite.ToString());

    Response.End();

}

How to get start and end of day in Javascript?

Using the momentjs library, this can be achieved with the startOf() and endOf() methods on the moment's current date object, passing the string 'day' as arguments:

Local GMT:

var start = moment().startOf('day'); // set to 12:00 am today
var end = moment().endOf('day'); // set to 23:59 pm today

For UTC:

var start = moment.utc().startOf('day'); 
var end = moment.utc().endOf('day'); 

How to import image (.svg, .png ) in a React Component

import React, {Component} from 'react';
import imagename from './imagename.png'; //image is in the current folder where the App.js exits


class App extends React. Component{
    constructor(props){
     super(props)
     this.state={
      imagesrc=imagename // as it is imported
     }
   }

   render(){
       return (

        <ImageClass 
        src={this.state.imagesrc}
        />
       );
   }
}

class ImageClass extends React.Component{
    render(){
        return (

            <img src={this.props.src} height='200px' width='100px' />
        );
    }
}

export default App;

What does Maven do, in theory and in practice? When is it worth to use it?

What it does

Maven is a "build management tool", it is for defining how your .java files get compiled to .class, packaged into .jar (or .war or .ear) files, (pre/post)processed with tools, managing your CLASSPATH, and all others sorts of tasks that are required to build your project. It is similar to Apache Ant or Gradle or Makefiles in C/C++, but it attempts to be completely self-contained in it that you shouldn't need any additional tools or scripts by incorporating other common tasks like downloading & installing necessary libraries etc.

It is also designed around the "build portability" theme, so that you don't get issues as having the same code with the same buildscript working on one computer but not on another one (this is a known issue, we have VMs of Windows 98 machines since we couldn't get some of our Delphi applications compiling anywhere else). Because of this, it is also the best way to work on a project between people who use different IDEs since IDE-generated Ant scripts are hard to import into other IDEs, but all IDEs nowadays understand and support Maven (IntelliJ, Eclipse, and NetBeans). Even if you don't end up liking Maven, it ends up being the point of reference for all other modern builds tools.

Why you should use it

There are three things about Maven that are very nice.

  1. Maven will (after you declare which ones you are using) download all the libraries that you use and the libraries that they use for you automatically. This is very nice, and makes dealing with lots of libraries ridiculously easy. This lets you avoid "dependency hell". It is similar to Apache Ant's Ivy.

  2. It uses "Convention over Configuration" so that by default you don't need to define the tasks you want to do. You don't need to write a "compile", "test", "package", or "clean" step like you would have to do in Ant or a Makefile. Just put the files in the places in which Maven expects them and it should work off of the bat.

  3. Maven also has lots of nice plug-ins that you can install that will handle many routine tasks from generating Java classes from an XSD schema using JAXB to measuring test coverage with Cobertura. Just add them to your pom.xml and they will integrate with everything else you want to do.

The initial learning curve is steep, but (nearly) every professional Java developer uses Maven or wishes they did. You should use Maven on every project although don't be surprised if it takes you a while to get used to it and that sometimes you wish you could just do things manually, since learning something new sometimes hurts. However, once you truly get used to Maven you will find that build management takes almost no time at all.

How to Start

The best place to start is "Maven in 5 Minutes". It will get you start with a project ready for you to code in with all the necessary files and folders set-up (yes, I recommend using the quickstart archetype, at least at first).

After you get started you'll want a better understanding over how the tool is intended to be used. For that "Better Builds with Maven" is the most thorough place to understand the guts of how it works, however, "Maven: The Complete Reference" is more up-to-date. Read the first one for understanding, but then use the second one for reference.

Multiple parameters in a List. How to create without a class?

If appropriate, you might use a Dictionary which is also a generic collection:

Dictionary<string, int> d = new Dictionary<string, int>();
d.Add("string", 1);

top align in html table?

<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
    <TR style="vertical-align:top">
        <TD>
            <!-- The log text-box -->
            <div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
                Log:
            </div>
        </TD>
        <TD>
            <!-- The 2nd column -->
        </TD>
        <TD>
            <!-- The 3rd column -->
        </TD>
    </TR>
</TABLE>

javascript - pass selected value from popup window to parent window input box

From your code

<input type=button value="Select" onClick="sendValue(this.form.details);"

Im not sure that your this.form.details valid or not.

IF it's valid, have a look in window.opener.document.getElementById('details').value = selvalue;

I can't found an input's id contain details I'm just found only id=sku1 (recommend you to add " like id="sku1").

And from your id it's hardcode. Let's see how to do with dynamic when a child has callback to update some textbox on the parent Take a look at here.

First page.

<html>
<head>
<script>
    function callFromDialog(id,data){ //for callback from the dialog
        document.getElementById(id).value = data;
        // do some thing other if you want
    }

    function choose(id){
        var URL = "secondPage.html?id=" + id + "&dummy=avoid#";
        window.open(URL,"mywindow","menubar=1,resizable=1,width=350,height=250")
    }
</script>
</head>
<body>
<input id="tbFirst" type="text" /> <button onclick="choose('tbFirst')">choose</button>
<input id="tbSecond" type="text" /> <button onclick="choose('tbSecond')">choose</button>
</body>
</html>

Look in function choose I'm sent an id of textbox to the popup window (don't forget to add dummy data at last of URL param like &dummy=avoid#)

Popup Page

<html>
<head>
<script>
    function goSelect(data){
        var idFromCallPage = getUrlVars()["id"];
        window.opener.callFromDialog(idFromCallPage,data); //or use //window.opener.document.getElementById(idFromCallPage).value = data;
        window.close();
    }


    function getUrlVars(){
        var vars = [], hash;
        var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
        for(var i = 0; i < hashes.length; i++)
        {
            hash = hashes[i].split('=');
            vars.push(hash[0]);
            vars[hash[0]] = hash[1];
        }
        return vars;
    }
</script>
</head>
<body>
<a href="#" onclick="goSelect('Car')">Car</a> <br />
<a href="#" onclick="goSelect('Food')">Food</a> <br />
</body>
</html>

I have add function getUrlVars for get URL param that the parent has pass to child.

Okay, when select data in the popup, for this case it's will call function goSelect

In that function will get URL param to sent back.

And when you need to sent back to the parent just use window.opener and the name of function like window.opener.callFromDialog

By fully is window.opener.callFromDialog(idFromCallPage,data);

Or if you want to use window.opener.document.getElementById(idFromCallPage).value = data; It's ok too.

Attach the Java Source Code

The option provided by"praveenak" can also be applied to any other jar files with source file provided. For example, for JavaFx, we right click jfxrt.jar, select "Properties" and enter jdk1.8.0_05/javafx-src.zip for "Path" under External location.

Set HTTP header for one request

There's a headers parameter in the config object you pass to $http for per-call headers:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

Or with the shortcut method:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});

The list of the valid parameters is available in the $http service documentation.

RuntimeError on windows trying python multiprocessing

hello here is my structure for multi process

from multiprocessing import Process
import time


start = time.perf_counter()


def do_something(time_for_sleep):
    print(f'Sleeping {time_for_sleep} second...')
    time.sleep(time_for_sleep)
    print('Done Sleeping...')



p1 = Process(target=do_something, args=[1])
p2 = Process(target=do_something, args=[2])


if 

__name__ == '__main__':
    p1.start()
    p2.start()

    p1.join()
    p2.join()

    finish = time.perf_counter()
    print(f'Finished in {round(finish-start,2 )} second(s)')

you don't have to put imports in the name == 'main', just running the program you wish to running inside

add id to dynamically created <div>

If I got you correctly, it is as easy as

cartDiv.id = "someID";

No need for jQuery.

Have a look at the properties of a DOM Element.

For classes it is the same:

cartDiv.className = "classes here";

But note that this will overwrite already existing class names. If you want to add and remove classes dynamically, you either have to use jQuery or write your own function that does some string replacement.

How do I hide anchor text without hiding the anchor?

Try

 a{
    line-height: 0; 
    font-size: 0;
    color: transparent; 
 }


The color: transparent; covers an issue with Webkit browsers still displaying 1px of the text.

How to get the size of a file in MB (Megabytes)?

Easiest is by using FileUtils from Apache commons-io.( https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html )

Returns human readable file size from Bytes to Exabytes , rounding down to the boundary.

File fileObj = new File(filePathString);
String fileSizeReadable = FileUtils.byteCountToDisplaySize(fileObj.length());

// output will be like 56 MB 

Why doesn't margin:auto center an image?

i know this is an old post, but wanted to share how i solved the same problem.

My image was inheriting a float:left from a parent class. By setting float:none I was able to make margin:0 auto and display: block work properly. Hope it may help someone in the future.

if, elif, else statement issues in Bash

You have some syntax issues with your script. Here is a fixed version:

#!/bin/bash

if [ "$seconds" -eq 0 ]; then
   timezone_string="Z"
elif [ "$seconds" -gt 0 ]; then
   timezone_string=$(printf "%02d:%02d" $((seconds/3600)) $(((seconds / 60) % 60)))
else
   echo "Unknown parameter"
fi

How to find Oracle Service Name

With SQL Developer you should also find it without writing any query. Right click on your Connection/Propriety.

You should see the name on the left under something like "connection details" and should look like "Connectionname@servicename", or on the right, under the connection's details.

Checking for the correct number of arguments

#!/bin/sh
if [ "$#" -ne 1 ] || ! [ -d "$1" ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi

Translation: If number of arguments is not (numerically) equal to 1 or the first argument is not a directory, output usage to stderr and exit with a failure status code.

More friendly error reporting:

#!/bin/sh
if [ "$#" -ne 1 ]; then
  echo "Usage: $0 DIRECTORY" >&2
  exit 1
fi
if ! [ -e "$1" ]; then
  echo "$1 not found" >&2
  exit 1
fi
if ! [ -d "$1" ]; then
  echo "$1 not a directory" >&2
  exit 1
fi

Load image from resources

Try this for WPF

StreamResourceInfo sri = Application.GetResourceStream(new Uri("pack://application:,,,/WpfGifImage001;Component/Images/Progess_Green.gif"));
picBox1.Image = System.Drawing.Image.FromStream(sri.Stream);

How to get box-shadow on left & right sides only

Try this, it's working for me:

    box-shadow: -5px 0 5px -5px #333, 5px 0 5px -5px #333;

redirect to current page in ASP.Net

Why Server.Transfer? Response.Redirect(Request.RawUrl) would get you what you need.

Bootstrap Columns Not Working

Have you checked that those classes are present in the CSS? Are you using twitter-bootstrap-rails gem? It still uses Bootstrap 2.X version and those are Bootstrap 3.X classes. The CSS grid changed since.

You can switch to the bootstrap3 branch of the gem https://github.com/seyhunak/twitter-bootstrap-rails/tree/bootstrap3 or include boostrap in an alternative way.

Why do we have to override the equals() method in Java?

From the article Override equals and hashCode in Java:

Default implementation of equals() class provided by java.lang.Object compares memory location and only return true if two reference variable are pointing to same memory location i.e. essentially they are same object.

Java recommends to override equals and hashCode method if equality is going to be defined by logical way or via some business logic: example:

many classes in Java standard library does override it e.g. String overrides equals, whose implementation of equals() method return true if content of two String objects are exactly same

Integer wrapper class overrides equals to perform numerical comparison etc.

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

For those who like to reduce typing (i.e., everyone!): pd.set_option('max_colwidth', None) does the same thing

Set icon for Android application

If you intend on your application being available on a large range of devices, you should place your application icon into the different res/drawable... folders provided. In each of these folders, you should include a 48dp sized icon:

  • drawable-ldpi (120 dpi, Low density screen) - 36px x 36px
  • drawable-mdpi (160 dpi, Medium density screen) - 48px x 48px
  • drawable-hdpi (240 dpi, High density screen) - 72px x 72px
  • drawable-xhdpi (320 dpi, Extra-high density screen) - 96px x 96px
  • drawable-xxhdpi (480 dpi, Extra-extra-high density screen) - 144px x 144px
  • drawable-xxxhdpi (640 dpi, Extra-extra-extra-high density screen) - 192px x 192px

You may then define the icon in your AndroidManifest.xml file as such:

<application android:icon="@drawable/icon_name" android:label="@string/app_name" >
.... 
</application> 

Changing column names of a data frame

There are a couple options with dplyr::rename() and dplyr::select():

library(dplyr)

mtcars %>% 
  tibble::rownames_to_column('car_model') %>%                            # convert rowname to a column. tibble must be installed.
  select(car_model, est_mpg = mpg, horse_power = hp, everything()) %>%   # rename specific columns and reorder
  rename(weight = wt, cylinders = cyl) %>%                               # another option for renaming specific columns that keeps everything by default
  head(2)
      car_model est_mpg horse_power cylinders disp drat weight  qsec vs am gear carb
1     Mazda RX4      21         110         6  160  3.9  2.620 16.46  0  1    4    4
2 Mazda RX4 Wag      21         110         6  160  3.9  2.875 17.02  0  1    4    4

There are also three scoped variants of dplyr::rename(): dplyr::rename_all() for all column names, dplyr::rename_if() for conditionally targeting column names, and dplyr::rename_at() for select named columns. The following example replaces spaces and periods with an underscore and converts everything to lower case:

iris %>%  
  rename_all(~gsub("\\s+|\\.", "_", .)) %>% 
  rename_all(tolower) %>% 
  head(2)
  sepal_length sepal_width petal_length petal_width species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa

dplyr::select_all() can also be used in a similar way:

iris %>%  
  select_all(~gsub("\\s+|\\.", "_", .)) %>% 
  select_all(tolower) %>% 
  head(2)
  sepal_length sepal_width petal_length petal_width species
1          5.1         3.5          1.4         0.2  setosa
2          4.9         3.0          1.4         0.2  setosa

Structs data type in php?

You can use an array

$something = array(
   'key' => 'value',
   'key2' => 'value2'
);

or with standard object.

$something = new StdClass();

$something->key = 'value';
$something->key2 = 'value2';

How do I clone a generic List in Java?

This is the code I use for that:

ArrayList copy = new ArrayList (original.size());
Collections.copy(copy, original);

Hope is usefull for you

mysqldump data only

Best to dump to a compressed file

mysqldump --no-create-info -u username -hhostname -p dbname | gzip > /backupsql.gz

and to restore using pv apt-get install pv to monitor progress

pv backupsql.gz | gunzip | mysql -uusername -hhostip -p dbname

Last element in .each() set

For future Googlers i've a different approach to check if it's last element. It's similar to last lines in OP question.

This directly compares elements rather than just checking index numbers.

$yourset.each(function() {
    var $this = $(this);
    if($this[0] === $yourset.last()[0]) {
        //$this is the last one
    }
});

Error "initializer element is not constant" when trying to initialize variable with const

It's a limitation of the language. In section 6.7.8/4:

All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

In section 6.6, the spec defines what must considered a constant expression. No where does it state that a const variable must be considered a constant expression. It is legal for a compiler to extend this (6.6/10 - An implementation may accept other forms of constant expressions) but that would limit portability.

If you can change my_foo so it does not have static storage, you would be okay:

int main()
{
    foo_t my_foo = foo_init;
    return 0;
}

How do I force Robocopy to overwrite files?

This is really weird, why nobody is mentioning the /IM switch ?! I've been using it for a long time in backup jobs. But I tried googling just now and I couldn't land on a single web page that says anything about it even on MS website !!! Also found so many user posts complaining about the same issue!!

Anyway.. to use Robocopy to overwrite EVERYTHING what ever size or time in source or distination you must include these three switches in your command (/IS /IT /IM)

/IS :: Include Same files. (Includes same size files)
/IT :: Include Tweaked files. (Includes same files with different Attributes)
/IM :: Include Modified files (Includes same files with different times).

This is the exact command I use to transfer few TeraBytes of mostly 1GB+ files (ISOs - Disk Images - 4K Videos):

robocopy B:\Source D:\Destination /E /J /COPYALL /MT:1 /DCOPY:DATE /IS /IT /IM /X /V /NP /LOG:A:\ROBOCOPY.LOG

I did a small test for you .. and here is the result:

               Total    Copied   Skipped  Mismatch    FAILED    Extras
    Dirs :      1028      1028         0         0         0       169
   Files :      8053      8053         0         0         0         1
   Bytes : 649.666 g 649.666 g         0         0         0   1.707 g
   Times :   2:46:53   0:41:43                       0:00:00   0:41:44


   Speed :           278653398 Bytes/sec.
   Speed :           15944.675 MegaBytes/min.
   Ended : Friday, August 21, 2020 7:34:33 AM

Dest, Disk: WD Gold 6TB (Compare the write speed with my result)

Even with those "Extras", that's for reporting only because of the "/X" switch. As you can see nothing was Skipped and Total number and size of all files are equal to the Copied. Sometimes It will show small number of skipped files when I abuse it and cancel it multiple times during operation but even with that the values in the first 2 columns are always Equal. I also confirmed that once before by running a PowerShell script that scans all files in destination and generate a report of all time-stamps.

Some performance tips from my history with it and so many tests & troubles!:

. Despite of what most users online advise to use maximum threads "/MT:128" like it's a general trick to get the best performance ... PLEASE DON'T USE "/MT:128" WITH VERY LARGE FILES ... that's a big mistake and it will decrease your drive performance dramatically after several runs .. it will create very high fragmentation or even cause the files system to fail in some cases and you end up spending valuable time trying to recover a RAW partition and all that nonsense. And above all that, It will perform 4-6 times slower!!

For very large files:

  1. Use Only "One" thread "/MT:1" | Impact: BIG
  2. Must use "/J" to disable buffering. | Impact: High
  3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: Medium.
  4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: Low.

For regular big files:

  1. Use multi threads, I would not exceed "/MT:4" | Impact: BIG
  2. IF destination disk has low Cache specs use "/J" to disable buffering | Impact: High
  3. & 4 same as above.

For thousands of tiny files:

  1. Go nuts :) with Multi threads, at first I would start with 16 and multibly by 2 while monitoring the disk performance. Once it starts dropping I'll fall back to the prevouse value and stik with it | Impact: BIG
  2. Don't use "/J" | Impact: High
  3. Use "/NP" with "/LOG:file" and Don't output to the console by "/TEE" | Impact: HIGH.
  4. Put the "/LOG:file" on a separate drive from the source or destination | Impact: HIGH.

Equivalent of jQuery .hide() to set visibility: hidden

Pure JS equivalent for jQuery hide()/show() :

function hide(el) {
    el.style.visibility = 'hidden';    
    return el;
}

function show(el) {
    el.style.visibility = 'visible';    
    return el;
}

hide(document.querySelector(".test"));
// hide($('.test')[0])   // usage with jQuery

We use return el due to satisfy fluent interface "desing pattern".

Here is working example.


Below I also provide HIGHLY unrecommended alternative, which is however probably more "close to question" answer:

HTMLElement.prototype.hide = function() {
    this.style.visibility = 'hidden';  
    return this;
}

HTMLElement.prototype.show = function() {
    this.style.visibility = 'visible';  
    return this;
}

document.querySelector(".test1").hide();
// $('.test1')[0].hide();   // usage with jQuery

of course this not implement jQuery 'each' (given in @JamesAllardice answer) because we use pure js here.

Working example is here.

Printing one character at a time from a string, using the while loop

This will print each character in text

text = raw_input("Give some input:  ")
for i in range(0,len(text)):
   print(text[i])

Find if a textbox is disabled or not using jquery

 if($("element_selector").attr('disabled') || $("element_selector").prop('disabled'))
 {

    // code when element is disabled

  }

What’s the difference between Response.Write() andResponse.Output.Write()?

Response.write() is used to display the normal text and Response.output.write() is used to display the formated text.

Where can I find the TypeScript version installed in Visual Studio?

The tsc -v command run technically reads the TypeScript compiler version within the SDK directory set within the Windows Path variable. This doesn't necessarily reflect the latest version installed as the Path variable is not updated with subsequent installations.

The version that VS.NET uses to compile the TypeScript is what's in the project's configuration:

<TypeScriptToolsVersion>1.5</TypeScriptToolsVersion>

To help explain this more in detail I created the following post which has the specifics on the TypeScript versions installed, and which version VS.NET uses to compile the TypeScript files.

Which Version of TypeScript is Installed and Which Version is Visual Studio Using?

I also added a feature request on Microsoft Connect to make viewing and switching the TypeScript targeted version in VS.NET easier. This isn't really a TypeScript feature request as much as it is a VS.NET IDE enhancement.

Allow switching TypeScript configured version from Project Properties IDE

Pandas every nth row

There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__.

df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

For example, to get every 2 rows, you can do

df[::2]

   a  b  c
0  x  x  x
2  x  x  x
4  x  x  x

There's also GroupBy.first/GroupBy.head, you group on the index:

df.index // 2
# Int64Index([0, 0, 1, 1, 2], dtype='int64')

df.groupby(df.index // 2).first()
# Alternatively,
# df.groupby(df.index // 2).head(1)

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do

# df.groupby(np.arange(len(df)) // 2).first()
df.groupby(pd.RangeIndex(len(df)) // 2).first()

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

Deserializing JSON data to C# using JSON.NET

Use

var rootObject =  JsonConvert.DeserializeObject<RootObject>(string json);

Create your classes on JSON 2 C#


Json.NET documentation: Serializing and Deserializing JSON with Json.NET

How do I add an "Add to Favorites" button or link on my website?

I have faced some problems with rel="sidebar". when I add it in link tag bookmarking will work on FF but stop working in other browser. so I fix that by adding rel="sidebar" dynamic by code:

jQuery('.bookmarkMeLink').click(function() {
    if (window.sidebar && window.sidebar.addPanel) { 
        // Mozilla Firefox Bookmark
        window.sidebar.addPanel(document.title,window.location.href,'');
    }
    else if(window.sidebar && jQuery.browser.mozilla){
        //for other version of FF add rel="sidebar" to link like this:
        //<a id="bookmarkme" href="#" rel="sidebar" title="bookmark this page">Bookmark This Page</a>
        jQuery(this).attr('rel', 'sidebar');
    }
    else if(window.external && ('AddFavorite' in window.external)) { 
        // IE Favorite
        window.external.AddFavorite(location.href,document.title); 
    } else if(window.opera && window.print) { 
        // Opera Hotlist
        this.title=document.title;
        return true;
    } else { 
        // webkit - safari/chrome
        alert('Press ' + (navigator.userAgent.toLowerCase().indexOf('mac') != - 1 ? 'Command/Cmd' : 'CTRL') + ' + D to bookmark this page.');

    }
});

How can I use goto in Javascript?

// example of goto in javascript:

var i, j;
loop_1:
    for (i = 0; i < 3; i++) { //The first for statement is labeled "loop_1"
        loop_2:
            for (j = 0; j < 3; j++) { //The second for statement is labeled "loop_2"
                if (i === 1 && j === 1) {
                    continue loop_1;
                }
                console.log('i = ' + i + ', j = ' + j);
            }
        }

Centering floating divs within another div

In my case, I could not get the answer by @Sampson to work for me, at best I got a single column centered on the page. In the process however, I learned how the float actually works and created this solution. At it's core the fix is very simple but hard to find as evident by this thread which has had more than 146k views at the time of this post without mention.

All that is needed is to total the amount of screen space width that the desired layout will occupy then make the parent the same width and apply margin:auto. That's it!

The elements in the layout will dictate the width and height of the "outer" div. Take each "myFloat" or element's width or height + its borders + its margins and its paddings and add them all together. Then add the other elements together in the same fashion. This will give you the parent width. They can all be somewhat different sizes and you can do this with fewer or more elements.

Ex.(each element has 2 sides so border, margin and padding get multiplied x2)

So an element that has a width of 10px, border 2px, margin 6px, padding 3px would look like this: 10 + 4 + 12 + 6 = 32

Then add all of your element's totaled widths together.

Element 1 = 32
Element 2 = 24
Element 3 = 32
Element 4 = 24

In this example the width for the "outer" div would be 112.

_x000D_
_x000D_
.outer {_x000D_
  /* floats + margins + borders = 270 */_x000D_
  max-width: 270px;_x000D_
  margin: auto;_x000D_
  height: 80px;_x000D_
  border: 1px;_x000D_
  border-style: solid;_x000D_
}_x000D_
_x000D_
.myFloat {_x000D_
    /* 3 floats x 50px = 150px */_x000D_
    width: 50px;_x000D_
    /* 6 margins x 10px = 60 */_x000D_
    margin: 10px;_x000D_
    /* 6 borders x 10px = 60 */_x000D_
    border: 10px solid #6B6B6B;_x000D_
    float: left;_x000D_
    text-align: center;_x000D_
    height: 40px;_x000D_
}
_x000D_
<div class="outer">_x000D_
  <div class="myFloat">Float 1</div>_x000D_
  <div class="myFloat">Float 2</div>_x000D_
  <div class="myFloat">Float 3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_