Programs & Examples On #Render to string

error: pathspec 'test-branch' did not match any file(s) known to git

This error can also appear if your git branch is not correct even though case sensitive wise. In my case I was getting this error as actual branch name was "CORE-something" but I was taking pull like "core-something".

How to test that a registered variable is not empty?

when: myvar | default('', true) | trim != ''

I use | trim != '' to check if a variable has an empty value or not. I also always add the | default(..., true) check to catch when myvar is undefined too.

SELECT with a Replace()

if you want any hope of ever using an index, store the data in a consistent manner (with the spaces removed). Either just remove the spaces or add a persisted computed column, Then you can just select from that column and not have to add all the space removing overhead every time you run your query.

add a PERSISTED computed column:

ALTER TABLE Contacts ADD PostcodeSpaceFree AS Replace(Postcode, ' ', '') PERSISTED 
go
CREATE NONCLUSTERED INDEX IX_Contacts_PostcodeSpaceFree 
ON Contacts (PostcodeSpaceFree) --INCLUDE (covered columns here!!)
go

to just fix the column by removing the spaces use:

UPDATE Contacts
    SET Postcode=Replace(Postcode, ' ', '')

now you can search like this, either select can use an index:

--search the PERSISTED computed column
SELECT 
    PostcodeSpaceFree 
    FROM Contacts
    WHERE PostcodeSpaceFree  LIKE 'NW101%'

or

--search the fixed (spaces removed column)
SELECT 
    Postcode
    FROM Contacts
    WHERE PostcodeLIKE 'NW101%'

Array from dictionary keys in swift

Swift 3 & Swift 4

componentArray = Array(dict.keys) // for Dictionary

componentArray = dict.allKeys // for NSDictionary

error C4996: 'scanf': This function or variable may be unsafe in c programming

You can add "_CRT_SECURE_NO_WARNINGS" in Preprocessor Definitions.

Right-click your project->Properties->Configuration Properties->C/C++ ->Preprocessor->Preprocessor Definitions.

enter image description here

127 Return code from $?

127 - command not found

example: $caat The error message will

bash:

caat: command not found

now you check using echo $?

Spark Kill Running Application

  • copy past the application Id from the spark scheduler, for instance application_1428487296152_25597
  • connect to the server that have launch the job
  • yarn application -kill application_1428487296152_25597

maven "cannot find symbol" message unhelpful

I was getting a similar problem in Eclipse STS when trying to run a Maven install on a project. I had changed some versions in the dependencies of my pom.xml file for that project and the projects that those dependencies pointed to. I solved it by running a Maven install on all the projects I changed and then running install on the original one again.

How to use Chrome's network debugger with redirects

This has been changed since v32, thanks to @Daniel Alexiuc & @Thanatos for their comments.


Current (= v32)

At the top of the "Network" tab of DevTools, there's a checkbox to switch on the "Preserve log" functionality. If it is checked, the network log is preserved on page load.

Chrome v33 DevTools Network Tab: Preserve Log

The little red dot on the left now has the purpose to switch network logging on and off completely.


Older versions

In older versions of Chrome (v21 here), there's a little, clickable red dot in the footer of the "Network" tab.

Chrome v22 DevTools Network Tab: Preserve Log Upon Navigation

If you hover over it, it will tell you, that it will "Preserve Log Upon Navigation" when it is activated. It holds the promise.

Bootstrap 3 Glyphicons are not working

If you're using a CDN for the bootstrap CSS files it may be the culprit, as the glyph files (e.g. glyphicons-halflings-regular.woff) are taken from the CDN as well.

In my case, I faced this issue using Microsoft's CDN, but switching to MaxCDN resolved it.

How do I convert a C# List<string[]> to a Javascript array?

Many way to Json Parse but i have found most effective way to

 @model  List<string[]>

     <script>

         function DataParse() {
             var model = '@Html.Raw(Json.Encode(Model))';
             var data = JSON.parse(model);  

            for (i = 0; i < data.length; i++) {
            ......
             }

     </script>

This project references NuGet package(s) that are missing on this computer

I had this when the csproj and sln files were in the same folder (stupid, I know). Once I moved to sln file to the folder above the csproj folder my so

How can I dynamically add a directive in AngularJS?

Inspired from many of the previous answers I have came up with the following "stroman" directive that will replace itself with any other directives.

app.directive('stroman', function($compile) {
  return {
    link: function(scope, el, attrName) {
      var newElem = angular.element('<div></div>');
      // Copying all of the attributes
      for (let prop in attrName.$attr) {
        newElem.attr(prop, attrName[prop]);
      }
      el.replaceWith($compile(newElem)(scope)); // Replacing
    }
  };
});

Important: Register the directives that you want to use with restrict: 'C'. Like this:

app.directive('my-directive', function() {
  return {
    restrict: 'C',
    template: 'Hi there',
  };
});

You can use like this:

<stroman class="my-directive other-class" randomProperty="8"></stroman>

To get this:

<div class="my-directive other-class" randomProperty="8">Hi there</div>

Protip. If you don't want to use directives based on classes then you can change '<div></div>' to something what you like. E.g. have a fixed attribute that contains the name of the desired directive instead of class.

Numeric for loop in Django templates

Unfortunately, that's not supported in the Django template language. There are a couple of suggestions, but they seem a little complex. I would just put a variable in the context:

...
render_to_response('foo.html', {..., 'range': range(10), ...}, ...)
...

and in the template:

{% for i in range %}
     ...
{% endfor %}

How can I truncate a double to only two decimal places in Java?

If, for whatever reason, you don't want to use a BigDecimal you can cast your double to an int to truncate it.

If you want to truncate to the Ones place:

  • simply cast to int

To the Tenths place:

  • multiply by ten
  • cast to int
  • cast back to double
  • and divide by ten.

Hundreths place

  • multiply and divide by 100 etc.

Example:

static double truncateTo( double unroundedNumber, int decimalPlaces ){
    int truncatedNumberInt = (int)( unroundedNumber * Math.pow( 10, decimalPlaces ) );
    double truncatedNumber = (double)( truncatedNumberInt / Math.pow( 10, decimalPlaces ) );
    return truncatedNumber;
}

In this example, decimalPlaces would be the number of places PAST the ones place you wish to go, so 1 would round to the tenths place, 2 to the hundredths, and so on (0 rounds to the ones place, and negative one to the tens, etc.)

Selecting Folder Destination in Java?

try something like this

JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("select folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);

How to delete or change directory of a cloned git repository on a local computer

Just move it :)

command line :

move "C:\Documents and Setings\$USER\project" C:\project

or just drag the folder in explorer.

Git won't care where it is - all the metadata for the repository is inside a folder called .git inside your project folder.

Can you force a React component to rerender without calling setState?

Another way is calling setState, AND preserve state:

this.setState(prevState=>({...prevState}));

How to send email by using javascript or jquery

You can do it server-side with nodejs.

Check out the popular Nodemailer package. There are plenty of transports and plugins for integrating with services like AWS SES and SendGrid!

The following example uses SES transport (Amazon SES):

let nodemailer = require("nodemailer");
let aws = require("aws-sdk");
let transporter = nodemailer.createTransport({
  SES: new aws.SES({ apiVersion: "2010-12-01" })
});

Rendering HTML in a WebView with custom CSS

It's as simple as is:

WebView webview = (WebView) findViewById(R.id.webview);
webview.loadUrl("file:///android_asset/some.html");

And your some.html needs to contain something like:

<link rel="stylesheet" type="text/css" href="style.css" />

Check if MySQL table exists or not

Updated mysqli version:

if ($result = $mysqli->query("SHOW TABLES LIKE '".$table."'")) {
    if($result->num_rows == 1) {
        echo "Table exists";
    }
}
else {
    echo "Table does not exist";
}

Original mysql version:

if(mysql_num_rows(mysql_query("SHOW TABLES LIKE '".$table."'"))==1) 
    echo "Table exists";
else echo "Table does not exist";

Referenced from the PHP docs.

How to check if an element exists in the xml using xpath?

Use:

boolean(/*/*[@subjectIdentifier="Primary"]/*/*/*/*
                           [name()='AttachedXml' 
                          and 
                            namespace-uri()='http://xml.mycompany.com/XMLSchema'
                           ]
       )

OpenVPN failed connection / All TAP-Win32 adapters on this system are currently in use

I found a solution to this. It's bloody witchcraft, but it works.

When you install the client, open Control Panel > Network Connections.

You'll see a disabled network connection that was added by the TAP installer (Local Area Connection 3 or some such).

Right Click it, click Enable.

The device will not reset itself to enabled, but that's ok; try connecting w/ the client again. It'll work.

Angular - POST uploaded file

Look at my code, but be aware. I use async/await, because latest Chrome beta can read any es6 code, which gets by TypeScript with compilation. So, you must replace asyns/await by .then().

Input change handler:

/**
 * @param fileInput
 */
public psdTemplateSelectionHandler (fileInput: any){
    let FileList: FileList = fileInput.target.files;

    for (let i = 0, length = FileList.length; i < length; i++) {
        this.psdTemplates.push(FileList.item(i));
    }

    this.progressBarVisibility = true;
}

Submit handler:

public async psdTemplateUploadHandler (): Promise<any> {
    let result: any;

    if (!this.psdTemplates.length) {
        return;
    }

    this.isSubmitted = true;

    this.fileUploadService.getObserver()
        .subscribe(progress => {
            this.uploadProgress = progress;
        });

    try {
        result = await this.fileUploadService.upload(this.uploadRoute, this.psdTemplates);
    } catch (error) {
        document.write(error)
    }

    if (!result['images']) {
        return;
    }

    this.saveUploadedTemplatesData(result['images']);
    this.redirectService.redirect(this.redirectRoute);
}

FileUploadService. That service also stored uploading progress in progress$ property, and in other places, you can subscribe on it and get new value every 500ms.

import { Component } from 'angular2/core';
import { Injectable } from 'angular2/core';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/share';

@Injectable()
export class FileUploadService {
/**
 * @param Observable<number>
 */
private progress$: Observable<number>;

/**
 * @type {number}
 */
private progress: number = 0;

private progressObserver: any;

constructor () {
    this.progress$ = new Observable(observer => {
        this.progressObserver = observer
    });
}

/**
 * @returns {Observable<number>}
 */
public getObserver (): Observable<number> {
    return this.progress$;
}

/**
 * Upload files through XMLHttpRequest
 *
 * @param url
 * @param files
 * @returns {Promise<T>}
 */
public upload (url: string, files: File[]): Promise<any> {
    return new Promise((resolve, reject) => {
        let formData: FormData = new FormData(),
            xhr: XMLHttpRequest = new XMLHttpRequest();

        for (let i = 0; i < files.length; i++) {
            formData.append("uploads[]", files[i], files[i].name);
        }

        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(JSON.parse(xhr.response));
                } else {
                    reject(xhr.response);
                }
            }
        };

        FileUploadService.setUploadUpdateInterval(500);

        xhr.upload.onprogress = (event) => {
            this.progress = Math.round(event.loaded / event.total * 100);

            this.progressObserver.next(this.progress);
        };

        xhr.open('POST', url, true);
        xhr.send(formData);
    });
}

/**
 * Set interval for frequency with which Observable inside Promise will share data with subscribers.
 *
 * @param interval
 */
private static setUploadUpdateInterval (interval: number): void {
    setInterval(() => {}, interval);
}
}

How to Lock the data in a cell in excel using vba

You can first choose which cells you don't want to be protected (to be user-editable) by setting the Locked status of them to False:

Worksheets("Sheet1").Range("B2:C3").Locked = False

Then, you can protect the sheet, and all the other cells will be protected. The code to do this, and still allow your VBA code to modify the cells is:

Worksheets("Sheet1").Protect UserInterfaceOnly:=True

or

Call Worksheets("Sheet1").Protect(UserInterfaceOnly:=True)

Improving bulk insert performance in Entity framework

Better way is to skip the Entity Framework entirely for this operation and rely on SqlBulkCopy class. Other operations can continue using EF as before.

That increases the maintenance cost of the solution, but anyway helps reduce time required to insert large collections of objects into the database by one to two orders of magnitude compared to using EF.

Here is an article that compares SqlBulkCopy class with EF for objects with parent-child relationship (also describes changes in design required to implement bulk insert): How to Bulk Insert Complex Objects into SQL Server Database

Twitter API - Display all tweets with a certain hashtag?

UPDATE for v1.1:

Rather than giving q="search_string" give it q="hashtag" in URL encoded form to return results with HASHTAG ONLY. So your query would become:

    GET https://api.twitter.com/1.1/search/tweets.json?q=%23freebandnames

%23 is URL encoded form of #. Try the link out in your browser and it should work.

You can optimize the query by adding since_id and max_id parameters detailed here. Hope this helps !

Note: Search API is now a OAUTH authenticated call, so please include your access_tokens to the above call

Updated

Twitter Search doc link: https://developer.twitter.com/en/docs/tweets/search/api-reference/get-search-tweets.html

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '''')' at line 2

There is a single quote in $submitsubject or $submit_message

Why is this a problem?

The single quote char terminates the string in MySQL and everything past that is treated as a sql command. You REALLY don't want to write your sql like that. At best, your application will break intermittently (as you're observing) and at worst, you have just introduced a huge security vulnerability.

Imagine if someone submitted '); DROP TABLE private_messages; in submit message.

Your SQL Command would be:

INSERT INTO private_messages (to_id, from_id, time_sent, subject, message) 
        VALUES('sender_id', 'id', now(),'subjet','');

DROP TABLE private_messages;

Instead you need to properly sanitize your values.

AT A MINIMUM you must run each value through mysql_real_escape_string() but you should really be using prepared statements.

If you were using mysql_real_escape_string() your code would look like this:

if($_POST['submit_message']){

if($_POST['form_subject']==""){
    $submit_subject="(no subject)";
}else{
    $submit_subject=mysql_real_escape_string($_POST['form_subject']); 
}
$submit_message=mysql_real_escape_string($_POST['form_message']);
$sender_id = mysql_real_escape_string($_POST['sender_id']);

Here is a great article on prepared statements and PDO.

Search an Oracle database for tables with specific column names?

To find all tables with a particular column:

select owner, table_name from all_tab_columns where column_name = 'ID';

To find tables that have any or all of the 4 columns:

select owner, table_name, column_name
from all_tab_columns
where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS');

To find tables that have all 4 columns (with none missing):

select owner, table_name
from all_tab_columns
where column_name in ('ID', 'FNAME', 'LNAME', 'ADDRESS')
group by owner, table_name
having count(*) = 4;

ReactJS Two components communicating

OK, there are few ways to do it, but I exclusively want focus on using store using Redux which makes your life much easier for these situations rather than give you a quick solution only for this case, using pure React will end up mess up in real big application and communicating between Components becomes harder and harder as the application grows...

So what Redux does for you?

Redux is like local storage in your application which can be used whenever you need data to be used in different places in your application...

Basically, Redux idea comes from flux originally, but with some fundamental changes including the concept of having one source of truth by creating only one store...

Look at the graph below to see some differences between Flux and Redux...

Redux and Flux

Consider applying Redux in your application from the start if your application needs communication between Components...

Also reading these words from Redux Documentation could be helpful to start with:

As the requirements for JavaScript single-page applications have become increasingly complicated, our code must manage more state than ever before. This state can include server responses and cached data, as well as locally created data that has not yet been persisted to the server. UI state is also increasing in complexity, as we need to manage active routes, selected tabs, spinners, pagination controls, and so on.

Managing this ever-changing state is hard. If a model can update another model, then a view can update a model, which updates another model, and this, in turn, might cause another view to update. At some point, you no longer understand what happens in your app as you have lost control over the when, why, and how of its state. When a system is opaque and non-deterministic, it's hard to reproduce bugs or add new features.

As if this wasn't bad enough, consider the new requirements becoming common in front-end product development. As developers, we are expected to handle optimistic updates, server-side rendering, fetching data before performing route transitions, and so on. We find ourselves trying to manage a complexity that we have never had to deal with before, and we inevitably ask the question: is it time to give up? The answer is no.

This complexity is difficult to handle as we're mixing two concepts that are very hard for the human mind to reason about: mutation and asynchronicity. I call them Mentos and Coke. Both can be great in separation, but together they create a mess. Libraries like React attempt to solve this problem in the view layer by removing both asynchrony and direct DOM manipulation. However, managing the state of your data is left up to you. This is where Redux enters.

Following in the steps of Flux, CQRS, and Event Sourcing, Redux attempts to make state mutations predictable by imposing certain restrictions on how and when updates can happen. These restrictions are reflected in the three principles of Redux.

Which characters make a URL invalid?

In general URIs as defined by RFC 3986 (see Section 2: Characters) may contain any of the following 84 characters:

ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~:/?#[]@!$&'()*+,;=

Note that this list doesn't state where in the URI these characters may occur.

Any other character needs to be encoded with the percent-encoding (%hh). Each part of the URI has further restrictions about what characters need to be represented by an percent-encoded word.

Round double in two decimal places in C#?

Use an interpolated string, this generates a rounded up string:

var strlen = 6;
$"{48.485:F2}"

Output

"48.49"

How do I convert array of Objects into one Object in JavaScript?

I like the functional approach to achieve this task:

var arr = [{ key:"11", value:"1100" }, { key:"22", value:"2200" }];
var result = arr.reduce(function(obj,item){
  obj[item.key] = item.value; 
  return obj;
}, {});

Note: Last {} is the initial obj value for reduce function, if you won't provide the initial value the first arr element will be used (which is probably undesirable).

https://jsfiddle.net/GreQ/2xa078da/

Atom menu is missing. How do I re-enable

Press Alt + v and select Toggle menu bar option.

Where do I find the line number in the Xcode editor?

In Preferences->Text Editing-> Show: Line numbers you can enable the line numbers on the left hand side of the file.

Could not find or load main class org.gradle.wrapper.GradleWrapperMain

I followed the answers from above when i ran into this. And If you are having this issue than make sure to force push both jar and properties files. After these two, i stopped getting this issue.

git add -f gradle/wrapper/gradle-wrapper.jar
git add -f gradle/wrapper/gradle-wrapper.properties

How to get object size in memory?

OK, this question has been answered and answer accepted but someone asked me to put my answer so there you go.

First of all, it is not possible to say for sure. It is an internal implementation detail and not documented. However, based on the objects included in the other object. Now, how do we calculate the memory requirement for our cached objects?

I had previously touched this subject in this article:

Now, how do we calculate the memory requirement for our cached objects? Well, as most of you would know, Int32 and float are four bytes, double and DateTime 8 bytes, char is actually two bytes (not one byte), and so on. String is a bit more complex, 2*(n+1), where n is the length of the string. For objects, it will depend on their members: just sum up the memory requirement of all its members, remembering all object references are simply 4 byte pointers on a 32 bit box. Now, this is actually not quite true, we have not taken care of the overhead of each object in the heap. I am not sure if you need to be concerned about this, but I suppose, if you will be using lots of small objects, you would have to take the overhead into consideration. Each heap object costs as much as its primitive types, plus four bytes for object references (on a 32 bit machine, although BizTalk runs 32 bit on 64 bit machines as well), plus 4 bytes for the type object pointer, and I think 4 bytes for the sync block index. Why is this additional overhead important? Well, let’s imagine we have a class with two Int32 members; in this case, the memory requirement is 16 bytes and not 8.

ld cannot find an existing library

The problem is the linker is looking for libmagic.so but you only have libmagic.so.1

A quick hack is to symlink libmagic.so.1 to libmagic.so

Cast from VARCHAR to INT - MySQL

As described in Cast Functions and Operators:

The type for the result can be one of the following values:

  • BINARY[(N)]
  • CHAR[(N)]
  • DATE
  • DATETIME
  • DECIMAL[(M[,D])]
  • SIGNED [INTEGER]
  • TIME
  • UNSIGNED [INTEGER]

Therefore, you should use:

SELECT CAST(PROD_CODE AS UNSIGNED) FROM PRODUCT

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

I used a hybrid approach for fragments containing a list view. It seems to be performant since I don't replace the current fragment but rather add the new fragment and hide the current one. I have the following method in the activity that hosts my fragments:

public void addFragment(Fragment currentFragment, Fragment targetFragment, String tag) {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.setCustomAnimations(0,0,0,0);
    transaction.hide(currentFragment);
    // use a fragment tag, so that later on we can find the currently displayed fragment
    transaction.add(R.id.frame_layout, targetFragment, tag)
            .addToBackStack(tag)
            .commit();
}

I use this method in my fragment (containing the list view) whenever a list item is clicked/tapped (and thus I need to launch/display the details fragment):

FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
SearchFragment currentFragment = (SearchFragment) fragmentManager.findFragmentByTag(getFragmentTags()[0]);
DetailsFragment detailsFragment = DetailsFragment.newInstance("some object containing some details");
((MainActivity) getActivity()).addFragment(currentFragment, detailsFragment, "Details");

getFragmentTags() returns an array of strings that I use as tags for different fragments when I add a new fragment (see transaction.add method in addFragment method above).

In the fragment containing the list view, I do this in its onPause() method:

@Override
public void onPause() {
    // keep the list view's state in memory ("save" it) 
    // before adding a new fragment or replacing current fragment with a new one
    ListView lv =  (ListView) getActivity().findViewById(R.id.listView);
    mListViewState = lv.onSaveInstanceState();
    super.onPause();
}

Then in onCreateView of the fragment (actually in a method that is invoked in onCreateView), I restore the state:

// Restore previous state (including selected item index and scroll position)
if(mListViewState != null) {
    Log.d(TAG, "Restoring the listview's state.");
    lv.onRestoreInstanceState(mListViewState);
}

How to pre-populate the sms body text via an html link

We found a proposed method and tested:

<a href="sms:12345678?body=Hello my friend">Send SMS</a>

Here are the results:

  • iPhone4 - fault (empty body of message);
  • Nokia N8 - ok (body of message - "Hello my friend", To "12345678");
  • HTC Mozart - fault (message "unsupported page" (after click on the "Send sms" link));
  • HTC Desire - fault (message "Invalid recipients(s):
    <12345678?body=Hellomyfriend>"(after click on the "Send sms" link)).

I therefore conclude it doesn't really work - with this method at least.

Display loading image while post with ajax

make sure to change in ajax call

async: true,
type: "GET",
dataType: "html",

Importing a CSV file into a sqlite3 database table using Python

You're right that .import is the way to go, but that's a command from the SQLite3.exe shell. A lot of the top answers to this question involve native python loops, but if your files are large (mine are 10^6 to 10^7 records), you want to avoid reading everything into pandas or using a native python list comprehension/loop (though I did not time them for comparison).

For large files, I believe the best option is to create the empty table in advance using sqlite3.execute("CREATE TABLE..."), strip the headers from your CSV files, and then use subprocess.run() to execute sqlite's import statement. Since the last part is I believe the most pertinent, I will start with that.

subprocess.run()

from pathlib import Path
db_name = Path('my.db').resolve()
csv_file = Path('file.csv').resolve()
result = subprocess.run(['sqlite3',
                         str(db_name),
                         '-cmd',
                         '.mode csv',
                         '.import '+str(csv_file).replace('\\','\\\\')
                                 +' <table_name>'],
                        capture_output=True)

Explanation
From the command line, the command you're looking for is sqlite3 my.db -cmd ".mode csv" ".import file.csv table". subprocess.run() runs a command line process. The argument to subprocess.run() is a sequence of strings which are interpreted as a command followed by all of it's arguments.

  • sqlite3 my.db opens the database
  • -cmd flag after the database allows you to pass multiple follow on commands to the sqlite program. In the shell, each command has to be in quotes, but here, they just need to be their own element of the sequence
  • '.mode csv' does what you'd expect
  • '.import '+str(csv_file).replace('\\','\\\\')+' <table_name>' is the import command.
    Unfortunately, since subprocess passes all follow-ons to -cmd as quoted strings, you need to double up your backslashes if you have a windows directory path.

Stripping Headers

Not really the main point of the question, but here's what I used. Again, I didn't want to read the whole files into memory at any point:

with open(csv, "r") as source:
    source.readline()
    with open(str(csv)+"_nohead", "w") as target:
        shutil.copyfileobj(source, target)

PHP - concatenate or directly insert variables in string

I know this question already has a chosen answer, but I found this article that evidently shows that string interpolation works faster than concatenation. It might be helpful for those who are still in doubt.

Load More Posts Ajax Button in WordPress

UPDATE 24.04.2016.

I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)

EDIT

I've tested this on Twenty Fifteen and it's working, so it should be working for you.

In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:

    <div id="ajax-posts" class="row">
        <?php
            $postsPerPage = 3;
            $args = array(
                    'post_type' => 'post',
                    'posts_per_page' => $postsPerPage,
                    'cat' => 8
            );

            $loop = new WP_Query($args);

            while ($loop->have_posts()) : $loop->the_post();
        ?>

         <div class="small-12 large-4 columns">
                <h1><?php the_title(); ?></h1>
                <p><?php the_content(); ?></p>
         </div>

         <?php
                endwhile;
        wp_reset_postdata();
         ?>
    </div>
    <div id="more_posts">Load More</div>

This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with

$cat_id = get_query_var('cat');

This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like

<div id="more_posts" data-category="<?php echo $cat_id; ?>">>Load More</div>

And pull the category with

var cat = $('#more_posts').data('category');

But for now, you can leave this out.

Next in functions.php I added

wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
    'ajaxurl' => admin_url( 'admin-ajax.php' ),
    'noposts' => __('No older posts found', 'twentyfifteen'),
));

Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.

At the end of the functions.php file I added the function that will load your posts:

function more_post_ajax(){

    $ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
    $page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;

    header("Content-Type: text/html");

    $args = array(
        'suppress_filters' => true,
        'post_type' => 'post',
        'posts_per_page' => $ppp,
        'cat' => 8,
        'paged'    => $page,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :  while ($loop -> have_posts()) : $loop -> the_post();
        $out .= '<div class="small-12 large-4 columns">
                <h1>'.get_the_title().'</h1>
                <p>'.get_the_content().'</p>
         </div>';

    endwhile;
    endif;
    wp_reset_postdata();
    die($out);
}

add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');

Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.

If you've added your category in the loader, you'd add:

$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';

And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.

Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment

var ppp = 3; // Post per page
var cat = 8;
var pageNumber = 1;


function load_posts(){
    pageNumber++;
    var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
    $.ajax({
        type: "POST",
        dataType: "html",
        url: ajax_posts.ajaxurl,
        data: str,
        success: function(data){
            var $data = $(data);
            if($data.length){
                $("#ajax-posts").append($data);
                $("#more_posts").attr("disabled",false);
            } else{
                $("#more_posts").attr("disabled",true);
            }
        },
        error : function(jqXHR, textStatus, errorThrown) {
            $loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
        }

    });
    return false;
}

$("#more_posts").on("click",function(){ // When btn is pressed.
    $("#more_posts").attr("disabled",true); // Disable the button, temp.
    load_posts();
});

Saved it, tested it, and it works :)

Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD

enter image description here

enter image description here

enter image description here

UPDATE

For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with

$(window).on('scroll', function () {
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer

$(window).on('scroll', function(){
    if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
        if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
                load_posts();
        }
    }
});

Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.

You can easily check it by putting console.logs in your code and see in the inspector what they throw out

$(window).on('scroll', function () {
    console.log($(window).scrollTop() + $(window).height());
    console.log($(document).height() - 100);
    if ($(window).scrollTop() + $(window).height()  >= $(document).height() - 100) {
        load_posts();
    }
});

And just adjust accordingly ;)

Hope this helps :) If you have any questions just ask.

How to create local notifications?

In appdelegate.m file write the follwing code in applicationDidEnterBackground to get the local notification

- (void)applicationDidEnterBackground:(UIApplication *)application
{
   UILocalNotification *notification = [[UILocalNotification alloc]init];
   notification.repeatInterval = NSDayCalendarUnit;
   [notification setAlertBody:@"Hello world"];
   [notification setFireDate:[NSDate dateWithTimeIntervalSinceNow:1]];
   [notification setTimeZone:[NSTimeZone  defaultTimeZone]];
   [application setScheduledLocalNotifications:[NSArray arrayWithObject:notification]];
}

Push eclipse project to GitHub with EGit

Simple Steps:

-Open Eclipse.

  • Select Project which you want to push on github->rightclick.
  • select Team->share Project->Git->Create repository->finish.(it will ask to login in Git account(popup).
  • Right click again to Project->Team->commit. you are done

Showing the same file in both columns of a Sublime Text window

I would suggest you to use Origami. Its a great plugin for splitting the screen. For better information on keyboard short cuts install it and after restarting Sublime text open Preferences->Package Settings -> Origami -> Key Bindings - Default

For specific to your question I would suggest you to see the short cuts related to cloning of files in the above mentioned file.

How to convert hex string to Java string?

Just another way to convert hex string to java string:

public static String unHex(String arg) {        

    String str = "";
    for(int i=0;i<arg.length();i+=2)
    {
        String s = arg.substring(i, (i + 2));
        int decimal = Integer.parseInt(s, 16);
        str = str + (char) decimal;
    }       
    return str;
}

Filter an array using a formula (without VBA)

This will do it if you only want the first "B" value, you can sub a cell address for "B" if you want to make it more generic.

=INDEX(A2:A6,SUMPRODUCT(MATCH(TRUE,(B2:B6)="B",0)),1)

To use this based on two columns, just concatenate inside the match:

=INDEX(A2:A6,SUMPRODUCT(MATCH(TRUE,(A2:A6&B2:B6)=("3"&"B"),0)),1)

How do I fill arrays in Java?

In Java-8 you can use IntStream to produce a stream of numbers that you want to repeat, and then convert it to array. This approach produces an expression suitable for use in an initializer:

int[] data = IntStream.generate(() -> value).limit(size).toArray();

Above, size and value are expressions that produce the number of items that you want tot repeat and the value being repeated.

Demo.

VBA Excel 2-Dimensional Arrays

Here's A generic VBA Array To Range function that writes an array to the sheet in a single 'hit' to the sheet. This is much faster than writing the data into the sheet one cell at a time in loops for the rows and columns... However, there's some housekeeping to do, as you must specify the size of the target range correctly.

This 'housekeeping' looks like a lot of work and it's probably rather slow: but this is 'last mile' code to write to the sheet, and everything is faster than writing to the worksheet. Or at least, so much faster that it's effectively instantaneous, compared with a read or write to the worksheet, even in VBA, and you should do everything you possibly can in code before you hit the sheet.

A major component of this is error-trapping that I used to see turning up everywhere . I hate repetitive coding: I've coded it all here, and - hopefully - you'll never have to write it again.

A VBA 'Array to Range' function

Public Sub ArrayToRange(rngTarget As Excel.Range, InputArray As Variant)
' Write an array to an Excel range in a single 'hit' to the sheet
' InputArray must be a 2-Dimensional structure of the form Variant(Rows, Columns)

' The target range is resized automatically to the dimensions of the array, with
' the top left cell used as the start point.

' This subroutine saves repetitive coding for a common VBA and Excel task.

' If you think you won't need the code that works around common errors (long strings
' and objects in the array, etc) then feel free to comment them out.

On Error Resume Next

'
' Author: Nigel Heffernan
' HTTP://Excellerando.blogspot.com
'
' This code is in te public domain: take care to mark it clearly, and segregate
' it from proprietary code if you intend to assert intellectual property rights
' or impose commercial confidentiality restrictions on that proprietary code

Dim rngOutput As Excel.Range

Dim iRowCount   As Long
Dim iColCount   As Long
Dim iRow        As Long
Dim iCol        As Long
Dim arrTemp     As Variant
Dim iDimensions As Integer

Dim iRowOffset  As Long
Dim iColOffset  As Long
Dim iStart      As Long


Application.EnableEvents = False
If rngTarget.Cells.Count > 1 Then
    rngTarget.ClearContents
End If
Application.EnableEvents = True

If IsEmpty(InputArray) Then
    Exit Sub
End If


If TypeName(InputArray) = "Range" Then
    InputArray = InputArray.Value
End If

' Is it actually an array? IsArray is sadly broken so...
If Not InStr(TypeName(InputArray), "(") Then
    rngTarget.Cells(1, 1).Value2 = InputArray
    Exit Sub
End If


iDimensions = ArrayDimensions(InputArray)

If iDimensions < 1 Then

    rngTarget.Value = CStr(InputArray)

ElseIf iDimensions = 1 Then

    iRowCount = UBound(InputArray) - LBound(InputArray)
    iStart = LBound(InputArray)
    iColCount = 1

    If iRowCount > (655354 - rngTarget.Row) Then
        iRowCount = 655354 + iStart - rngTarget.Row
        ReDim Preserve InputArray(iStart To iRowCount)
    End If

    iRowCount = UBound(InputArray) - LBound(InputArray)
    iColCount = 1

    ' It's a vector. Yes, I asked for a 2-Dimensional array. But I'm feeling generous.
    ' By convention, a vector is presented in Excel as an arry of 1 to n rows and 1 column.
    ReDim arrTemp(LBound(InputArray, 1) To UBound(InputArray, 1), 1 To 1)
    For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
        arrTemp(iRow, 1) = InputArray(iRow)
    Next

    With rngTarget.Worksheet
        Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount))
        rngOutput.Value2 = arrTemp
        Set rngTarget = rngOutput
    End With

    Erase arrTemp

ElseIf iDimensions = 2 Then

    iRowCount = UBound(InputArray, 1) - LBound(InputArray, 1)
    iColCount = UBound(InputArray, 2) - LBound(InputArray, 2)

    iStart = LBound(InputArray, 1)

    If iRowCount > (65534 - rngTarget.Row) Then
        iRowCount = 65534 - rngTarget.Row
        InputArray = ArrayTranspose(InputArray)
        ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iRowCount)
        InputArray = ArrayTranspose(InputArray)
    End If


    iStart = LBound(InputArray, 2)
    If iColCount > (254 - rngTarget.Column) Then
        ReDim Preserve InputArray(LBound(InputArray, 1) To UBound(InputArray, 1), iStart To iColCount)
    End If



    With rngTarget.Worksheet

        Set rngOutput = .Range(rngTarget.Cells(1, 1), rngTarget.Cells(iRowCount + 1, iColCount + 1))

        Err.Clear
        Application.EnableEvents = False
        rngOutput.Value2 = InputArray
        Application.EnableEvents = True

        If Err.Number <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
                    If IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
                        InputArray(iRow, iCol) = Trim(InputArray(iRow, iCol))
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Formula = InputArray
        End If 'err<>0

        If Err <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)
                    If IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        If Left(InputArray(iRow, iCol), 1) = "=" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                        If Left(InputArray(iRow, iCol), 1) = "+" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                        If Left(InputArray(iRow, iCol), 1) = "*" Then
                            InputArray(iRow, iCol) = "'" & InputArray(iRow, iCol)
                        End If
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Value2 = InputArray
        End If 'err<>0

        If Err <> 0 Then
            For iRow = LBound(InputArray, 1) To UBound(InputArray, 1)
                For iCol = LBound(InputArray, 2) To UBound(InputArray, 2)

                    If IsObject(InputArray(iRow, iCol)) Then
                        InputArray(iRow, iCol) = "[OBJECT] " & TypeName(InputArray(iRow, iCol))
                    ElseIf IsArray(InputArray(iRow, iCol)) Then
                        InputArray(iRow, iCol) = Split(InputArray(iRow, iCol), ",")
                    ElseIf IsNumeric(InputArray(iRow, iCol)) Then
                        ' no action
                    Else
                        InputArray(iRow, iCol) = "" & InputArray(iRow, iCol)
                        If Len(InputArray(iRow, iCol)) > 255 Then
                            ' Block-write operations fail on strings exceeding 255 chars. You *have*
                            ' to go back and check, and write this masterpiece one cell at a time...
                            InputArray(iRow, iCol) = Left(Trim(InputArray(iRow, iCol)), 255)
                        End If
                    End If
                Next iCol
            Next iRow
            Err.Clear
            rngOutput.Text = InputArray
        End If 'err<>0

        If Err <> 0 Then
            Application.ScreenUpdating = False
            Application.Calculation = xlCalculationManual
            iRowOffset = LBound(InputArray, 1) - 1
            iColOffset = LBound(InputArray, 2) - 1
            For iRow = 1 To iRowCount
                If iRow Mod 100 = 0 Then
                    Application.StatusBar = "Filling range... " & CInt(100# * iRow / iRowCount) & "%"
                End If
                For iCol = 1 To iColCount
                    rngOutput.Cells(iRow, iCol) = InputArray(iRow + iRowOffset, iCol + iColOffset)
                Next iCol
            Next iRow
            Application.StatusBar = False
            Application.ScreenUpdating = True


        End If 'err<>0


        Set rngTarget = rngOutput   ' resizes the range This is useful, *most* of the time

    End With

End If

End Sub

You will need the source for ArrayDimensions:

This API declaration is required in the module header:

Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" _
                   (Destination As Any, _
                    Source As Any, _
                    ByVal Length As Long)

...And here's the function itself:

Private Function ArrayDimensions(arr As Variant) As Integer
  '-----------------------------------------------------------------
  ' will return:
  ' -1 if not an array
  ' 0  if an un-dimmed array
  ' 1  or more indicating the number of dimensions of a dimmed array
  '-----------------------------------------------------------------


  ' Retrieved from Chris Rae's VBA Code Archive - http://chrisrae.com/vba
  ' Code written by Chris Rae, 25/5/00

  ' Originally published by R. B. Smissaert.
  ' Additional credits to Bob Phillips, Rick Rothstein, and Thomas Eyde on VB2TheMax

  Dim ptr As Long
  Dim vType As Integer

  Const VT_BYREF = &H4000&

  'get the real VarType of the argument
  'this is similar to VarType(), but returns also the VT_BYREF bit
  CopyMemory vType, arr, 2

  'exit if not an array
  If (vType And vbArray) = 0 Then
    ArrayDimensions = -1
    Exit Function
  End If

  'get the address of the SAFEARRAY descriptor
  'this is stored in the second half of the
  'Variant parameter that has received the array
  CopyMemory ptr, ByVal VarPtr(arr) + 8, 4

  'see whether the routine was passed a Variant
  'that contains an array, rather than directly an array
  'in the former case ptr already points to the SA structure.
  'Thanks to Monte Hansen for this fix

  If (vType And VT_BYREF) Then
    ' ptr is a pointer to a pointer
    CopyMemory ptr, ByVal ptr, 4
  End If

  'get the address of the SAFEARRAY structure
  'this is stored in the descriptor

  'get the first word of the SAFEARRAY structure
  'which holds the number of dimensions
  '...but first check that saAddr is non-zero, otherwise
  'this routine bombs when the array is uninitialized

  If ptr Then
    CopyMemory ArrayDimensions, ByVal ptr, 2
  End If

End Function

Also: I would advise you to keep that declaration private. If you must make it a public Sub in another module, insert the Option Private Module statement in the module header. You really don't want your users calling any function with CopyMemoryoperations and pointer arithmetic.

SQL Server CASE .. WHEN .. IN statement

Try this...

SELECT
    AlarmEventTransactionTableTable.TxnID,
    CASE
        WHEN DeviceID IN('7', '10', '62', '58', '60',
                 '46', '48', '50', '137', '139',
                 '142', '143', '164') THEN '01'
        WHEN DeviceID IN('8', '9', '63', '59', '61',
                 '47', '49', '51', '138', '140',
                 '141', '144', '165') THEN '02'
        ELSE 'NA' END AS clocking,
    AlarmEventTransactionTable.DateTimeOfTxn
 FROM
    multiMAXTxn.dbo.AlarmEventTransactionTable

Just remove highlighted string

SELECT AlarmEventTransactionTableTable.TxnID, CASE AlarmEventTransactions.DeviceID WHEN DeviceID IN('7', '10', '62', '58', '60', ...)

Is there a goto statement in Java?

goto is not in Java

you have to use GOTO But it don't work correctly.in key java word it is not used. http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html

   public static void main(String[] args) {            
            GOTO me;
            //code;
            me:
            //code; 
            }   
   }

Simpler way to create dictionary of separate variables?

While this is probably an awful idea, it is along the same lines as rlotun's answer but it'll return the correct result more often.

import inspect
def getVarName(getvar):
  frame = inspect.currentframe()
  callerLocals = frame.f_back.f_locals
  for k, v in list(callerLocals.items()):
    if v is getvar():
      callerLocals.pop(k)
      try:
        getvar()
        callerLocals[k] = v
      except NameError:
        callerLocals[k] = v
        del frame
        return k
  del frame

You call it like this:

bar = True
foo = False
bean = False
fooName = getVarName(lambda: foo)
print(fooName) # prints "foo"

Is there an easy way to strike through text in an app widget?

You can use this:

remoteviews.setInt(R.id.YourTextView, "setPaintFlags", Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);

Of course you can also add other flags from the android.graphics.Paint class.

Is it possible to opt-out of dark mode on iOS 13?

In Xcode 12, you can change add as "appearances". This will work!!

How can I pass variable to ansible playbook in the command line?

This also worked for me if you want to use shell environment variables:

ansible-playbook -i "localhost," ldap.yaml --extra-vars="LDAP_HOST={{ lookup('env', 'LDAP_HOST') }} clustername=mycluster env=dev LDAP_USERNAME={{ lookup('env', 'LDAP_USERNAME') }} LDAP_PASSWORD={{ lookup('env', 'LDAP_PASSWORD') }}"

How to specify legend position in matplotlib in graph coordinates

You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend

import matplotlib.pyplot as plt

plt.subplot(211)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend above this subplot, expanding itself to
# fully use the given bounding box.
plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
           ncol=2, mode="expand", borderaxespad=0.)

plt.subplot(223)
plt.plot([1,2,3], label="test1")
plt.plot([3,2,1], label="test2")
# Place a legend to the right of this smaller subplot.
plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)

plt.show()

Get program path in VB.NET?

Set Your Own application Path

Dim myPathsValues As String

    TextBox1.Text = Application.StartupPath
    TextBox2.Text = Len(Application.StartupPath)
    TextBox3.Text = Microsoft.VisualBasic.Right(Application.StartupPath, 10)
    myPathsValues = Val(TextBox2.Text) - 9
    TextBox4.Text = Microsoft.VisualBasic.Left(Application.StartupPath, myPathsValues) & "Reports"

C# create simple xml file

I'd recommend serialization,

public class Person
{
      public  string FirstName;
      public  string MI;
      public  string LastName;
}

static void Serialize()
{
      clsPerson p = new Person();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(System.Console.Out, p);
      System.Console.WriteLine();
      System.Console.WriteLine(" --- Press any key to continue --- ");
      System.Console.ReadKey();
}

You can further control serialization with attributes.
But if it is simple, you could use XmlDocument:

using System;
using System.Xml;

public class GenerateXml {
    private static void Main() {
        XmlDocument doc = new XmlDocument();
        XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
        doc.AppendChild(docNode);

        XmlNode productsNode = doc.CreateElement("products");
        doc.AppendChild(productsNode);

        XmlNode productNode = doc.CreateElement("product");
        XmlAttribute productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "01";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);

        XmlNode nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("Java"));
        productNode.AppendChild(nameNode);
        XmlNode priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        // Create and add another product node.
        productNode = doc.CreateElement("product");
        productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "02";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);
        nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("C#"));
        productNode.AppendChild(nameNode);
        priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        doc.Save(Console.Out);
    }
}

And if it needs to be fast, use XmlWriter:

public static void WriteXML()
{
    // Create an XmlWriterSettings object with the correct options.
    System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
    settings.Indent = true;
    settings.IndentChars = "    "; //  "\t";
    settings.OmitXmlDeclaration = false;
    settings.Encoding = System.Text.Encoding.UTF8;

    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("data.xml", settings))
    {

        writer.WriteStartDocument();
        writer.WriteStartElement("books");

        for (int i = 0; i < 100; ++i)
        {
            writer.WriteStartElement("book");
            writer.WriteElementString("item", "Book "+ (i+1).ToString());
            writer.WriteEndElement();
        }

        writer.WriteEndElement();

        writer.Flush();
        writer.Close();
    } // End Using writer 

}

And btw, the fastest way to read XML is XmlReader:

public static void ReadXML()
{
    using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"))
    {
        while (xmlReader.Read())
        {
            if ((xmlReader.NodeType == System.Xml.XmlNodeType.Element) && (xmlReader.Name == "Cube"))
            {
                if (xmlReader.HasAttributes)
                    System.Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));
            }

        } // Whend 

    } // End Using xmlReader

    System.Console.ReadKey();
}

And the most convenient way to read XML is to just deserialize the XML into a class.
This also works for creating the serialization classes, btw.
You can generate the class from XML with Xml2CSharp:
https://xmltocsharp.azurewebsites.net/

Regular Expression to reformat a US phone number in Javascript

Here is one that will accept both phone numbers and phone numbers with extensions.

function phoneNumber(tel) {
var toString = String(tel),
    phoneNumber = toString.replace(/[^0-9]/g, ""),
    countArrayStr = phoneNumber.split(""),
    numberVar = countArrayStr.length,
    closeStr = countArrayStr.join("");
if (numberVar == 10) {
    var phone = closeStr.replace(/(\d{3})(\d{3})(\d{4})/, "$1.$2.$3"); // Change number symbols here for numbers 10 digits in length. Just change the periods to what ever is needed.
} else if (numberVar > 10) {
    var howMany = closeStr.length,
        subtract = (10 - howMany),
        phoneBeginning = closeStr.slice(0, subtract),
        phoneExtention = closeStr.slice(subtract),
        disX = "x", // Change the extension symbol here
        phoneBeginningReplace = phoneBeginning.replace(/(\d{3})(\d{3})(\d{4})/, "$1.$2.$3"), // Change number symbols here for numbers greater than 10 digits in length. Just change the periods and to what ever is needed. 
        array = [phoneBeginningReplace, disX, phoneExtention],
        afterarray = array.splice(1, 0, " "),
        phone = array.join("");

} else {
    var phone = "invalid number US number";
}
return phone;
}

phoneNumber("1234567891"); // Your phone number here

How can I calculate the time between 2 Dates in typescript

In order to calculate the difference you have to put the + operator,

that way typescript converts the dates to numbers.

+new Date()- +new Date("2013-02-20T12:01:04.753Z")

From there you can make a formula to convert the difference to minutes or hours.

What is the correct target for the JAVA_HOME environment variable for a Linux OpenJDK Debian-based distribution?

What finally worked for me (Grails now works smoothly) is doing almost like Steve B. has pointed out:

JAVA_HOME=/usr/lib/jvm/default-java

This way if the user changes the default JDK for the system, JAVA_HOME still works.

default-java is a symlink to the current JVM.

Update multiple rows using select statement

You can use alias to improve the query:

UPDATE t1
   SET t1.Value = t2.Value
  FROM table1 AS t1
         INNER JOIN 
       table2 AS t2
         ON t1.ID = t2.ID

How to call stopservice() method of Service class from the calling activity class

@Juri

If you add IntentFilters for your service, you are saying you want to expose your service to other applications, then it may be stopped unexpectedly by other applications.

Replace deprecated preg_replace /e with preg_replace_callback

You can use an anonymous function to pass the matches to your function:

$result = preg_replace_callback(
    "/\{([<>])([a-zA-Z0-9_]*)(\?{0,1})([a-zA-Z0-9_]*)\}(.*)\{\\1\/\\2\}/isU",
    function($m) { return CallFunction($m[1], $m[2], $m[3], $m[4], $m[5]); },
    $result
);

Apart from being faster, this will also properly handle double quotes in your string. Your current code using /e would convert a double quote " into \".

Git:nothing added to commit but untracked files present

In case someone cares just about the error nothing added to commit but untracked files present (use "git add" to track) and not about Please move or remove them before you can merge.. You might have a look at the answers on Git - Won't add files?

There you find at least 2 good candidates for the issue in question here: that you either are in a subfolder or in a parent folder, but not in the actual repo folder. If you are in the directory one level too high, this will definitely raise that message "nothing added to commit…", see my answer in the link for details. I do not know if the same message occurs when you are in a subfolder, but it is likely. That could fit to your explanations.

How to Use Content-disposition for force a file to download to the hard drive?

With recent browsers you can use the HTML5 download attribute as well:

<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>

It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):

(function (){

    addEvent(window, "load", function (){
        if (isInternetExplorer())
            polyfillDataUriDownload();
    });

    function polyfillDataUriDownload(){
        var links = document.querySelectorAll('a[download], area[download]');
        for (var index = 0, length = links.length; index<length; ++index) {
            (function (link){
                var dataUri = link.getAttribute("href");
                var fileName = link.getAttribute("download");
                if (dataUri.slice(0,5) != "data:")
                    throw new Error("The XHR part is not implemented here.");
                addEvent(link, "click", function (event){
                    cancelEvent(event);
                    try {
                        var dataBlob = dataUriToBlob(dataUri);
                        forceBlobDownload(dataBlob, fileName);
                    } catch (e) {
                        alert(e)
                    }
                });
            })(links[index]);
        }
    }

    function forceBlobDownload(dataBlob, fileName){
        window.navigator.msSaveBlob(dataBlob, fileName);
    }

    function dataUriToBlob(dataUri) {
        if  (!(/base64/).test(dataUri))
            throw new Error("Supports only base64 encoding.");
        var parts = dataUri.split(/[:;,]/),
            type = parts[1],
            binData = atob(parts.pop()),
            mx = binData.length,
            uiArr = new Uint8Array(mx);
        for(var i = 0; i<mx; ++i)
            uiArr[i] = binData.charCodeAt(i);
        return new Blob([uiArr], {type: type});
    }

    function addEvent(subject, type, listener){
        if (window.addEventListener)
            subject.addEventListener(type, listener, false);
        else if (window.attachEvent)
            subject.attachEvent("on" + type, listener);
    }

    function cancelEvent(event){
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;
    }

    function isInternetExplorer(){
        return /*@cc_on!@*/false || !!document.documentMode;
    }
    
})();

PHP - If variable is not empty, echo some html code

if(!empty($web))
{
   echo 'Something';
}

List all files from a directory recursively with Java

In Java 8, it's a 1-liner via Files.find() with an arbitrarily large depth (eg 999) and BasicFileAttributes of isRegularFile()

public static printFnames(String sDir) {
    Files.find(Paths.get(sDir), 999, (p, bfa) -> bfa.isRegularFile()).forEach(System.out::println);
}

To add more filtering, enhance the lambda, for example all jpg files modified in the last 24 hours:

(p, bfa) -> bfa.isRegularFile()
  && p.getFileName().toString().matches(".*\\.jpg")
  && bfa.lastModifiedTime().toMillis() > System.currentMillis() - 86400000

Removing spaces from a variable input using PowerShell 4.0

You're close. You can strip the whitespace by using the replace method like this:

$answer.replace(' ','')

There needs to be no space or characters between the second set of quotes in the replace method (replacing the whitespace with nothing).

Wavy shape with css

I like ThomasA's answer, but wanted a more realistic context with the wave being used to separate two divs. So I created a more complete demo where the separator SVG gets positioned perfectly between the two divs.

css wavy divider in CSS

Now I thought it would be cool to take it further. What if we could do this all in CSS without the need for the inline SVG? The point being to avoid extra markup. Here's how I did it:

Two simple <div>:

_x000D_
_x000D_
/** CSS using pseudo-elements: **/_x000D_
_x000D_
#A {_x000D_
  background: #0074D9;_x000D_
}_x000D_
_x000D_
#B {_x000D_
  background: #7FDBFF;_x000D_
}_x000D_
_x000D_
#A::after {_x000D_
  content: "";_x000D_
  position: relative;_x000D_
  left: -3rem;_x000D_
  /* padding * -1 */_x000D_
  top: calc( 3rem - 4rem / 2);_x000D_
  /* padding - height/2 */_x000D_
  float: left;_x000D_
  display: block;_x000D_
  height: 4rem;_x000D_
  width: 100vw;_x000D_
  background: hsla(0, 0%, 100%, 0.5);_x000D_
  background-image: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 70 500 60' preserveAspectRatio='none'%3E%3Crect x='0' y='0' width='500' height='500' style='stroke: none; fill: %237FDBFF;' /%3E%3Cpath d='M0,100 C150,200 350,0 500,100 L500,00 L0,0 Z' style='stroke: none; fill: %230074D9;'%3E%3C/path%3E%3C/svg%3E");_x000D_
  background-size: 100% 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/** Cosmetics **/_x000D_
_x000D_
* {_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#A,_x000D_
#B {_x000D_
  padding: 3rem;_x000D_
}_x000D_
_x000D_
div {_x000D_
  font-family: monospace;_x000D_
  font-size: 1.2rem;_x000D_
  line-height: 1.2;_x000D_
}_x000D_
_x000D_
#A {_x000D_
  color: white;_x000D_
}
_x000D_
<div id="A">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus nec quam tincidunt, iaculis mi non, hendrerit felis. Nulla pretium lectus et arcu tempus, quis luctus ex imperdiet. In facilisis nulla suscipit ornare finibus. …_x000D_
</div>_x000D_
_x000D_
<div id="B" class="wavy">… In iaculis fermentum lacus vel porttitor. Vestibulum congue elementum neque eget feugiat. Donec suscipit diam ligula, aliquam consequat tellus sagittis porttitor. Sed sodales leo nisl, ut consequat est ornare eleifend. Cras et semper mi, in porta nunc.</div>
_x000D_
_x000D_
_x000D_

Demo Wavy divider (with CSS pseudo-elements to avoid extra markup)

It was a bit trickier to position than with an inline SVG but works just as well. (Could use CSS custom properties or pre-processor variables to keep the height and padding easy to read.)

To edit the colors, you need to edit the URL-encoded SVG itself.

Pay attention (like in the first demo) to a change in the viewBox to get rid of unwanted spaces in the SVG. (Another option would be to draw a different SVG.)

Another thing to pay attention to here is the background-size set to 100% 100% to get it to stretch in both directions.

Why, Fatal error: Class 'PHPUnit_Framework_TestCase' not found in ...?

It may well be that you're running WordPress core tests, and have recently upgraded your PhpUnit to version 6. If that's the case, then the recent change to namespacing in PhpUnit will have broken your code.

Fortunately, there's a patch to the core tests at https://core.trac.wordpress.org/changeset/40547 which will work around the problem. It also includes changes to travis.yml, which you may not have in your setup; if that's the case then you'll need to edit the .diff file to ignore the Travis patch.

  1. Download the "Unified Diff" patch from the bottom of https://core.trac.wordpress.org/changeset/40547
  2. Edit the patch file to remove the Travis part of the patch if you don't need that. Delete from the top of the file to just above this line:

    Index: /branches/4.7/tests/phpunit/includes/bootstrap.php
    
  3. Save the diff in the directory above your /includes/ directory - in my case this was the Wordpress directory itself

  4. Use the Unix patch tool to patch the files. You'll also need to strip the first few slashes to move from an absolute to a relative directory structure. As you can see from point 3 above, there are five slashes before the include directory, which a -p5 flag will get rid of for you.

    $ cd [WORDPRESS DIRECTORY]
    $ patch -p5 < changeset_40547.diff 
    

After I did this my tests ran correctly again.

Iframe positioning

you should use position: relative; for one iframe and position:absolute; for the second;

Example: for first iframe use:

<div id="contentframe" style="position:relative; top: 100px; left: 50px;">

for second iframe use:

<div id="contentframe" style="position:absolute; top: 0px; left: 690px;">

How do I find out which process is locking a file using .NET?

Long ago it was impossible to reliably get the list of processes locking a file because Windows simply did not track that information. To support the Restart Manager API, that information is now tracked.

I put together code that takes the path of a file and returns a List<Process> of all processes that are locking that file.

using System.Runtime.InteropServices;
using System.Diagnostics;
using System;
using System.Collections.Generic;

static public class FileUtil
{
    [StructLayout(LayoutKind.Sequential)]
    struct RM_UNIQUE_PROCESS
    {
        public int dwProcessId;
        public System.Runtime.InteropServices.ComTypes.FILETIME ProcessStartTime;
    }

    const int RmRebootReasonNone = 0;
    const int CCH_RM_MAX_APP_NAME = 255;
    const int CCH_RM_MAX_SVC_NAME = 63;

    enum RM_APP_TYPE
    {
        RmUnknownApp = 0,
        RmMainWindow = 1,
        RmOtherWindow = 2,
        RmService = 3,
        RmExplorer = 4,
        RmConsole = 5,
        RmCritical = 1000
    }

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
    struct RM_PROCESS_INFO
    {
        public RM_UNIQUE_PROCESS Process;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_APP_NAME + 1)]
        public string strAppName;

        [MarshalAs(UnmanagedType.ByValTStr, SizeConst = CCH_RM_MAX_SVC_NAME + 1)]
        public string strServiceShortName;

        public RM_APP_TYPE ApplicationType;
        public uint AppStatus;
        public uint TSSessionId;
        [MarshalAs(UnmanagedType.Bool)]
        public bool bRestartable;
    }

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Unicode)]
    static extern int RmRegisterResources(uint pSessionHandle,
                                          UInt32 nFiles,
                                          string[] rgsFilenames,
                                          UInt32 nApplications,
                                          [In] RM_UNIQUE_PROCESS[] rgApplications,
                                          UInt32 nServices,
                                          string[] rgsServiceNames);

    [DllImport("rstrtmgr.dll", CharSet = CharSet.Auto)]
    static extern int RmStartSession(out uint pSessionHandle, int dwSessionFlags, string strSessionKey);

    [DllImport("rstrtmgr.dll")]
    static extern int RmEndSession(uint pSessionHandle);

    [DllImport("rstrtmgr.dll")]
    static extern int RmGetList(uint dwSessionHandle,
                                out uint pnProcInfoNeeded,
                                ref uint pnProcInfo,
                                [In, Out] RM_PROCESS_INFO[] rgAffectedApps,
                                ref uint lpdwRebootReasons);

    /// <summary>
    /// Find out what process(es) have a lock on the specified file.
    /// </summary>
    /// <param name="path">Path of the file.</param>
    /// <returns>Processes locking the file</returns>
    /// <remarks>See also:
    /// http://msdn.microsoft.com/en-us/library/windows/desktop/aa373661(v=vs.85).aspx
    /// http://wyupdate.googlecode.com/svn-history/r401/trunk/frmFilesInUse.cs (no copyright in code at time of viewing)
    /// 
    /// </remarks>
    static public List<Process> WhoIsLocking(string path)
    {
        uint handle;
        string key = Guid.NewGuid().ToString();
        List<Process> processes = new List<Process>();

        int res = RmStartSession(out handle, 0, key);
        if (res != 0) throw new Exception("Could not begin restart session.  Unable to determine file locker.");

        try
        {
            const int ERROR_MORE_DATA = 234;
            uint pnProcInfoNeeded = 0,
                 pnProcInfo = 0,
                 lpdwRebootReasons = RmRebootReasonNone;

            string[] resources = new string[] { path }; // Just checking on one resource.

            res = RmRegisterResources(handle, (uint)resources.Length, resources, 0, null, 0, null);

            if (res != 0) throw new Exception("Could not register resource.");                                    

            //Note: there's a race condition here -- the first call to RmGetList() returns
            //      the total number of process. However, when we call RmGetList() again to get
            //      the actual processes this number may have increased.
            res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, null, ref lpdwRebootReasons);

            if (res == ERROR_MORE_DATA)
            {
                // Create an array to store the process results
                RM_PROCESS_INFO[] processInfo = new RM_PROCESS_INFO[pnProcInfoNeeded];
                pnProcInfo = pnProcInfoNeeded;

                // Get the list
                res = RmGetList(handle, out pnProcInfoNeeded, ref pnProcInfo, processInfo, ref lpdwRebootReasons);
                if (res == 0)
                {
                    processes = new List<Process>((int)pnProcInfo);

                    // Enumerate all of the results and add them to the 
                    // list to be returned
                    for (int i = 0; i < pnProcInfo; i++)
                    {
                        try
                        {
                            processes.Add(Process.GetProcessById(processInfo[i].Process.dwProcessId));
                        }
                        // catch the error -- in case the process is no longer running
                        catch (ArgumentException) { }
                    }
                }
                else throw new Exception("Could not list processes locking resource.");                    
            }
            else if (res != 0) throw new Exception("Could not list processes locking resource. Failed to get size of result.");                    
        }
        finally
        {
            RmEndSession(handle);
        }

        return processes;
    }
}

Using from Limited Permission (e.g. IIS)

This call accesses the registry. If the process does not have permission to do so, you will get ERROR_WRITE_FAULT, meaning An operation was unable to read or write to the registry. You could selectively grant permission to your restricted account to the necessary part of the registry. It is more secure though to have your limited access process set a flag (e.g. in the database or the file system, or by using an interprocess communication mechanism such as queue or named pipe) and have a second process call the Restart Manager API.

Granting other-than-minimal permissions to the IIS user is a security risk.

Detect merged cells in VBA Excel with MergeArea

There are several helpful bits of code for this.

Place your cursor in a merged cell and ask these questions in the Immidiate Window:

Is the activecell a merged cell?

? Activecell.Mergecells
 True

How many cells are merged?

? Activecell.MergeArea.Cells.Count
 2

How many columns are merged?

? Activecell.MergeArea.Columns.Count
 2

How many rows are merged?

? Activecell.MergeArea.Rows.Count
  1

What's the merged range address?

? activecell.MergeArea.Address
  $F$2:$F$3

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

Firebase (FCM) how to get token

In firebase-messaging:17.1.0 and newer the FirebaseInstanceIdService is deprecated, you can get the onNewToken on the FirebaseMessagingService class as explained on https://stackoverflow.com/a/51475096/1351469

But if you want to just get the token any time, then now you can do it like this:

FirebaseInstanceId.getInstance().getInstanceId().addOnSuccessListener( this.getActivity(),  new OnSuccessListener<InstanceIdResult>() {
  @Override
  public void onSuccess(InstanceIdResult instanceIdResult) {
    String newToken = instanceIdResult.getToken();
    Log.e("newToken",newToken);
  }
});

ASP.NET MVC View Engine Comparison

I like ndjango. It is very easy to use and very flexible. You can easily extend view functionality with custom tags and filters. I think that "greatly tied to F#" is rather advantage than disadvantage.

How to replace values at specific indexes of a python list?

You can solve it using dictionary

to_modify = [5,4,3,2,1,0]
indexes = [0,1,3,5]
replacements = [0,0,0,0]

dic = {}
for i in range(len(indexes)):
    dic[indexes[i]]=replacements[i]
print(dic)

for index, item in enumerate(to_modify):
    for i in indexes:
        to_modify[i]=dic[i]
print(to_modify)

The output will be

{0: 0, 1: 0, 3: 0, 5: 0}
[0, 0, 3, 0, 1, 0]

fatal error C1010 - "stdafx.h" in Visual Studio how can this be corrected?

Look at https://stackoverflow.com/a/4726838/2963099

Turn off pre compiled headers:

Project Properties -> C++ -> Precompiled Headers

set Precompiled Header to "Not Using Precompiled Header".

ssh-copy-id no identities found error

Use simple ssh-keyscan hostname to find if key(s) exists on both sites:

ssh-keyscan rc1.localdomain
[or@rc2 ~]$ ssh-keyscan rc1
# rc1 SSH-2.0-OpenSSH_5.3
rc1 ssh-rsa AAAAB3NzaC1yc2EAAAABI.......==

ssh-keyscan rc2.localdomain
[or@rc2 ~]$ ssh-keyscan rc2
# rac2 SSH-2.0-OpenSSH_5.3
rac2 ssh-rsa AAAAB3NzaC1yc2EAAAABIwAAAQEAys7kG6pNiC.......==

ActiveXObject creation error " Automation server can't create object"

This error is cause by security clutches between the web application and your java. To resolve it, look into your java setting under control panel. Move the security level to a medium.

Facebook Android Generate Key Hash

Hi everyone its my story how i get signed has key for facebook

first of all you just have copy this 2 methods in your first class

    private void getAppKeyHash() {
    try {
        PackageInfo info = getPackageManager().getPackageInfo(
                getPackageName(), PackageManager.GET_SIGNATURES);
        for (Signature signature : info.signatures) {
            MessageDigest md;

            md = MessageDigest.getInstance("SHA");
            md.update(signature.toByteArray());
            String something = new String(Base64.encode(md.digest(), 0));
            System.out.println("HASH  " + something);
            showSignedHashKey(something);

        }
    } catch (NameNotFoundException e1) {
        // TODO Auto-generated catch block
        Log.e("name not found", e1.toString());
    } catch (NoSuchAlgorithmException e) {

        Log.e("no such an algorithm", e.toString());
    } catch (Exception e) {
        Log.e("exception", e.toString());
    }
}
public void showSignedHashKey(String hashKey) {

    AlertDialog.Builder adb = new AlertDialog.Builder(this);
    adb.setTitle("Note Signed Hash Key");
    adb.setMessage(hashKey);
    adb.setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {

        }
    });

    adb.show();
}

**Call funcation getAppKeyHash() from your oncreate methode if you want signed hash then make signed build install signed build and run you will get hash key in dialog then just note it and update it on facebook dev account and comment that function and make another signed APK **

Spring can you autowire inside an abstract class?

In my case, inside a Spring4 Application, i had to use a classic Abstract Factory Pattern(for which i took the idea from - http://java-design-patterns.com/patterns/abstract-factory/) to create instances each and every time there was a operation to be done.So my code was to be designed like:

public abstract class EO {
    @Autowired
    protected SmsNotificationService smsNotificationService;
    @Autowired
    protected SendEmailService sendEmailService;
    ...
    protected abstract void executeOperation(GenericMessage gMessage);
}

public final class OperationsExecutor {
    public enum OperationsType {
        ENROLL, CAMPAIGN
    }

    private OperationsExecutor() {
    }

    public static Object delegateOperation(OperationsType type, Object obj) 
    {
        switch(type) {
            case ENROLL:
                if (obj == null) {
                    return new EnrollOperation();
                }
                return EnrollOperation.validateRequestParams(obj);
            case CAMPAIGN:
                if (obj == null) {
                    return new CampaignOperation();
                }
                return CampaignOperation.validateRequestParams(obj);
            default:
                throw new IllegalArgumentException("OperationsType not supported.");
        }
    }
}

@Configurable(dependencyCheck = true)
public class CampaignOperation extends EO {
    @Override
    public void executeOperation(GenericMessage genericMessage) {
        LOGGER.info("This is CAMPAIGN Operation: " + genericMessage);
    }
}

Initially to inject the dependencies in the abstract class I tried all stereotype annotations like @Component, @Service etc but even though Spring context file had ComponentScanning for the entire package, but somehow while creating instances of Subclasses like CampaignOperation, the Super Abstract class EO was having null for its properties as spring was unable to recognize and inject its dependencies.After much trial and error I used this **@Configurable(dependencyCheck = true)** annotation and finally Spring was able to inject the dependencies and I was able to use the properties in the subclass without cluttering them with too many properties.

<context:annotation-config />
<context:component-scan base-package="com.xyz" />

I also tried these other references to find a solution:

  1. http://www.captaindebug.com/2011/06/implementing-springs-factorybean.html#.WqF5pJPwaAN
  2. http://forum.spring.io/forum/spring-projects/container/46815-problem-with-autowired-in-abstract-class
  3. https://github.com/cavallefano/Abstract-Factory-Pattern-Spring-Annotation
  4. http://www.jcombat.com/spring/factory-implementation-using-servicelocatorfactorybean-in-spring
  5. https://www.madbit.org/blog/programming/1074/1074/#sthash.XEJXdIR5.dpbs
  6. Using abstract factory with Spring framework
  7. Spring Autowiring not working for Abstract classes
  8. Inject spring dependency in abstract super class
  9. Spring and Abstract class - injecting properties in abstract classes
    1. Spring autowire dependency defined in an abstract class

Please try using **@Configurable(dependencyCheck = true)** and update this post, I might try helping you if you face any problems.

AngularJs: Reload page

This can be done by calling the reload() method of the window object in plain JavaScript

window.location.reload();

Efficient SQL test query or validation query that will work across all (or most) databases

After a little bit of research along with help from some of the answers here:

SELECT 1

  • H2
  • MySQL
  • Microsoft SQL Server (according to NimChimpsky)
  • PostgreSQL
  • SQLite

SELECT 1 FROM DUAL

  • Oracle

SELECT 1 FROM any_existing_table WHERE 1=0

or

SELECT 1 FROM INFORMATION_SCHEMA.SYSTEM_USERS

or

CALL NOW()

  • HSQLDB (tested with version 1.8.0.10)

    Note: I tried using a WHERE 1=0 clause on the second query, but it didn't work as a value for Apache Commons DBCP's validationQuery, since the query doesn't return any rows


VALUES 1 or SELECT 1 FROM SYSIBM.SYSDUMMY1

SELECT 1 FROM SYSIBM.SYSDUMMY1

  • DB2

select count(*) from systables

  • Informix

Tomcat in Intellij Idea Community Edition

Tomcat can also be integrated with IntelliJ Idea - Community Edition with Tomcat Runner Plugin.

Details below: https://plugins.jetbrains.com/plugin/8266-tomcat-runner-plugin-for-intellij

How to disable HTML button using JavaScript?

The official way to set the disabled attribute on an HTMLInputElement is this:

var input = document.querySelector('[name="myButton"]');
// Without querySelector API
// var input = document.getElementsByName('myButton').item(0);

// disable
input.setAttribute('disabled', true);
// enable
input.removeAttribute('disabled');

While @kaushar's answer is sufficient for enabling and disabling an HTMLInputElement, and is probably preferable for cross-browser compatibility due to IE's historically buggy setAttribute, it only works because Element properties shadow Element attributes. If a property is set, then the DOM uses the value of the property by default rather than the value of the equivalent attribute.

There is a very important difference between properties and attributes. An example of a true HTMLInputElement property is input.value, and below demonstrates how shadowing works:

_x000D_
_x000D_
var input = document.querySelector('#test');_x000D_
_x000D_
// the attribute works as expected_x000D_
console.log('old attribute:', input.getAttribute('value'));_x000D_
// the property is equal to the attribute when the property is not explicitly set_x000D_
console.log('old property:', input.value);_x000D_
_x000D_
// change the input's value property_x000D_
input.value = "My New Value";_x000D_
_x000D_
// the attribute remains there because it still exists in the DOM markup_x000D_
console.log('new attribute:', input.getAttribute('value'));_x000D_
// but the property is equal to the set value due to the shadowing effect_x000D_
console.log('new property:', input.value);
_x000D_
<input id="test" type="text" value="Hello World" />
_x000D_
_x000D_
_x000D_

That is what it means to say that properties shadow attributes. This concept also applies to inherited properties on the prototype chain:

_x000D_
_x000D_
function Parent() {_x000D_
  this.property = 'ParentInstance';_x000D_
}_x000D_
_x000D_
Parent.prototype.property = 'ParentPrototype';_x000D_
_x000D_
// ES5 inheritance_x000D_
Child.prototype = Object.create(Parent.prototype);_x000D_
Child.prototype.constructor = Child;_x000D_
_x000D_
function Child() {_x000D_
  // ES5 super()_x000D_
  Parent.call(this);_x000D_
_x000D_
  this.property = 'ChildInstance';_x000D_
}_x000D_
_x000D_
Child.prototype.property = 'ChildPrototype';_x000D_
_x000D_
logChain('new Parent()');_x000D_
_x000D_
log('-------------------------------');_x000D_
logChain('Object.create(Parent.prototype)');_x000D_
_x000D_
log('-----------');_x000D_
logChain('new Child()');_x000D_
_x000D_
log('------------------------------');_x000D_
logChain('Object.create(Child.prototype)');_x000D_
_x000D_
// below is for demonstration purposes_x000D_
// don't ever actually use document.write(), eval(), or access __proto___x000D_
function log(value) {_x000D_
  document.write(`<pre>${value}</pre>`);_x000D_
}_x000D_
_x000D_
function logChain(code) {_x000D_
  log(code);_x000D_
_x000D_
  var object = eval(code);_x000D_
_x000D_
  do {_x000D_
    log(`${object.constructor.name} ${object instanceof object.constructor ? 'instance' : 'prototype'} property: ${JSON.stringify(object.property)}`);_x000D_
    _x000D_
    object = object.__proto__;_x000D_
  } while (object !== null);_x000D_
}
_x000D_
_x000D_
_x000D_

I hope this clarifies any confusion about the difference between properties and attributes.

Configuring Log4j Loggers Programmatically

You can add/remove Appender programmatically to Log4j:

  ConsoleAppender console = new ConsoleAppender(); //create appender
  //configure the appender
  String PATTERN = "%d [%p|%c|%C{1}] %m%n";
  console.setLayout(new PatternLayout(PATTERN)); 
  console.setThreshold(Level.FATAL);
  console.activateOptions();
  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(console);

  FileAppender fa = new FileAppender();
  fa.setName("FileLogger");
  fa.setFile("mylog.log");
  fa.setLayout(new PatternLayout("%d %-5p [%c{1}] %m%n"));
  fa.setThreshold(Level.DEBUG);
  fa.setAppend(true);
  fa.activateOptions();

  //add appender to any Logger (here is root)
  Logger.getRootLogger().addAppender(fa);
  //repeat with all other desired appenders

I'd suggest you put it into an init() somewhere, where you are sure, that this will be executed before anything else. You can then remove all existing appenders on the root logger with

 Logger.getRootLogger().getLoggerRepository().resetConfiguration();

and start with adding your own. You need log4j in the classpath of course for this to work.

Remark:
You can take any Logger.getLogger(...) you like to add appenders. I just took the root logger because it is at the bottom of all things and will handle everything that is passed through other appenders in other categories (unless configured otherwise by setting the additivity flag).

If you need to know how logging works and how is decided where logs are written read this manual for more infos about that.
In Short:

  Logger fizz = LoggerFactory.getLogger("com.fizz")

will give you a logger for the category "com.fizz".
For the above example this means that everything logged with it will be referred to the console and file appender on the root logger.
If you add an appender to Logger.getLogger("com.fizz").addAppender(newAppender) then logging from fizz will be handled by alle the appenders from the root logger and the newAppender.
You don't create Loggers with the configuration, you just provide handlers for all possible categories in your system.

How do I replace NA values with zeros in an R dataframe?

Another dplyr pipe compatible option with tidyrmethod replace_na that works for several columns:

require(dplyr)
require(tidyr)

m <- matrix(sample(c(NA, 1:10), 100, replace = TRUE), 10)
d <- as.data.frame(m)

myList <- setNames(lapply(vector("list", ncol(d)), function(x) x <- 0), names(d))

df <- d %>% replace_na(myList)

You can easily restrict to e.g. numeric columns:

d$str <- c("string", NA)

myList <- myList[sapply(d, is.numeric)]

df <- d %>% replace_na(myList)

How to calculate the IP range when the IP address and the netmask is given?

I learned this shortcut from working at the network deployment position. It helped me so much, I figured I will share this secret with everyone. So far, I have not able to find an easier way online that I know of.

For example a network 192.115.103.64 /27, what is the range?

just remember that subnet mask is 0, 128, 192, 224, 240, 248, 252, 254, 255

255.255.255.255 11111111.11111111.11111111.11111111 /32

255.255.255.254 11111111.11111111.11111111.11111110 /31

255.255.255.252 11111111.11111111.11111111.11111100 /30

255.255.255.248 11111111.11111111.11111111.11111000 /29

255.255.255.240 11111111.11111111.11111111.11110000 /28

255.255.255.224 11111111.11111111.11111111.11100000 /27

255.255.255.192 11111111.11111111.11111111.11000000 /26

255.255.255.128 11111111.11111111.11111111.10000000 /25

255.255.255.0 11111111.11111111.11111111.00000000 /24

from /27 we know that (11111111.11111111.11111111.11100000). Counting from the left, it is the third number from the last octet, which equal 255.255.255.224 subnet mask. (Don't count 0, 0 is /24) so 128, 192, 224..etc

Here where the math comes in:

use the subnet mask - subnet mask of the previous listed subnet mask in this case 224-192=32

We know 192.115.103.64 is the network: 64 + 32 = 96 (the next network for /27)

which means we have .0 .32. 64. 96. 128. 160. 192. 224. (Can't use 256 because it is .255)

Here is the range 64 -- 96.

network is 64.

first host is 65.(first network +1)

Last host is 94. (broadcast -1)

broadcast is 95. (last network -1)

Node.js: How to send headers with form data using request module?

This should work.

var url = 'http://<your_url_here>';
var headers = { 
    'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0',
    'Content-Type' : 'application/x-www-form-urlencoded' 
};
var form = { username: 'user', password: '', opaque: 'someValue', logintype: '1'};

request.post({ url: url, form: form, headers: headers }, function (e, r, body) {
    // your callback body
});

How do I tell if a regular file does not exist in Bash?

[[ -f $FILE ]] || printf '%s does not exist!\n' "$FILE"

Also, it's possible that the file is a broken symbolic link, or a non-regular file, like e.g. a socket, device or fifo. For example, to add a check for broken symlinks:

if [[ ! -f $FILE ]]; then
    if [[ -L $FILE ]]; then
        printf '%s is a broken symlink!\n' "$FILE"
    else
        printf '%s does not exist!\n' "$FILE"
    fi
fi

What is the max size of localStorage values?

You don't want to stringify large objects into a single localStorage entry. That would be very inefficient - the whole thing would have to be parsed and re-encoded every time some slight detail changes. Also, JSON can't handle multiple cross references within an object structure and wipes out a lot of details, e.g. the constructor, non-numerical properties of arrays, what's in a sparse entry, etc.

Instead, you can use Rhaboo. It stores large objects using lots of localStorage entries so you can make small changes quickly. The restored objects are much more accurate copies of the saved ones and the API is incredibly simple. E.g.:

var store = Rhaboo.persistent('Some name');
store.write('count', store.count ? store.count+1 : 1);
store.write('somethingfancy', {
  one: ['man', 'went'],
  2: 'mow',
  went: [  2, { mow: ['a', 'meadow' ] }, {}  ]
});
store.somethingfancy.went[1].mow.write(1, 'lawn');

BTW, I wrote it.

Converting an int or String to a char array on Arduino

Just as a reference, here is an example of how to convert between String and char[] with a dynamic length -

// Define 
String str = "This is my string"; 

// Length (with one extra character for the null terminator)
int str_len = str.length() + 1; 

// Prepare the character array (the buffer) 
char char_array[str_len];

// Copy it over 
str.toCharArray(char_array, str_len);

Yes, this is painfully obtuse for something as simple as a type conversion, but sadly it's the easiest way.

How can I match on an attribute that contains a certain string?

mjv's answer is a good start but will fail if atag is not the first classname listed.

The usual approach is the rather unwieldy:

//*[contains(concat(' ', @class, ' '), ' atag ')]

this works as long as classes are separated by spaces only, and not other forms of whitespace. This is almost always the case. If it might not be, you have to make it more unwieldy still:

//*[contains(concat(' ', normalize-space(@class), ' '), ' atag ')]

(Selecting by classname-like space-separated strings is such a common case it's surprising there isn't a specific XPath function for it, like CSS3's '[class~="atag"]'.)

PreparedStatement with Statement.RETURN_GENERATED_KEYS

String query = "INSERT INTO ....";
PreparedStatement preparedStatement = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);

preparedStatement.setXXX(1, VALUE); 
preparedStatement.setXXX(2, VALUE); 
....
preparedStatement.executeUpdate();  

ResultSet rs = preparedStatement.getGeneratedKeys();  
int key = rs.next() ? rs.getInt(1) : 0;

if(key!=0){
    System.out.println("Generated key="+key);
}

how to log in to mysql and query the database from linux terminal

I assume you are looking to use mysql client, which is a good thing and much more efficient to use than any phpMyAdmin alternatives.

The proper way to log in with the commandline client is by typing:

mysql -u username -p

Notice I did not type the password. Doing so would of made the password visible on screen, that is not good in multi-user environnment!

After typing this hit enter key, mysql will ask you for your password.

Once logged in, of course you will need:

use databaseName;

to do anything.

Good-luck.

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()

Here is the result. enter image description here

How to press back button in android programmatically?

Sometimes is useful to override method onBackPressed() because in case you work with fragments and you're changing between them if you push backbutton they return to the previous fragment.

Python equivalent of a given wget command

I had to do something like this on a version of linux that didn't have the right options compiled into wget. This example is for downloading the memory analysis tool 'guppy'. I'm not sure if it's important or not, but I kept the target file's name the same as the url target name...

Here's what I came up with:

python -c "import requests; r = requests.get('https://pypi.python.org/packages/source/g/guppy/guppy-0.1.10.tar.gz') ; open('guppy-0.1.10.tar.gz' , 'wb').write(r.content)"

That's the one-liner, here's it a little more readable:

import requests
fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname
r = requests.get(url)
open(fname , 'wb').write(r.content)

This worked for downloading a tarball. I was able to extract the package and download it after downloading.

EDIT:

To address a question, here is an implementation with a progress bar printed to STDOUT. There is probably a more portable way to do this without the clint package, but this was tested on my machine and works fine:

#!/usr/bin/env python

from clint.textui import progress
import requests

fname = 'guppy-0.1.10.tar.gz'
url = 'https://pypi.python.org/packages/source/g/guppy/' + fname

r = requests.get(url, stream=True)
with open(fname, 'wb') as f:
    total_length = int(r.headers.get('content-length'))
    for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1): 
        if chunk:
            f.write(chunk)
            f.flush()

How to remove leading zeros using C#

Regex rx = new Regex(@"^0+(\d+)$");
rx.Replace("0001234", @"$1"); // => "1234"
rx.Replace("0001234000", @"$1"); // => "1234000"
rx.Replace("000", @"$1"); // => "0" (TrimStart will convert this to "")

// usage
var outString = rx.Replace(inputString, @"$1");

R command for setting working directory to source file location in Rstudio

Most GUIs assume that if you are in a directory and "open", double-click, or otherwise attempt to execute an .R file, that the directory in which it resides will be the working directory unless otherwise specified. The Mac GUI provides a method to change that default behavior which is changeable in the Startup panel of Preferences that you set in a running session and become effective at the next "startup". You should be also looking at:

?Startup

The RStudio documentation says:

"When launched through a file association, RStudio automatically sets the working directory to the directory of the opened file." The default setup is for RStudio to be register as a handler for .R files, although there is also mention of ability to set a default "association" with RStudio for .Rdata and .R extensions. Whether having 'handler' status and 'association' status are the same on Linux, I cannot tell.

http://www.rstudio.com/ide/docs/using/workspaces

Get the filename of a fileupload in a document through JavaScript

Try

var fu1 = document.getElementById("FileUpload1").value;

How to convert string to boolean in typescript Angular 4

Define extension: String+Extension.ts

interface String {
  toBoolean(): boolean
}

String.prototype.toBoolean = function (): boolean {
  switch (this) {
    case 'true':
    case '1':
    case 'on':
    case 'yes':
      return true
    default:
      return false
  }
}

And import in any file where you want to use it '@/path/to/String+Extension'

default web page width - 1024px or 980px?

980 is not the "defacto standard", you'll generally see most people targeting a size a little bit less than 1024px wide to account for browser chrome such as scrollbars, etc.

Usually people target between 960 and 990px wide. Often people use a grid system (like 960.gs) which is opinionated about what the default width should be.

Also note, just recently the most common screen size now averages quite a bit bigger than 1024px wide, ranking in at 1366px wide. See http://techcrunch.com/2012/04/11/move-over-1024x768-the-most-popular-screen-resolution-on-the-web-is-now-1366x768/

Composer - the requested PHP extension mbstring is missing from your system

For php 7.1

sudo apt-get install php7.1-mbstring

Cheers!

Adding a simple UIAlertView

UIAlertView is deprecated on iOS 8. Therefore, to create an alert on iOS 8 and above, it is recommended to use UIAlertController:

UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Title" message:@"Alert Message" preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *defaultAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){

    // Enter code here
}];
[alert addAction:defaultAction];

// Present action where needed
[self presentViewController:alert animated:YES completion:nil];

This is how I have implemented it.

File uploading with Express 4.0: req.files undefined

Please use below code

app.use(fileUpload());

matplotlib does not show my drawings although I call pyplot.show()

Similar to @Rikki, I solved this problem by upgrading matplotlib with pip install matplotlib --upgrade. If you can't upgrade uninstalling and reinstalling may work.

pip uninstall matplotlib
pip install matplotlib

How to access the value of a promise?

I am a slow learner of javascript promises, by default all async functions return a promise, you can wrap your result as:

(async () => {
//Optional "await"
  await yourAsyncFunctionOrPromise()
    .then(function (result) {
      return result +1;
    })
    .catch(function (error) {
      return error;
    })()
})

"The await expression causes async function execution to pause until a Promise is settled (that is, fulfilled or rejected), and to resume execution of the async function after fulfillment. When resumed, the value of the await expression is that of the fulfilled Promise. If the Promise is rejected, the await expression throws the rejected value."

Read more about await and promises at MDN Web Docs

Android open camera from button

the below code does exactly what you want

//use this intent on click event

Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(cameraIntent,CAMERA_REQUEST);

// the above code is used in 'on activity Result'

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);
    callbackManager.onActivityResult(requestCode, resultCode, data);

    if (requestCode == CAMERA_REQUEST) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        image.setImageBitmap(photo);
    }
}

Get all table names of a particular database by SQL query?

For Mysql you can do simple. SHOW TABLES;

PHP - syntax error, unexpected T_CONSTANT_ENCAPSED_STRING

You have a sintax error in your code:

try changing this line

$out.='<option value=''.$key.'">'.$value["name"].';

with

$out.='<option value="'.$key.'">'.$value["name"].'</option>';

SQL: ... WHERE X IN (SELECT Y FROM ...)

Maybe try this

Select cust.*

From dbo.Customers cust
Left Join dbo.Subscribers subs on cust.Customer_ID = subs.Customer_ID
Where subs.Customer_Id Is Null

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

Get the new record primary key ID from MySQL insert query?

You need to use the LAST_INSERT_ID() function: http://dev.mysql.com/doc/refman/5.0/en/information-functions.html#function_last-insert-id

Eg:

INSERT INTO table_name (col1, col2,...) VALUES ('val1', 'val2'...);
SELECT LAST_INSERT_ID();

This will get you back the PRIMARY KEY value of the last row that you inserted:

The ID that was generated is maintained in the server on a per-connection basis. This means that the value returned by the function to a given client is the first AUTO_INCREMENT value generated for most recent statement affecting an AUTO_INCREMENT column by that client.

So the value returned by LAST_INSERT_ID() is per user and is unaffected by other queries that might be running on the server from other users.

Is there a limit on how much JSON can hold?

Implementations are free to set limits on JSON documents, including the size, so choose your parser wisely. See RFC 7159, Section 9. Parsers:

"An implementation may set limits on the size of texts that it accepts. An implementation may set limits on the maximum depth of nesting. An implementation may set limits on the range and precision of numbers. An implementation may set limits on the length and character contents of strings."

Convert double to Int, rounded down

I think I had a better output, especially for a double datatype sorting.

Though this question has been marked answered, perhaps this will help someone else;

Arrays.sort(newTag, new Comparator<String[]>() {
         @Override
         public int compare(final String[] entry1, final String[] entry2) {
              final Integer time1 = (int)Integer.valueOf((int) Double.parseDouble(entry1[2]));
              final Integer time2 = (int)Integer.valueOf((int) Double.parseDouble(entry2[2]));
              return time1.compareTo(time2);
         }
    });

Stuck at ".android/repositories.cfg could not be loaded."

Creating a dummy blank repositories.cfg works on Windows 7 as well. After waiting for a couple of minutes the installation finishes and you get the message on your cmd window -- done

How to sort the letters in a string alphabetically in Python

You can use reduce

>>> a = 'ZENOVW'
>>> reduce(lambda x,y: x+y, sorted(a))
'ENOVWZ'

Why dict.get(key) instead of dict[key]?

Why dict.get(key) instead of dict[key]?

0. Summary

Comparing to dict[key], dict.get provides a fallback value when looking up for a key.

1. Definition

get(key[, default]) 4. Built-in Types — Python 3.6.4rc1 documentation

Return the value for key if key is in the dictionary, else default. If default is not given, it defaults to None, so that this method never raises a KeyError.

d = {"Name": "Harry", "Age": 17}
In [4]: d['gender']
KeyError: 'gender'
In [5]: d.get('gender', 'Not specified, please add it')
Out[5]: 'Not specified, please add it'

2. Problem it solves.

If without default value, you have to write cumbersome codes to handle such an exception.

def get_harry_info(key):
    try:
        return "{}".format(d[key])
    except KeyError:
        return 'Not specified, please add it'
In [9]: get_harry_info('Name')
Out[9]: 'Harry'
In [10]: get_harry_info('Gender')
Out[10]: 'Not specified, please add it'

As a convenient solution, dict.get introduces an optional default value avoiding above unwiedly codes.

3. Conclusion

dict.get has an additional default value option to deal with exception if key is absent from the dictionary

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

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

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

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

I hit this same problem after implementing IoC for a project (ASP.Net MVC EF6.2).

Usually I would initialise a data context in the constructor of a controller and use the same context to initialise all my repositories.

However using IoC to instantiate the repositories caused them all to have separate contexts and I started getting this error.

For now I've gone back to just newing up the repositories with a common context while I think of a better way.

What's the difference between an Angular component and module

Well, it's too late to post an answer, but I feel my explanation will be easy to understand for beginners with Angular. The following is one of the examples that I give during my presentation.

Consider your angular Application as a building. A building can have N number of apartments in it. An apartment is considered as a module. An Apartment can then have N number of rooms which correspond to the building blocks of an Angular application named components.

Now each apartment (Module)` will have rooms (Components), lifts (Services) to enable larger movement in and out the apartments, wires (Pipes) to transform around and make it useful in the apartments.

You will also have places like swimming pool, tennis court which are being shared by all building residents. So these can be considered as components inside SharedModule.

Basically, the difference is as follows,

Table showing key differences between Module and Component

Follow my slides to understand the building blocks of an Angular application

Here is my session on Building Blocks of Angular for beginners

How to make a smaller RatingBar?

<RatingBar
    android:id="@+id/rating_bar"
    style="@style/Widget.AppCompat.RatingBar.Small"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Getting "file not found" in Bridging Header when importing Objective-C frameworks into Swift project

Well its little strange but I guess you have to add a resource to your "Copy Bundle Resources" phase of your test target to make it load all headers from your main app target. In my case, I added main.storyboard and it took care of the error.

enter image description here

Spring Boot access static resources missing scr/main/resources

You need to use following construction

InputStream in = getClass().getResourceAsStream("/yourFile");

Please note that you have to add this slash before your file name.

How to prevent gcc optimizing some statements in C?

You can use

#pragma GCC push_options
#pragma GCC optimize ("O0")

your code

#pragma GCC pop_options

to disable optimizations since GCC 4.4.

See the GCC documentation if you need more details.

Is the NOLOCK (Sql Server hint) bad practice?

I agree with some comments about NOLOCK hint and especially with those saying "use it when it's appropriate". If the application written poorly and is using concurrency inappropriate way – that may cause the lock escalation. Highly transactional table also are getting locked all the time due to their nature. Having good index coverage won't help with retrieving the data, but setting ISOLATION LEVEL to READ UNCOMMITTED does. Also I believe that using NOLOCK hint is safe in many cases when the nature of changes is predictable. For example – in manufacturing when jobs with travellers are going through different processes with lots of inserts of measurements, you can safely execute query against the finished job with NOLOCK hint and this way avoid collision with other sessions that put PROMOTED or EXCLUSIVE locks on the table/page. The data you access in this case is static, but it may reside in a very transactional table with hundreds of millions of records and thousands updates/inserts per minute. Cheers

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

I had a similar issue and wrapped the component in "div" instead of "p" and the error went away.

How to call a JavaScript function, declared in <head>, in the body when I want to call it

Just drop

<script>
myfunction();
</script>

in the body where you want it to be called, understanding that when the page loads and the browser reaches that point, that's when the call will occur.

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

for Python in Windows:

python -m pip uninstall "package_keyword"
uninstall **** (y/n)?

Writing String to Stream and reading it back does not work

After you write to the MemoryStream and before you read it back, you need to Seek back to the beginning of the MemoryStream so you're not reading from the end.

UPDATE

After seeing your update, I think there's a more reliable way to build the stream:

UnicodeEncoding uniEncoding = new UnicodeEncoding();
String message = "Message";

// You might not want to use the outer using statement that I have
// I wasn't sure how long you would need the MemoryStream object    
using(MemoryStream ms = new MemoryStream())
{
    var sw = new StreamWriter(ms, uniEncoding);
    try
    {
        sw.Write(message);
        sw.Flush();//otherwise you are risking empty stream
        ms.Seek(0, SeekOrigin.Begin);

        // Test and work with the stream here. 
        // If you need to start back at the beginning, be sure to Seek again.
    }
    finally
    {
        sw.Dispose();
    }
}

As you can see, this code uses a StreamWriter to write the entire string (with proper encoding) out to the MemoryStream. This takes the hassle out of ensuring the entire byte array for the string is written.

Update: I stepped into issue with empty stream several time. It's enough to call Flush right after you've finished writing.

When to use an interface instead of an abstract class and vice versa?

Use an abstract class if you want to provide some basic implementations.

How to use underscore.js as a template engine?

Lodash is also the same First write a script as follows:

<script type="text/template" id="genTable">
<table cellspacing='0' cellpadding='0' border='1'>
        <tr>
            <% for(var prop in users[0]){%>
            <th><%= prop %> </th>
            <% }%>
        </tr>
        <%_.forEach(users, function(user) { %>
            <tr>
                 <% for(var prop in user){%>
                    <td><%= user[prop] %> </td>
                <% }%>

            </tr>
        <%})%>
</table>

Now write some simple JS as follows:

var arrOfObjects = [];
for (var s = 0; s < 10; s++) {
    var simpleObject = {};
    simpleObject.Name = "Name_" + s;
    simpleObject.Address = "Address_" + s;
    arrOfObjects[s] = simpleObject;
}
var theObject = { 'users': arrOfObjects }
var compiled = _.template($("#genTable").text());
var sigma = compiled({ 'users': myArr });

$(sigma).appendTo("#popup");

Where popoup is a div where you want to generate the table

Parsing a comma-delimited std::string

I'm surprised no one has proposed a solution using std::regex yet:

#include <string>
#include <algorithm>
#include <vector>
#include <regex>

void parse_csint( const std::string& str, std::vector<int>& result ) {

    typedef std::regex_iterator<std::string::const_iterator> re_iterator;
    typedef re_iterator::value_type re_iterated;

    std::regex re("(\\d+)");

    re_iterator rit( str.begin(), str.end(), re );
    re_iterator rend;

    std::transform( rit, rend, std::back_inserter(result), 
        []( const re_iterated& it ){ return std::stoi(it[1]); } );

}

This function inserts all integers at the back of the input vector. You can tweak the regular expression to include negative integers, or floating point numbers, etc.

Show loading screen when navigating between routes in Angular 2

If you have special logic required for the first route only you can do the following:

AppComponent

    loaded = false;

    constructor(private router: Router....) {
       router.events.pipe(filter(e => e instanceof NavigationEnd), take(1))
                    .subscribe((e) => {
                       this.loaded = true;
                       alert('loaded - this fires only once');
                   });

I had a need for this to hide my page footer, which was otherwise appearing at the top of the page. Also if you only want a loader for the first page you can use this.

Break out of a While...Wend loop

The best way is to use an And clause in your While statement

Dim count as Integer
count =0
While True And count <= 10
    count=count+1
    Debug.Print(count)
Wend

Change marker size in Google maps V3

This answer expounds on John Black's helpful answer, so I will repeat some of his answer content in my answer.

The easiest way to resize a marker seems to be leaving argument 2, 3, and 4 null and scaling the size in argument 5.

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|FFFF00",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(42, 68)
);  

As an aside, this answer to a similar question asserts that defining marker size in the 2nd argument is better than scaling in the 5th argument. I don't know if this is true.

Leaving arguments 2-4 null works great for the default google pin image, but you must set an anchor explicitly for the default google pin shadow image, or it will look like this:

what happens when you leave anchor null on an enlarged shadow

The bottom center of the pin image happens to be collocated with the tip of the pin when you view the graphic on the map. This is important, because the marker's position property (marker's LatLng position on the map) will automatically be collocated with the visual tip of the pin when you leave the anchor (4th argument) null. In other words, leaving the anchor null ensures the tip points where it is supposed to point.

However, the tip of the shadow is not located at the bottom center. So you need to set the 4th argument explicitly to offset the tip of the pin shadow so the shadow's tip will be colocated with the pin image's tip.

By experimenting I found the tip of the shadow should be set like this: x is 1/3 of size and y is 100% of size.

var pinShadow = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
    null,
    null,
    /* Offset x axis 33% of overall size, Offset y axis 100% of overall size */
    new google.maps.Point(40, 110), 
    new google.maps.Size(120, 110)); 

to give this:

offset the enlarged shadow anchor explicitly

OpenMP set_num_threads() is not working

According to the GCC manual for omp_get_num_threads:

In a sequential section of the program omp_get_num_threads returns 1

So this:

cout<<"sum="<<sum<<endl;
cout<<"threads="<<omp_get_num_threads()<<endl;

Should be changed to something like:

#pragma omp parallel
{
    cout<<"sum="<<sum<<endl;
    cout<<"threads="<<omp_get_num_threads()<<endl;
}

The code I use follows Hristo's advice of disabling dynamic teams, too.

Update MongoDB field using value of another field

Regarding this answer, the snapshot function is deprecated in version 3.6, according to this update. So, on version 3.6 and above, it is possible to perform the operation this way:

db.person.find().forEach(
    function (elem) {
        db.person.update(
            {
                _id: elem._id
            },
            {
                $set: {
                    name: elem.firstname + ' ' + elem.lastname
                }
            }
        );
    }
);

How to add custom method to Spring Data JPA

The accepted answer works, but has three problems:

  • It uses an undocumented Spring Data feature when naming the custom implementation as AccountRepositoryImpl. The documentation clearly states that it has to be called AccountRepositoryCustomImpl, the custom interface name plus Impl
  • You cannot use constructor injection, only @Autowired, that are considered bad practice
  • You have a circular dependency inside of the custom implementation (that's why you cannot use constructor injection).

I found a way to make it perfect, though not without using another undocumented Spring Data feature:

public interface AccountRepository extends AccountRepositoryBasic,
                                           AccountRepositoryCustom 
{ 
}

public interface AccountRepositoryBasic extends JpaRepository<Account, Long>
{
    // standard Spring Data methods, like findByLogin
}

public interface AccountRepositoryCustom 
{
    public void customMethod();
}

public class AccountRepositoryCustomImpl implements AccountRepositoryCustom 
{
    private final AccountRepositoryBasic accountRepositoryBasic;

    // constructor-based injection
    public AccountRepositoryCustomImpl(
        AccountRepositoryBasic accountRepositoryBasic)
    {
        this.accountRepositoryBasic = accountRepositoryBasic;
    }

    public void customMethod() 
    {
        // we can call all basic Spring Data methods using
        // accountRepositoryBasic
    }
}

how to reference a YAML "setting" from elsewhere in the same YAML file?

That your example is invalid is only because you chose a reserved character to start your scalars with. If you replace the * with some other non-reserved character (I tend to use non-ASCII characters for that as they are seldom used as part of some specification), you end up with perfectly legal YAML:

paths:
  root: /path/to/root/
  patha: ?root? + a
  pathb: ?root? + b
  pathc: ?root? + c

This will load into the standard representation for mappings in the language your parser uses and does not magically expand anything.
To do that use a locally default object type as in the following Python program:

# coding: utf-8

from __future__ import print_function

import ruamel.yaml as yaml

class Paths:
    def __init__(self):
        self.d = {}

    def __repr__(self):
        return repr(self.d).replace('ordereddict', 'Paths')

    @staticmethod
    def __yaml_in__(loader, data):
        result = Paths()
        loader.construct_mapping(data, result.d)
        return result

    @staticmethod
    def __yaml_out__(dumper, self):
        return dumper.represent_mapping('!Paths', self.d)

    def __getitem__(self, key):
        res = self.d[key]
        return self.expand(res)

    def expand(self, res):
        try:
            before, rest = res.split(u'?', 1)
            kw, rest = rest.split(u'? +', 1)
            rest = rest.lstrip() # strip any spaces after "+"
            # the lookup will throw the correct keyerror if kw is not found
            # recursive call expand() on the tail if there are multiple
            # parts to replace
            return before + self.d[kw] + self.expand(rest)
        except ValueError:
            return res

yaml_str = """\
paths: !Paths
  root: /path/to/root/
  patha: ?root? + a
  pathb: ?root? + b
  pathc: ?root? + c
"""

loader = yaml.RoundTripLoader
loader.add_constructor('!Paths', Paths.__yaml_in__)

paths = yaml.load(yaml_str, Loader=yaml.RoundTripLoader)['paths']

for k in ['root', 'pathc']:
    print(u'{} -> {}'.format(k, paths[k]))

which will print:

root -> /path/to/root/
pathc -> /path/to/root/c

The expanding is done on the fly and handles nested definitions, but you have to be careful about not invoking infinite recursion.

By specifying the dumper, you can dump the original YAML from the data loaded in, because of the on-the-fly expansion:

dumper = yaml.RoundTripDumper
dumper.add_representer(Paths, Paths.__yaml_out__)
print(yaml.dump(paths, Dumper=dumper, allow_unicode=True))

this will change the mapping key ordering. If that is a problem you have to make self.d a CommentedMap (imported from ruamel.yaml.comments.py)

What are the "standard unambiguous date" formats for string-to-date conversion in R?

As a complement to @JoshuaUlrich answer, here is the definition of function as.Date.character:

as.Date.character
function (x, format = "", ...) 
{
    charToDate <- function(x) {
        xx <- x[1L]
        if (is.na(xx)) {
            j <- 1L
            while (is.na(xx) && (j <- j + 1L) <= length(x)) xx <- x[j]
            if (is.na(xx)) 
                f <- "%Y-%m-%d"
        }
        if (is.na(xx) || !is.na(strptime(xx, f <- "%Y-%m-%d", 
            tz = "GMT")) || !is.na(strptime(xx, f <- "%Y/%m/%d", 
            tz = "GMT"))) 
            return(strptime(x, f))
        stop("character string is not in a standard unambiguous format")
    }
    res <- if (missing(format)) 
        charToDate(x)
    else strptime(x, format, tz = "GMT")
    as.Date(res)
}
<bytecode: 0x265b0ec>
<environment: namespace:base>

So basically if both strptime(x, format="%Y-%m-%d") and strptime(x, format="%Y/%m/%d") throws an NA it is considered ambiguous and if not unambiguous.

Right pad a string with variable number of spaces

Based on KMier's answer, addresses the comment that this method poses a problem when the field to be padded is not a field, but the outcome of a (possibly complicated) function; the entire function has to be repeated.

Also, this allows for padding a field to the maximum length of its contents.

WITH
cte AS (
  SELECT 'foo' AS value_to_be_padded
  UNION SELECT 'foobar'
),
cte_max AS (
  SELECT MAX(LEN(value_to_be_padded)) AS max_len
)
SELECT
  CONCAT(SPACE(max_len - LEN(value_to_be_padded)), value_to_be_padded AS left_padded,
  CONCAT(value_to_be_padded, SPACE(max_len - LEN(value_to_be_padded)) AS right_padded;

How can I style a PHP echo text?

You can "style echo" with adding new HTML code.

echo '<span class="city">' . $ip['cityName'] . '</span>';

Android: how to make keyboard enter button say "Search" and handle its click?

This answer is for TextInputEditText :

In the layout XML file set your input method options to your required type. for example done.

<com.google.android.material.textfield.TextInputLayout
        android:id="@+id/textInputLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <com.google.android.material.textfield.TextInputEditText
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:imeOptions="actionGo"/>

</com.google.android.material.textfield.TextInputLayout>

Similarly, you can also set imeOptions to actionSubmit, actionSearch, etc

In the java add the editor action listener.

TextInputLayout textInputLayout = findViewById(R.id.textInputLayout);

textInputLayout.getEditText().setOnEditorActionListener(new 

    TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if (actionId == EditorInfo.IME_ACTION_GO) {
                performYourAction();
                return true;
            }
            return false;
        }
    });

If you're using kotlin :

textInputLayout.editText.setOnEditorActionListener { _, actionId, _ ->
    if (actionId == EditorInfo.IME_ACTION_GO) {
        performYourAction()
    }
    true
}

What does -z mean in Bash?

-z

string is null, that is, has zero length

String=''   # Zero-length ("null") string variable.

if [ -z "$String" ]
then
  echo "\$String is null."
else
  echo "\$String is NOT null."
fi     # $String is null.

How do I resize a Google Map with JavaScript after it has loaded?

This is best it will do the Job done. It will re-size your Map. No need to inspect element anymore to re-size your Map. What it does it will automatically trigger re-size event .

    google.maps.event.addListener(map, "idle", function()
        {
            google.maps.event.trigger(map, 'resize');
        });

        map_array[Next].setZoom( map.getZoom() - 1 );
    map_array[Next].setZoom( map.getZoom() + 1 );

Using form input to access camera and immediately upload photos using web app

It's really easy to do this, simply send the file via an XHR request inside of the file input's onchange handler.

<input id="myFileInput" type="file" accept="image/*;capture=camera">

var myInput = document.getElementById('myFileInput');

function sendPic() {
    var file = myInput.files[0];

    // Send file here either by adding it to a `FormData` object 
    // and sending that via XHR, or by simply passing the file into 
    // the `send` method of an XHR instance.
}

myInput.addEventListener('change', sendPic, false);

Start an activity from a fragment

with Kotlin I execute this code:

requireContext().startActivity<YourTargetActivity>()

Lining up labels with radio buttons in bootstrap

In Bootstrap 4 you can use the form-check-inline class.

<div class="form-check form-check-inline">
  <input class="form-check-input" type="radio" name="queryFieldName" id="option1" value="1">
  <label class="form-check-label" for="option1">First</label>
</div>
<div class="form-check form-check-inline">
  <input class="form-check-input" type="radio" name="queryFieldName" id="option2" value="2">
  <label class="form-check-label" for="option2">Second</label>
</div>

How can I make Bootstrap 4 columns all the same height?

You can use the new Bootstrap cards:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link: Click here

regards,

How to connect to MongoDB in Windows?

I found that when I got this error it wasn't because I didn't have my default db path set up. It was because I was trying to run mongo.exe before running mongod.exe.

How to find elements by class

Specific to BeautifulSoup 3:

soup.findAll('div',
             {'class': lambda x: x 
                       and 'stylelistrow' in x.split()
             }
            )

Will find all of these:

<div class="stylelistrow">
<div class="stylelistrow button">
<div class="button stylelistrow">

What's the most efficient way to check if a record exists in Oracle?

select NVL ((select 'Y' from  dual where exists
   (select  1 from sales where sales_type = 'Accessories')),'N') as rec_exists
from dual

1.Dual table will return 'Y' if record exists in sales_type table 2.Dual table will return null if no record exists in sales_type table and NVL will convert that to 'N'

Vbscript list all PDF files in folder and subfolders

The file extension may be case sentive...but the code works.

Set objFSO = CreateObject("Scripting.FileSystemObject")
  objStartFolder = "C:\Dev\"

  Set objFolder = objFSO.GetFolder(objStartFolder)
  Wscript.Echo objFolder.Path

  Set colFiles = objFolder.Files

  For Each objFile in colFiles
  strFileName = objFile.Name

  If objFSO.GetExtensionName(strFileName) = "pdf" Then
      Wscript.Echo objFile.Name
  End If

  Next
  Wscript.Echo

  ShowSubfolders objFSO.GetFolder(objStartFolder)

  Sub ShowSubFolders(Folder)
     For Each Subfolder in Folder.SubFolders
          Wscript.Echo Subfolder.Path
          Set objFolder = objFSO.GetFolder(Subfolder.Path)
          Set colFiles = objFolder.Files
          For Each objFile in colFiles
              Wscript.Echo objFile.Name
          Next
          Wscript.Echo
          ShowSubFolders Subfolder
      Next
  End Sub

Unable to Git-push master to Github - 'origin' does not appear to be a git repository / permission denied

I have the same problem and i think the firewall is blocking the git protocol. So in the end I have to resort to using https:// to fetch and push. However this will always prompt the user to enter the password...

here is the example what working for me (just to share with those cant use git:// protocol :)

git fetch https://[user-name]@github.com/[user-name]/[project].git

if the above works, you can remove the origin and replace with

git remote rm origin  
git remote add origin https://[user-name]@github.com/[user-name]/[project].git

"Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6

I was also facing the same issue until I added the type="module" to the script.

Before it was like this

<script src="../src/main.js"></script>

And after changing it to

<script type="module" src="../src/main.js"></script>

It worked perfectly.

Why this line xmlns:android="http://schemas.android.com/apk/res/android" must be the first in the layout xml file?

xmlns:android="http://schemas.android.com/apk/res/android"

This is form of xmlns:android ="@+/id". Now to refernce it we use for example

android:layout_width="wrap_content"
android:text="Hello World!"

Another xmlns is

 xmlns:app="http://schemas.android.com/apk/res-auto"

which is in form of xmlns:app = "@+/id" and its use is given below

 app:layout_constraintBottom_toBottomOf="parent"
 app:layout_constraintLeft_toLeftOf="parent"

Saving image to file

You can try with this code

Image.Save("myfile.png", ImageFormat.Png)

Link : http://msdn.microsoft.com/en-us/library/ms142147.aspx

How to find a whole word in a String in java

Use regex + word boundaries as others answered.

"I will come and meet you at the 123woods".matches(".*\\b123woods\\b.*");

will be true.

"I will come and meet you at the 123woods".matches(".*\\bwoods\\b.*");

will be false.

Declaring and initializing arrays in C

Is there a way to declare first and then initialize an array in C?

There is! but not using the method you described.

You can't initialize with a comma separated list, this is only allowed in the declaration. You can however initialize with...

myArray[0] = 1;
myArray[1] = 2;
...

or

for(int i = 1; i <= SIZE; i++)
{
  myArray[i-1] = i;
}

Regular expression to extract numbers from a string

^\s*(\w+)\s*\(\s*(\d+)\D+(\d+)\D+\)\s*$

should work. After the match, backreference 1 will contain the month, backreference 2 will contain the first number and backreference 3 the second number.

Explanation:

^     # start of string
\s*   # optional whitespace
(\w+) # one or more alphanumeric characters, capture the match
\s*   # optional whitespace
\(    # a (
\s*   # optional whitespace
(\d+) # a number, capture the match
\D+   # one or more non-digits
(\d+) # a number, capture the match
\D+   # one or more non-digits
\)    # a )
\s*   # optional whitespace
$     # end of string

Typescript export vs. default export

Default Export (export default)

// MyClass.ts -- using default export
export default class MyClass { /* ... */ }

The main difference is that you can only have one default export per file and you import it like so:

import MyClass from "./MyClass";

You can give it any name you like. For example this works fine:

import MyClassAlias from "./MyClass";

Named Export (export)

// MyClass.ts -- using named exports
export class MyClass { /* ... */ }
export class MyOtherClass { /* ... */ }

When you use a named export, you can have multiple exports per file and you need to import the exports surrounded in braces:

import { MyClass } from "./MyClass";

Note: Adding the braces will fix the error you're describing in your question and the name specified in the braces needs to match the name of the export.

Or say your file exported multiple classes, then you could import both like so:

import { MyClass, MyOtherClass } from "./MyClass";
// use MyClass and MyOtherClass

Or you could give either of them a different name in this file:

import { MyClass, MyOtherClass as MyOtherClassAlias } from "./MyClass";
// use MyClass and MyOtherClassAlias

Or you could import everything that's exported by using * as:

import * as MyClasses from "./MyClass";
// use MyClasses.MyClass and MyClasses.MyOtherClass here

Which to use?

In ES6, default exports are concise because their use case is more common; however, when I am working on code internal to a project in TypeScript, I prefer to use named exports instead of default exports almost all the time because it works very well with code refactoring. For example, if you default export a class and rename that class, it will only rename the class in that file and not any of the other references in other files. With named exports it will rename the class and all the references to that class in all the other files.

It also plays very nicely with barrel files (files that use namespace exports—export *—to export other files). An example of this is shown in the "example" section of this answer.

Note that my opinion on using named exports even when there is only one export is contrary to the TypeScript Handbook—see the "Red Flags" section. I believe this recommendation only applies when you are creating an API for other people to use and the code is not internal to your project. When I'm designing an API for people to use, I'll use a default export so people can do import myLibraryDefaultExport from "my-library-name";. If you disagree with me about doing this, I would love to hear your reasoning.

That said, find what you prefer! You could use one, the other, or both at the same time.

Additional Points

A default export is actually a named export with the name default, so if the file has a default export then you can also import by doing:

import { default as MyClass } from "./MyClass";

And take note these other ways to import exist: 

import MyDefaultExportedClass, { Class1, Class2 } from "./SomeFile";
import MyDefaultExportedClass, * as Classes from "./SomeFile";
import "./SomeFile"; // runs SomeFile.js without importing any exports

Microsoft Excel mangles Diacritics in .csv files?

The CSV format is implemented as ASCII, not unicode, in Excel, thus mangling the diacritics. We experienced the same issue which is how I tracked down that the official CSV standard was defined as being ASCII-based in Excel.

How to add header to a dataset in R?

You can do the following:

Load the data:

test <- read.csv(
          "http://archive.ics.uci.edu/ml/machine-learning-databases/breast-cancer-wisconsin/breast-cancer-wisconsin.data",
          header=FALSE)

Note that the default value of the header argument for read.csv is TRUE so in order to get all lines you need to set it to FALSE.

Add names to the different columns in the data.frame

names(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

or alternative and faster as I understand (not reloading the entire dataset):

colnames(test) <- c("A","B","C","D","E","F","G","H","I","J","K")

"You tried to execute a query that does not include the specified aggregate function"

The error is because fName is included in the SELECT list, but is not included in a GROUP BY clause and is not part of an aggregate function (Count(), Min(), Max(), Sum(), etc.)

You can fix that problem by including fName in a GROUP BY. But then you will face the same issue with surname. So put both in the GROUP BY:

SELECT
    fName,
    surname,
    Count(*) AS num_rows
FROM
    author
    INNER JOIN book
    ON author.aID = book.authorID;
GROUP BY
    fName,
    surname

Note I used Count(*) where you wanted SUM(orders.quantity). However, orders isn't included in the FROM section of your query, so you must include it before you can Sum() one of its fields.

If you have Access available, build the query in the query designer. It can help you understand what features are possible and apply the correct Access SQL syntax.

WPF binding to Listbox selectedItem

Inside the DataTemplate you're working in the context of a Rule, that's why you cannot bind to SelectedRule.Name -- there is no such property on a Rule. To bind to the original data context (which is your ViewModel) you can write:

<TextBlock Text="{Binding ElementName=lbRules, Path=DataContext.SelectedRule.Name}" />

UPDATE: regarding the SelectedItem property binding, it looks perfectly valid, I tried the same on my machine and it works fine. Here is my full test app:

XAML:

<Window x:Class="TestWpfApplication.ListBoxSelectedItem"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="ListBoxSelectedItem" Height="300" Width="300"
    xmlns:app="clr-namespace:TestWpfApplication">
    <Window.DataContext>
        <app:ListBoxSelectedItemViewModel/>
    </Window.DataContext>
    <ListBox ItemsSource="{Binding Path=Rules}" SelectedItem="{Binding Path=SelectedRule, Mode=TwoWay}">
        <ListBox.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="Name:" />
                    <TextBox Text="{Binding Name}"/>
                </StackPanel>
            </DataTemplate>
        </ListBox.ItemTemplate>
    </ListBox>
</Window>

Code behind:

namespace TestWpfApplication
{
    /// <summary>
    /// Interaction logic for ListBoxSelectedItem.xaml
    /// </summary>
    public partial class ListBoxSelectedItem : Window
    {
        public ListBoxSelectedItem()
        {
            InitializeComponent();
        }
    }


    public class Rule
    {
        public string Name { get; set; }
    }

    public class ListBoxSelectedItemViewModel
    {
        public ListBoxSelectedItemViewModel()
        {
            Rules = new ObservableCollection<Rule>()
            {
                new Rule() { Name = "Rule 1"},
                new Rule() { Name = "Rule 2"},
                new Rule() { Name = "Rule 3"},
            };
        }

        public ObservableCollection<Rule> Rules { get; private set; }

        private Rule selectedRule;
        public Rule SelectedRule
        {
            get { return selectedRule; }
            set
            {
                selectedRule = value;
            }
        }
    }
}

How to convert milliseconds to seconds with precision

Surely you just need:

double seconds = milliseconds / 1000.0;

There's no need to manually do the two parts separately - you just need floating point arithmetic, which the use of 1000.0 (as a double literal) forces. (I'm assuming your milliseconds value is an integer of some form.)

Note that as usual with double, you may not be able to represent the result exactly. Consider using BigDecimal if you want to represent 100ms as 0.1 seconds exactly. (Given that it's a physical quantity, and the 100ms wouldn't be exact in the first place, a double is probably appropriate, but...)

GitHub - error: failed to push some refs to '[email protected]:myrepo.git'

$ git fetch --unshallow origin
$ git push you remote name

Custom thread pool in Java 8 parallel stream

you can try implementing this ForkJoinWorkerThreadFactory and inject it to Fork-Join class.

public ForkJoinPool(int parallelism,
                        ForkJoinWorkerThreadFactory factory,
                        UncaughtExceptionHandler handler,
                        boolean asyncMode) {
        this(checkParallelism(parallelism),
             checkFactory(factory),
             handler,
             asyncMode ? FIFO_QUEUE : LIFO_QUEUE,
             "ForkJoinPool-" + nextPoolId() + "-worker-");
        checkPermission();
    }

you can use this constructor of Fork-Join pool to do this.

notes:-- 1. if you use this, take into consideration that based on your implementation of new threads, scheduling from JVM will be affected, which generally schedules fork-join threads to different cores(treated as a computational thread). 2. task scheduling by fork-join to threads won't get affected. 3. Haven't really figured out how parallel stream is picking threads from fork-join(couldn't find proper documentation on it), so try using a different threadNaming factory so as to make sure, if threads in parallel stream are being picked from customThreadFactory that you provide. 4. commonThreadPool won't use this customThreadFactory.

Python : List of dict, if exists increment a dict value, if not append a new dict

To do it exactly your way? You could use the for...else structure

for url in list_of_urls:
    for url_dict in urls:
        if url_dict['url'] == url:
            url_dict['nbr'] += 1
            break
    else:
        urls.append(dict(url=url, nbr=1))

But it is quite inelegant. Do you really have to store the visited urls as a LIST? If you sort it as a dict, indexed by url string, for example, it would be way cleaner:

urls = {'http://www.google.fr/': dict(url='http://www.google.fr/', nbr=1)}

for url in list_of_urls:
    if url in urls:
        urls[url]['nbr'] += 1
    else:
        urls[url] = dict(url=url, nbr=1)

A few things to note in that second example:

  • see how using a dict for urls removes the need for going through the whole urls list when testing for one single url. This approach will be faster.
  • Using dict( ) instead of braces makes your code shorter
  • using list_of_urls, urls and url as variable names make the code quite hard to parse. It's better to find something clearer, such as urls_to_visit, urls_already_visited and current_url. I know, it's longer. But it's clearer.

And of course I'm assuming that dict(url='http://www.google.fr', nbr=1) is a simplification of your own data structure, because otherwise, urls could simply be:

urls = {'http://www.google.fr':1}

for url in list_of_urls:
    if url in urls:
        urls[url] += 1
    else:
        urls[url] = 1

Which can get very elegant with the defaultdict stance:

urls = collections.defaultdict(int)
for url in list_of_urls:
    urls[url] += 1

POSTing JSON to URL via WebClient in C#

The following example demonstrates how to POST a JSON via WebClient.UploadString Method:

var vm = new { k = "1", a = "2", c = "3", v=  "4" };
using (var client = new WebClient())
{
   var dataString = JsonConvert.SerializeObject(vm);
   client.Headers.Add(HttpRequestHeader.ContentType, "application/json");
   client.UploadString(new Uri("http://www.contoso.com/1.0/service/action"), "POST", dataString);
}

Prerequisites: Json.NET library

case statement in where clause - SQL Server

simply do the select:

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date) AND
((@day = 'Monday' AND (Monday = 1))
OR (@day = 'Tuesday' AND (Tuesday = 1))
OR (Wednesday = 1))

this in equals method

this is the current Object instance. Whenever you have a non-static method, it can only be called on an instance of your object.

Get exit code of a background process

My solution was to use an anonymous pipe to pass the status to a monitoring loop. There are no temporary files used to exchange status so nothing to cleanup. If you were uncertain about the number of background jobs the break condition could be [ -z "$(jobs -p)" ].

#!/bin/bash

exec 3<> <(:)

{ sleep 15 ; echo "sleep/exit $?" >&3 ; } &

while read -u 3 -t 1 -r STAT CODE || STAT="timeout" ; do
    echo "stat: ${STAT}; code: ${CODE}"
    if [ "${STAT}" = "sleep/exit" ] ; then
        break
    fi
done

HTTP Status 500 - Error instantiating servlet class pkg.coreServlet

Make sure the following:

  1. Proper "war" file structure i.e. WEB-INF & META-INF
  2. "web.xml" file is setup correct.
  3. Last and important: private static final long serialVersionUID = 1L; should be there in your class (<servlet-class>MyClass</servlet-class>).

Horizontal line using HTML/CSS

I have try this my new code and it might be helpful to you, it works perfectly in google chromr

hr {
     color: #f00;
     background: #f00; 
     width: 75%; 
     height: 5px;
}

How to get the Parent's parent directory in Powershell?

In PowerShell 3, $PsScriptRoot or for your question of two parents up,

$dir = ls "$PsScriptRoot\..\.."

Conditional WHERE clause in SQL Server

Try this one -

WHERE DateDropped = 0
    AND (
        (ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0) 
        OR 
        (ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)
    )

Regex for password must contain at least eight characters, at least one number and both lower and uppercase letters and special characters

You can use the below regular expression pattern to check the password whether it matches your expectations or not.

((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[~!@#$%^&*()]).{8,20})

Does the Java &= operator apply & or &&?

From the Java Language Specification - 15.26.2 Compound Assignment Operators.

A compound assignment expression of the form E1 op= E2 is equivalent to E1 = (T)((E1) op (E2)), where T is the type of E1, except that E1 is evaluated only once.

So a &= b; is equivalent to a = a & b;.

(In some usages, the type-casting makes a difference to the result, but in this one b has to be boolean and the type-cast does nothing.)

And, for the record, a &&= b; is not valid Java. There is no &&= operator.


In practice, there is little semantic difference between a = a & b; and a = a && b;. (If b is a variable or a constant, the result is going to be the same for both versions. There is only a semantic difference when b is a subexpression that has side-effects. In the & case, the side-effect always occurs. In the && case it occurs depending on the value of a.)

On the performance side, the trade-off is between the cost of evaluating b, and the cost of a test and branch of the value of a, and the potential saving of avoiding an unnecessary assignment to a. The analysis is not straight-forward, but unless the cost of calculating b is non-trivial, the performance difference between the two versions is too small to be worth considering.

javax.net.ssl.SSLException: Received fatal alert: protocol_version

public class SecureSocket {
static {
    // System.setProperty("javax.net.debug", "all");
    System.setProperty("https.protocols", "TLSv1,TLSv1.1,TLSv1.2");
}
public static void main(String[] args) {
    String GhitHubSSLFile = "https://raw.githubusercontent.com/Yash-777/SeleniumWebDrivers/master/pom.xml";
    try {
        String str = readCloudFileAsString(GhitHubSSLFile);
                // new String(Files.readAllBytes(Paths.get( "D:/Sample.file" )));

        System.out.println("Cloud File Data : "+ str);
    } catch (IOException e) {
        e.printStackTrace();
    }
}
public static String readCloudFileAsString( String urlStr ) throws java.io.IOException {
    if( urlStr != null && urlStr != "" ) {
        java.io.InputStream s = null;
        String content = null;
        try {
            URL url = new URL( urlStr );
            s = (java.io.InputStream) url.getContent();
            content = IOUtils.toString(s, "UTF-8");
        }  
        }
        return content.toString();
    }
    return null;
}

Factory Reset Help }

How do you get a string from a MemoryStream?

A slightly modified version of Brian's answer allows optional management of read start, This seems to be the easiest method. probably not the most efficient, but easy to understand and use.

Public Function ReadAll(ByVal memStream As MemoryStream, Optional ByVal startPos As Integer = 0) As String
    ' reset the stream or we'll get an empty string returned
    ' remember the position so we can restore it later
    Dim Pos = memStream.Position
    memStream.Position = startPos

    Dim reader As New StreamReader(memStream)
    Dim str = reader.ReadToEnd()

    ' reset the position so that subsequent writes are correct
    memStream.Position = Pos

    Return str
End Function

Tesseract OCR simple example

Here's a great working example project; Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing Tesseract OCR Sample (Visual Studio) with Leptonica Preprocessing

Tesseract OCR 3.02.02 API can be confusing, so this guides you through including the Tesseract and Leptonica dll into a Visual Studio C++ Project, and provides a sample file which takes an image path to preprocess and OCR. The preprocessing script in Leptonica converts the input image into black and white book-like text.

Setup

To include this in your own projects, you will need to reference the header files and lib and copy the tessdata folders and dlls.

Copy the tesseract-include folder to the root folder of your project. Now Click on your project in Visual Studio Solution Explorer, and go to Project>Properties.

VC++ Directories>Include Directories:

..\tesseract-include\tesseract;..\tesseract-include\leptonica;$(IncludePath) C/C++>Preprocessor>Preprocessor Definitions:

_CRT_SECURE_NO_WARNINGS;%(PreprocessorDefinitions) C/C++>Linker>Input>Additional Dependencies:

..\tesseract-include\libtesseract302.lib;..\tesseract-include\liblept168.lib;%(AdditionalDependencies) Now you can include headers in your project's file:

include

include

Now copy the two dll files in tesseract-include and the tessdata folder in Debug to the Output Directory of your project.

When you initialize tesseract, you need to specify the location of the parent folder (!important) of the tessdata folder if it is not already the current directory of your executable file. You can copy my script, which assumes tessdata is installed in the executable's folder.

tesseract::TessBaseAPI *api = new tesseract::TessBaseAPI(); api->Init("D:\tessdataParentFolder\", ... Sample

You can compile the provided sample, which takes one command line argument of the image path to use. The preprocess() function uses Leptonica to create a black and white book-like copy of the image which makes tesseract work with 90% accuracy. The ocr() function shows the functionality of the Tesseract API to return a string output. The toClipboard() can be used to save text to clipboard on Windows. You can copy these into your own projects.

JQuery, Spring MVC @RequestBody and JSON - making it work together

I'm pretty sure you only have to register MappingJacksonHttpMessageConverter

(the easiest way to do that is through <mvc:annotation-driven /> in XML or @EnableWebMvc in Java)

See:


Here's a working example:

Maven POM

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion><groupId>test</groupId><artifactId>json</artifactId><packaging>war</packaging>
    <version>0.0.1-SNAPSHOT</version><name>json test</name>
    <dependencies>
        <dependency><!-- spring mvc -->
            <groupId>org.springframework</groupId><artifactId>spring-webmvc</artifactId><version>3.0.5.RELEASE</version>
        </dependency>
        <dependency><!-- jackson -->
            <groupId>org.codehaus.jackson</groupId><artifactId>jackson-mapper-asl</artifactId><version>1.4.2</version>
        </dependency>
    </dependencies>
    <build><plugins>
            <!-- javac --><plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId>
            <version>2.3.2</version><configuration><source>1.6</source><target>1.6</target></configuration></plugin>
            <!-- jetty --><plugin><groupId>org.mortbay.jetty</groupId><artifactId>jetty-maven-plugin</artifactId>
            <version>7.4.0.v20110414</version></plugin>
    </plugins></build>
</project>

in folder src/main/webapp/WEB-INF

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
    version="2.4">
    <servlet><servlet-name>json</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>json</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

json-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
                        http://www.springframework.org/schema/beans/spring-beans.xsd">

    <import resource="classpath:mvc-context.xml" />

</beans>

in folder src/main/resources:

mvc-context.xml

<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <mvc:annotation-driven />
    <context:component-scan base-package="test.json" />
</beans>

In folder src/main/java/test/json

TestController.java

@Controller
@RequestMapping("/test")
public class TestController {

    @RequestMapping(method = RequestMethod.POST, value = "math")
    @ResponseBody
    public Result math(@RequestBody final Request request) {
        final Result result = new Result();
        result.setAddition(request.getLeft() + request.getRight());
        result.setSubtraction(request.getLeft() - request.getRight());
        result.setMultiplication(request.getLeft() * request.getRight());
        return result;
    }

}

Request.java

public class Request implements Serializable {
    private static final long serialVersionUID = 1513207428686438208L;
    private int left;
    private int right;
    public int getLeft() {return left;}
    public void setLeft(int left) {this.left = left;}
    public int getRight() {return right;}
    public void setRight(int right) {this.right = right;}
}

Result.java

public class Result implements Serializable {
    private static final long serialVersionUID = -5054749880960511861L;
    private int addition;
    private int subtraction;
    private int multiplication;

    public int getAddition() { return addition; }
    public void setAddition(int addition) { this.addition = addition; }
    public int getSubtraction() { return subtraction; }
    public void setSubtraction(int subtraction) { this.subtraction = subtraction; }
    public int getMultiplication() { return multiplication; }
    public void setMultiplication(int multiplication) { this.multiplication = multiplication; }
}

You can test this setup by executing mvn jetty:run on the command line, and then sending a POST request:

URL:        http://localhost:8080/test/math
mime type:  application/json
post body:  { "left": 13 , "right" : 7 }

I used the Poster Firefox plugin to do this.

Here's what the response looks like:

{"addition":20,"subtraction":6,"multiplication":91}

SQL conditional SELECT

@selectField1 AS bit
@selectField2 AS bit

SELECT
CASE 
    WHEN @selectField1 THEN Field1
    WHEN @selectField2 THEN Field2
    ELSE someDefaultField
END
FROM Table

Is this what you're looking for?

What is the difference between const int*, const int * const, and int const *?

I think everything is answered here already, but I just want to add that you should beware of typedefs! They're NOT just text replacements.

For example:

typedef char *ASTRING;
const ASTRING astring;

The type of astring is char * const, not const char *. This is one reason I always tend to put const to the right of the type, and never at the start.

How to do the equivalent of pass by reference for primitives in Java

For a quick solution, you can use AtomicInteger or any of the atomic variables which will let you change the value inside the method using the inbuilt methods. Here is sample code:

import java.util.concurrent.atomic.AtomicInteger;


public class PrimitivePassByReferenceSample {

    /**
     * @param args
     */
    public static void main(String[] args) {

        AtomicInteger myNumber = new AtomicInteger(0);
        System.out.println("MyNumber before method Call:" + myNumber.get());
        PrimitivePassByReferenceSample temp = new PrimitivePassByReferenceSample() ;
        temp.changeMyNumber(myNumber);
        System.out.println("MyNumber After method Call:" + myNumber.get());


    }

     void changeMyNumber(AtomicInteger myNumber) {
        myNumber.getAndSet(100);

    }

}

Output:

MyNumber before method Call:0

MyNumber After method Call:100

adb uninstall failed

If You use Xiomi Device then You need to Login in MI Account.

After Successful Registration you can install and Uninstall via ADB.

Get client IP address via third party web service

Well, if in the HTML you import a script...

<script type="text/javascript" src="//stier.linuxfaq.org/ip.php"></script>

You can then use the variable userIP (which would be the visitor's IP address) anywhere on the page.

To redirect: <script>if (userIP == "555.555.555.55") {window.location.replace("http://192.168.1.3/flex-start/examples/navbar-fixed-top/");}</script>

Or to show it on the page: document.write (userIP);

DISCLAIMER: I am the author of the script I said to import. The script comes up with the IP by using PHP. The source code of the script is below.

<?php //Gets the IP address $ip = getenv("REMOTE_ADDR") ; Echo "var userIP = '" . $ip . "';"; ?>

How to create multiple class objects with a loop in python?

Using a dictionary for unique names without a name list:

class MyClass:
    def __init__(self, name):
        self.name = name
        self.pretty_print_name()

    def pretty_print_name(self):
    print("This object's name is {}.".format(self.name))

my_objects = {}
for i in range(1,11):
    name = 'obj_{}'.format(i)
    my_objects[name] = my_objects.get(name, MyClass(name = name))

Output:

"This object's name is obj_1."
"This object's name is obj_2."
"This object's name is obj_3."
"This object's name is obj_4."
"This object's name is obj_5."
"This object's name is obj_6."
"This object's name is obj_7."
"This object's name is obj_8."
"This object's name is obj_9."
"This object's name is obj_10."

Is there a way to get version from package.json in nodejs code?

There is another way of fetching certain information from your package.json file namely using pkginfo module.

Usage of this module is very simple. You can get all package variables using:

require('pkginfo')(module);

Or only certain details (version in this case)

require('pkginfo')(module, 'version');

And your package variables will be set to module.exports (so version number will be accessible via module.exports.version).

You could use the following code snippet:

require('pkginfo')(module, 'version');
console.log "Express server listening on port %d in %s mode %s", app.address().port, app.settings.env, module.exports.version

This module has very nice feature - it can be used in any file in your project (e.g. in subfolders) and it will automatically fetch information from your package.json. So you do not have to worry where you package.json is.

I hope that will help.

laravel Unable to prepare route ... for serialization. Uses Closure

The Actual solution of this problem is changing first line in web.php

Just replace Welcome route with following route

Route::view('/', 'welcome');

If still getting same error than you probab

Can git undo a checkout of unstaged files

I believe if a file is modified but not yet added (staged), it is purely "private".
Meaning it cannot be restored by GIT if overwritten with the index or the HEAD version (unless you have a copy of your current work somewhere).

A "private" content is one only visible in your current directory, but not registered in any way in Git.

Note: As explained in other answers, you can recover your changes if you use an IDE (with local history) or have an open editor (ctrl+Z).