Programs & Examples On #Distributed cache

How to get visitor's location (i.e. country) using geolocation?

For developers looking for a full-featured geolocation utility, you can have a look at geolocator.js (I'm the author).

Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.

var options = {
    enableHighAccuracy: true,
    timeout: 6000,
    maximumAge: 0,
    desiredAccuracy: 30,
    fallbackToIP: true, // if HTML5 geolocation fails or rejected
    addressLookup: true, // get detailed address information
    timezone: true, 
    map: "my-map" // this will even create a map for you
};

geolocator.locate(options, function (err, location) {
    console.log(err || location);
});

It supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and more...

Trying to use INNER JOIN and GROUP BY SQL with SUM Function, Not Working

Use subquery

SELECT * FROM RES_DATA inner join (SELECT [CUSTOMER ID], sum([TOTAL AMOUNT]) FROM INV_DATA group by [CUSTOMER ID]) T on RES_DATA.[CUSTOMER ID] = t.[CUSTOMER ID]

Copy every nth line from one sheet to another

If I were confronted with extracting every 7th row I would “insert” a column before Column “A” . I would then (assuming that there is a header row in row 1) type in the numbers 1,2,3,4,5,6,7 in rows 2,3,4,5,6,7,8, I would highlight the 1,2,3,4,5,6,7 and paste that block to the end of the sheet (700 rows worth). The result will be 1,23,4,5,6,7,1,2,3,4,5,6,7,1,2,3,4,5,6,7……. Now do a data sort ascending on column “A”. After the sort all of the 1’s will be the first in the series, all of the 7’s will be the seventh item.

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

Since your task might contain asynchronous code you have to signal gulp when your task has finished executing (= "async completion").

In Gulp 3.x you could get away without doing this. If you didn't explicitly signal async completion gulp would just assume that your task is synchronous and that it is finished as soon as your task function returns. Gulp 4.x is stricter in this regard. You have to explicitly signal task completion.

You can do that in six ways:

1. Return a Stream

This is not really an option if you're only trying to print something, but it's probably the most frequently used async completion mechanism since you're usually working with gulp streams. Here's a (rather contrived) example demonstrating it for your use case:

var print = require('gulp-print');

gulp.task('message', function() {
  return gulp.src('package.json')
    .pipe(print(function() { return 'HTTP Server Started'; }));
});

The important part here is the return statement. If you don't return the stream, gulp can't determine when the stream has finished.

2. Return a Promise

This is a much more fitting mechanism for your use case. Note that most of the time you won't have to create the Promise object yourself, it will usually be provided by a package (e.g. the frequently used del package returns a Promise).

gulp.task('message', function() { 
  return new Promise(function(resolve, reject) {
    console.log("HTTP Server Started");
    resolve();
  });
});

Using async/await syntax this can be simplified even further. All functions marked async implicitly return a Promise so the following works too (if your node.js version supports it):

gulp.task('message', async function() {
  console.log("HTTP Server Started");
});

3. Call the callback function

This is probably the easiest way for your use case: gulp automatically passes a callback function to your task as its first argument. Just call that function when you're done:

gulp.task('message', function(done) {
  console.log("HTTP Server Started");
  done();
});

4. Return a child process

This is mostly useful if you have to invoke a command line tool directly because there's no node.js wrapper available. It works for your use case but obviously I wouldn't recommend it (especially since it's not very portable):

var spawn = require('child_process').spawn;

gulp.task('message', function() {
  return spawn('echo', ['HTTP', 'Server', 'Started'], { stdio: 'inherit' });
});

5. Return a RxJS Observable.

I've never used this mechanism, but if you're using RxJS it might be useful. It's kind of overkill if you just want to print something:

var of = require('rxjs').of;

gulp.task('message', function() {
  var o = of('HTTP Server Started');
  o.subscribe(function(msg) { console.log(msg); });
  return o;
});

6. Return an EventEmitter

Like the previous one I'm including this for completeness sake, but it's not really something you're going to use unless you're already using an EventEmitter for some reason.

gulp.task('message3', function() {
  var e = new EventEmitter();
  e.on('msg', function(msg) { console.log(msg); });
  setTimeout(() => { e.emit('msg', 'HTTP Server Started'); e.emit('finish'); });
  return e;
});

What's the right way to decode a string that has special HTML entities in it?

jQuery will encode and decode for you.

_x000D_
_x000D_
function htmlDecode(value) {_x000D_
  return $("<textarea/>").html(value).text();_x000D_
}_x000D_
_x000D_
function htmlEncode(value) {_x000D_
  return $('<textarea/>').text(value).html();_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<script>_x000D_
$(document).ready(function() {_x000D_
   $("#encoded")_x000D_
  .text(htmlEncode("<img src onerror='alert(0)'>"));_x000D_
   $("#decoded")_x000D_
  .text(htmlDecode("&lt;img src onerror='alert(0)'&gt;"));_x000D_
});_x000D_
</script>_x000D_
_x000D_
<span>htmlEncode() result:</span><br/>_x000D_
<div id="encoded"></div>_x000D_
<br/>_x000D_
<span>htmlDecode() result:</span><br/>_x000D_
<div id="decoded"></div>
_x000D_
_x000D_
_x000D_

Add/remove HTML inside div using JavaScript

please try following to generate

 function addRow()
    {
        var e1 = document.createElement("input");
        e1.type = "text";
        e1.name = "name1";

        var cont = document.getElementById("content")
        cont.appendChild(e1);

    }

File opens instead of downloading in internet explorer in a href link

This is not a code issue. It is your default IE settings

To change the "always open" setting:

  1. In Windows Explorer, click on the "Tools" menu, choose "Folder options"
  2. In the window that appears, click on the "File Types" tab, and scroll through the list until you find the file extension you want to change (they're in alphabetical order). For example, if Internet Explorer always tries to open .zip files, scroll through the list until you find the entry for "zip".
  3. Click on the file type, then the "Advanced" button.
  4. Check the "Confirm after download" box, then click OK > Close.

EDIT: If you ask me , instead of making any changes in the code i would add the following text "Internet Explorer users: To download file, "Rightclick" the link and hit "Save target as" to download the file."

EDIT 2: THIS solution will work perfectly for you. Its a solution i just copied from the other answer. Im not trying to pass it off as my own

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"

However you must make sure that you specify the type of file(s) you allow. You have mentioned in your post that you want this for any type of file. This will be an issue.

For ex. If your site has images and if the end user clicks these images then they will be downloaded on his computer instead of opening in a new page. Got the point. So you need to specify the file extensions.

How to export and import environment variables in windows?

You can use RegEdit to export the following two keys:

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

HKEY_CURRENT_USER\Environment

The first set are system/global environment variables; the second set are user-level variables. Edit as needed and then import the .reg files on the new machine.

Clearing an HTML file upload field via JavaScript

Yes, the upload element is protected from direct manipulation in different browsers. However, you could erase the element from the DOM tree and then insert a new one in its place via JavaScript. That would give you the same result.

Something along the lines of:

$('#container-element').html('<input id="upload-file" type="file"/>');

Application not picking up .css file (flask/python)

One more point to add.Along with above upvoted answers, please make sure the below line is added to app.py file:

app = Flask(__name__, static_folder="your path to static")

Otherwise flask will not be able to detect static folder.

Using HTML5 file uploads with AJAX and jQuery

With jQuery (and without FormData API) you can use something like this:

function readFile(file){
   var loader = new FileReader();
   var def = $.Deferred(), promise = def.promise();

   //--- provide classic deferred interface
   loader.onload = function (e) { def.resolve(e.target.result); };
   loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
   loader.onerror = loader.onabort = function (e) { def.reject(e); };
   promise.abort = function () { return loader.abort.apply(loader, arguments); };

   loader.readAsBinaryString(file);

   return promise;
}

function upload(url, data){
    var def = $.Deferred(), promise = def.promise();
    var mul = buildMultipart(data);
    var req = $.ajax({
        url: url,
        data: mul.data,
        processData: false,
        type: "post",
        async: true,
        contentType: "multipart/form-data; boundary="+mul.bound,
        xhr: function() {
            var xhr = jQuery.ajaxSettings.xhr();
            if (xhr.upload) {

                xhr.upload.addEventListener('progress', function(event) {
                    var percent = 0;
                    var position = event.loaded || event.position; /*event.position is deprecated*/
                    var total = event.total;
                    if (event.lengthComputable) {
                        percent = Math.ceil(position / total * 100);
                        def.notify(percent);
                    }                    
                }, false);
            }
            return xhr;
        }
    });
    req.done(function(){ def.resolve.apply(def, arguments); })
       .fail(function(){ def.reject.apply(def, arguments); });

    promise.abort = function(){ return req.abort.apply(req, arguments); }

    return promise;
}

var buildMultipart = function(data){
    var key, crunks = [], bound = false;
    while (!bound) {
        bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
        for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
    }

    for (var key = 0, l = data.length; key < l; key++){
        if (typeof(data[key].value) !== "string") {
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
                "Content-Type: application/octet-stream\r\n"+
                "Content-Transfer-Encoding: binary\r\n\r\n"+
                data[key].value[0]);
        }else{
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
                data[key].value);
        }
    }

    return {
        bound: bound,
        data: crunks.join("\r\n")+"\r\n--"+bound+"--"
    };
};

//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
   var formData = form.find(":input:not('#file')").serializeArray();
   formData.file = [fileData, $file[0].files[0].name];
   upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});

With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})

How to get ERD diagram for an existing database?

Our team use Visual Paradigm to generate ER diagram from database in many of our projects. While we mainly work on MS SQL and Oracle, as I know they also support some other DBMS like PostgreSQL, MySQL, Sybase, DB2 and SQLite.

Steps:

  1. Select Tools > DB > Reverse Database... from the toolbar of Visual Paradigm
  2. Keep the settings as is and click Next Select PostgreSQL as driver and provide the driver file there. You can simply click on the download link there to get the driver.
  3. Enter the hostname, database name, user and password, and then click Next
  4. They will then study your database and lists out the tables in it.
  5. Select the table to form an ERD and continue, and that's it. An ERD will be generated with the tables you selected presented.

BTW they also support generating and updating database schema from ERD.

Hope this helps. :-)

More information about generating ERD from PostgreSQL database

How can I parse a local JSON file from assets folder into a ListView?

As Faizan describes in their answer here:

First of all read the Json File from your assests file using below code.

and then you can simply read this string return by this function as

public String loadJSONFromAsset() {
    String json = null;
    try {
        InputStream is = getActivity().getAssets().open("yourfilename.json");
        int size = is.available();
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();
        json = new String(buffer, "UTF-8");
    } catch (IOException ex) {
        ex.printStackTrace();
        return null;
    }
    return json;
}

and use this method like that

    try {
        JSONObject obj = new JSONObject(loadJSONFromAsset());
        JSONArray m_jArry = obj.getJSONArray("formules");
        ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>();
        HashMap<String, String> m_li;

        for (int i = 0; i < m_jArry.length(); i++) {
            JSONObject jo_inside = m_jArry.getJSONObject(i);
            Log.d("Details-->", jo_inside.getString("formule"));
            String formula_value = jo_inside.getString("formule");
            String url_value = jo_inside.getString("url");

            //Add your values in your `ArrayList` as below:
            m_li = new HashMap<String, String>();
            m_li.put("formule", formula_value);
            m_li.put("url", url_value);

            formList.add(m_li);
        }
    } catch (JSONException e) {
        e.printStackTrace();
    }

For further details regarding JSON Read HERE

Error: Local workspace file ('angular.json') could not be found

Well, I faced the same issue as soon as I updated my angular cli version.

Earlier I was using 1.7.4 and just now I upgraded it to angular cli 6.0.8.

To update Angular Cli global:

npm uninstall -g angular-cli
npm cache clean 
npm install -g @angular/cli@latest

To update Angular Cli dev:

npm uninstall --save-dev angular-cli
npm install --save-dev @angular/cli@latest
npm install

To fix audit issues after npm install:

npm audit fix

To fix the issue related to "angular.json":

ng update @angular/cli --migrate-only --from=1.7.4

remove all special characters in java

You can read the lines and replace all special characters safely this way.
Keep in mind that if you use \\W you will not replace underscores.

Scanner scan = new Scanner(System.in);

while(scan.hasNextLine()){
    System.out.println(scan.nextLine().replaceAll("[^a-zA-Z0-9]", ""));
}

How can I increase the size of a bootstrap button?

bootstrap comes with clas btn-lg http://getbootstrap.com/components/#btn-dropdowns-sizing

<div class="btn btn-default btn-block">
  Active
</div>

but if you want to have the button of the width of your column / container add btn-block

<div class="btn btn-default btn-lg">
      Active
    </div>

However this will expand to 100% so make surt ethat you will wrap your button in certain amount of columns e.g. then you know its always stays 3 columns until xs screen

<div class="col-sm-3">
             <div class="btn btn-default btn-block">
          Active
            </div>
        </div>

How to change XAMPP apache server port?

Have you tried to access your page by typing "http://localhost:8012" (after restarting the apache)?

jQuery: how do I animate a div rotation?

As of now you still can't animate rotations with jQuery, but you can with CSS3 animations, then simply add and remove the class with jQuery to make the animation occur.

JSFiddle demo


HTML

<img src="http://puu.sh/csDxF/2246d616d8.png" width="30" height="30"/>

CSS3

img {
-webkit-transform: rotate(-90deg);
-moz-transform: rotate(-90deg);
-o-transform: rotate(-90deg);
-ms-transform: rotate(-90deg);
transform: rotate(-90deg);
transition-duration:0.4s;
}

.rotate {
-webkit-transform: rotate(0deg);
-moz-transform: rotate(0deg);
-o-transform: rotate(0deg);
-ms-transform: rotate(0deg);
transform: rotate(0deg);
transition-duration:0.4s;
}

jQuery

$(document).ready(function() {
    $("img").mouseenter(function() {
        $(this).addClass("rotate");
    });
    $("img").mouseleave(function() {
        $(this).removeClass("rotate");
    });
});

Convert timestamp in milliseconds to string formatted time in Java

long millis = durationInMillis % 1000;
long second = (durationInMillis / 1000) % 60;
long minute = (durationInMillis / (1000 * 60)) % 60;
long hour = (durationInMillis / (1000 * 60 * 60)) % 24;

String time = String.format("%02d:%02d:%02d.%d", hour, minute, second, millis);

How do I do a case-insensitive string comparison?

The usual approach is to uppercase the strings or lower case them for the lookups and comparisons. For example:

>>> "hello".upper() == "HELLO".upper()
True
>>> 

Serialize an object to XML

The following function can be copied to any object to add an XML save function using the System.Xml namespace.

/// <summary>
/// Saves to an xml file
/// </summary>
/// <param name="FileName">File path of the new xml file</param>
public void Save(string FileName)
{
    using (var writer = new System.IO.StreamWriter(FileName))
    {
        var serializer = new XmlSerializer(this.GetType());
        serializer.Serialize(writer, this);
        writer.Flush();
    }
}

To create the object from the saved file, add the following function and replace [ObjectType] with the object type to be created.

/// <summary>
/// Load an object from an xml file
/// </summary>
/// <param name="FileName">Xml file name</param>
/// <returns>The object created from the xml file</returns>
public static [ObjectType] Load(string FileName)
{
    using (var stream = System.IO.File.OpenRead(FileName))
    {
        var serializer = new XmlSerializer(typeof([ObjectType]));
        return serializer.Deserialize(stream) as [ObjectType];
    }
}

Illegal mix of collations (utf8_unicode_ci,IMPLICIT) and (utf8_general_ci,IMPLICIT) for operation '='

This happens where a column is explicitly set to a different collation or the default collation is different in the table queried.

if you have many tables you want to change collation on run this query:

select concat('ALTER TABLE ', t.table_name , ' CONVERT TO CHARACTER 
SET utf8 COLLATE utf8_unicode_ci;') from (SELECT table_name FROM 
information_schema.tables where table_schema='SCHRMA') t;

this will output the queries needed to convert all the tables to use the correct collation per column

error LNK2001: unresolved external symbol (C++)

That means that the definition of your function is not present in your program. You forgot to add that one.cpp to your program.

What "to add" means in this case depends on your build environment and its terminology. In MSVC (since you are apparently use MSVC) you'd have to add one.cpp to the project.

In more practical terms, applicable to all typical build methodologies, when you link you program, the object file created form one.cpp is missing.

Console.log(); How to & Debugging javascript

Breakpoints and especially conditional breakpoints are your friends.

Also you can write small assert like function which will check values and throw exceptions if needed in debug version of site (some variable is set to true or url has some parameter)

mongodb group values by multiple fields

TLDR Summary

In modern MongoDB releases you can brute force this with $slice just off the basic aggregation result. For "large" results, run parallel queries instead for each grouping ( a demonstration listing is at the end of the answer ), or wait for SERVER-9377 to resolve, which would allow a "limit" to the number of items to $push to an array.

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 },
    { "$project": {
        "books": { "$slice": [ "$books", 2 ] },
        "count": 1
    }}
])

MongoDB 3.6 Preview

Still not resolving SERVER-9377, but in this release $lookup allows a new "non-correlated" option which takes an "pipeline" expression as an argument instead of the "localFields" and "foreignFields" options. This then allows a "self-join" with another pipeline expression, in which we can apply $limit in order to return the "top-n" results.

db.books.aggregate([
  { "$group": {
    "_id": "$addr",
    "count": { "$sum": 1 }
  }},
  { "$sort": { "count": -1 } },
  { "$limit": 2 },
  { "$lookup": {
    "from": "books",
    "let": {
      "addr": "$_id"
    },
    "pipeline": [
      { "$match": { 
        "$expr": { "$eq": [ "$addr", "$$addr"] }
      }},
      { "$group": {
        "_id": "$book",
        "count": { "$sum": 1 }
      }},
      { "$sort": { "count": -1  } },
      { "$limit": 2 }
    ],
    "as": "books"
  }}
])

The other addition here is of course the ability to interpolate the variable through $expr using $match to select the matching items in the "join", but the general premise is a "pipeline within a pipeline" where the inner content can be filtered by matches from the parent. Since they are both "pipelines" themselves we can $limit each result separately.

This would be the next best option to running parallel queries, and actually would be better if the $match were allowed and able to use an index in the "sub-pipeline" processing. So which is does not use the "limit to $push" as the referenced issue asks, it actually delivers something that should work better.


Original Content

You seem have stumbled upon the top "N" problem. In a way your problem is fairly easy to solve though not with the exact limiting that you ask for:

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 }
])

Now that will give you a result like this:

{
    "result" : [
            {
                    "_id" : "address1",
                    "books" : [
                            {
                                    "book" : "book4",
                                    "count" : 1
                            },
                            {
                                    "book" : "book5",
                                    "count" : 1
                            },
                            {
                                    "book" : "book1",
                                    "count" : 3
                            }
                    ],
                    "count" : 5
            },
            {
                    "_id" : "address2",
                    "books" : [
                            {
                                    "book" : "book5",
                                    "count" : 1
                            },
                            {
                                    "book" : "book1",
                                    "count" : 2
                            }
                    ],
                    "count" : 3
            }
    ],
    "ok" : 1
}

So this differs from what you are asking in that, while we do get the top results for the address values the underlying "books" selection is not limited to only a required amount of results.

This turns out to be very difficult to do, but it can be done though the complexity just increases with the number of items you need to match. To keep it simple we can keep this at 2 matches at most:

db.books.aggregate([
    { "$group": {
        "_id": {
            "addr": "$addr",
            "book": "$book"
        },
        "bookCount": { "$sum": 1 }
    }},
    { "$group": {
        "_id": "$_id.addr",
        "books": { 
            "$push": { 
                "book": "$_id.book",
                "count": "$bookCount"
            },
        },
        "count": { "$sum": "$bookCount" }
    }},
    { "$sort": { "count": -1 } },
    { "$limit": 2 },
    { "$unwind": "$books" },
    { "$sort": { "count": 1, "books.count": -1 } },
    { "$group": {
        "_id": "$_id",
        "books": { "$push": "$books" },
        "count": { "$first": "$count" }
    }},
    { "$project": {
        "_id": {
            "_id": "$_id",
            "books": "$books",
            "count": "$count"
        },
        "newBooks": "$books"
    }},
    { "$unwind": "$newBooks" },
    { "$group": {
      "_id": "$_id",
      "num1": { "$first": "$newBooks" }
    }},
    { "$project": {
        "_id": "$_id",
        "newBooks": "$_id.books",
        "num1": 1
    }},
    { "$unwind": "$newBooks" },
    { "$project": {
        "_id": "$_id",
        "num1": 1,
        "newBooks": 1,
        "seen": { "$eq": [
            "$num1",
            "$newBooks"
        ]}
    }},
    { "$match": { "seen": false } },
    { "$group":{
        "_id": "$_id._id",
        "num1": { "$first": "$num1" },
        "num2": { "$first": "$newBooks" },
        "count": { "$first": "$_id.count" }
    }},
    { "$project": {
        "num1": 1,
        "num2": 1,
        "count": 1,
        "type": { "$cond": [ 1, [true,false],0 ] }
    }},
    { "$unwind": "$type" },
    { "$project": {
        "books": { "$cond": [
            "$type",
            "$num1",
            "$num2"
        ]},
        "count": 1
    }},
    { "$group": {
        "_id": "$_id",
        "count": { "$first": "$count" },
        "books": { "$push": "$books" }
    }},
    { "$sort": { "count": -1 } }
])

So that will actually give you the top 2 "books" from the top two "address" entries.

But for my money, stay with the first form and then simply "slice" the elements of the array that are returned to take the first "N" elements.


Demonstration Code

The demonstration code is appropriate for usage with current LTS versions of NodeJS from v8.x and v10.x releases. That's mostly for the async/await syntax, but there is nothing really within the general flow that has any such restriction, and adapts with little alteration to plain promises or even back to plain callback implementation.

index.js

const { MongoClient } = require('mongodb');
const fs = require('mz/fs');

const uri = 'mongodb://localhost:27017';

const log = data => console.log(JSON.stringify(data, undefined, 2));

(async function() {

  try {
    const client = await MongoClient.connect(uri);

    const db = client.db('bookDemo');
    const books = db.collection('books');

    let { version } = await db.command({ buildInfo: 1 });
    version = parseFloat(version.match(new RegExp(/(?:(?!-).)*/))[0]);

    // Clear and load books
    await books.deleteMany({});

    await books.insertMany(
      (await fs.readFile('books.json'))
        .toString()
        .replace(/\n$/,"")
        .split("\n")
        .map(JSON.parse)
    );

    if ( version >= 3.6 ) {

    // Non-correlated pipeline with limits
      let result = await books.aggregate([
        { "$group": {
          "_id": "$addr",
          "count": { "$sum": 1 }
        }},
        { "$sort": { "count": -1 } },
        { "$limit": 2 },
        { "$lookup": {
          "from": "books",
          "as": "books",
          "let": { "addr": "$_id" },
          "pipeline": [
            { "$match": {
              "$expr": { "$eq": [ "$addr", "$$addr" ] }
            }},
            { "$group": {
              "_id": "$book",
              "count": { "$sum": 1 },
            }},
            { "$sort": { "count": -1 } },
            { "$limit": 2 }
          ]
        }}
      ]).toArray();

      log({ result });
    }

    // Serial result procesing with parallel fetch

    // First get top addr items
    let topaddr = await books.aggregate([
      { "$group": {
        "_id": "$addr",
        "count": { "$sum": 1 }
      }},
      { "$sort": { "count": -1 } },
      { "$limit": 2 }
    ]).toArray();

    // Run parallel top books for each addr
    let topbooks = await Promise.all(
      topaddr.map(({ _id: addr }) =>
        books.aggregate([
          { "$match": { addr } },
          { "$group": {
            "_id": "$book",
            "count": { "$sum": 1 }
          }},
          { "$sort": { "count": -1 } },
          { "$limit": 2 }
        ]).toArray()
      )
    );

    // Merge output
    topaddr = topaddr.map((d,i) => ({ ...d, books: topbooks[i] }));
    log({ topaddr });

    client.close();

  } catch(e) {
    console.error(e)
  } finally {
    process.exit()
  }

})()

books.json

{ "addr": "address1",  "book": "book1"  }
{ "addr": "address2",  "book": "book1"  }
{ "addr": "address1",  "book": "book5"  }
{ "addr": "address3",  "book": "book9"  }
{ "addr": "address2",  "book": "book5"  }
{ "addr": "address2",  "book": "book1"  }
{ "addr": "address1",  "book": "book1"  }
{ "addr": "address15", "book": "book1"  }
{ "addr": "address9",  "book": "book99" }
{ "addr": "address90", "book": "book33" }
{ "addr": "address4",  "book": "book3"  }
{ "addr": "address5",  "book": "book1"  }
{ "addr": "address77", "book": "book11" }
{ "addr": "address1",  "book": "book1"  }

Hide strange unwanted Xcode logs

OS_ACTIVITY_MODE didn't work for me (it may have been because I typo'd disable as disabled, but isn't that more natural?!?), or at least didn't prevent a great deal of messages. So here's the real deal with the environment variables.

https://llvm.org/svn/llvm-project/lldb/trunk/source/Plugins/Platform/MacOSX/PlatformDarwin.cpp

lldb_private::Error
PlatformDarwin::LaunchProcess(lldb_private::ProcessLaunchInfo &launch_info) {
  // Starting in Fall 2016 OSes, NSLog messages only get mirrored to stderr
  // if the OS_ACTIVITY_DT_MODE environment variable is set.  (It doesn't
  // require any specific value; rather, it just needs to exist).
  // We will set it here as long as the IDE_DISABLED_OS_ACTIVITY_DT_MODE flag
  // is not set.  Xcode makes use of IDE_DISABLED_OS_ACTIVITY_DT_MODE to tell
  // LLDB *not* to muck with the OS_ACTIVITY_DT_MODE flag when they
  // specifically want it unset.
  const char *disable_env_var = "IDE_DISABLED_OS_ACTIVITY_DT_MODE";
  auto &env_vars = launch_info.GetEnvironmentEntries();
  if (!env_vars.ContainsEnvironmentVariable(disable_env_var)) {
    // We want to make sure that OS_ACTIVITY_DT_MODE is set so that
    // we get os_log and NSLog messages mirrored to the target process
    // stderr.
    if (!env_vars.ContainsEnvironmentVariable("OS_ACTIVITY_DT_MODE"))
      env_vars.AppendArgument(llvm::StringRef("OS_ACTIVITY_DT_MODE=enable"));
  }

  // Let our parent class do the real launching.
  return PlatformPOSIX::LaunchProcess(launch_info);
}

So setting OS_ACTIVITY_DT_MODE to "NO" in the environment variables (GUI method explained in Schemes screenshot in main answer) makes it work for me.

As far as NSLog being the dumping ground for system messages, errors, and your own debugging: a real logging approach is probably called for anyway, e.g. https://github.com/fpillet/NSLogger .

OR

Drink the new Kool-Aid: http://asciiwwdc.com/2016/sessions/721 https://developer.apple.com/videos/play/wwdc2016/721/ It's not surprising that there are some hitches after overhauling the entire logging API.

ADDENDUM

Anyway, NSLog is just a shim:

https://developer.apple.com/library/content/releasenotes/Miscellaneous/RN-Foundation-OSX10.12/

NSLog / CFLog

NSLog is now just a shim to os_log in most circumstances.

Only makes sense now to quote the source for the other env variable. Quite a disparate place, this time from Apple internals. Not sure why they are overlapping. [Incorrect comment about NSLog removed]

[Edited 22 Sep]: I wonder what "release" and "stream" do differently than "debug". Not enough source.

https://github.com/macosforge/libdispatch/blob/8e63547ea4e5abbfe55c0c3064181c4950a791d3/src/voucher.c

e = getenv("OS_ACTIVITY_MODE");
if (e) {
    if (strcmp(e, "release") == 0) {
        mode = voucher_activity_mode_release;
    } else if (strcmp(e, "debug") == 0) {
        mode = voucher_activity_mode_debug;
    } else if (strcmp(e, "stream") == 0) {
        mode = voucher_activity_mode_stream;
    } else if (strcmp(e, "disable") == 0) {
        mode = voucher_activity_mode_disable;
    }
}

c# foreach (property in object)... Is there a simple way of doing this?

I couldn't get any of the above ways to work, but this worked. The username and password for DirectoryEntry are optional.

   private List<string> getAnyDirectoryEntryPropertyValue(string userPrincipalName, string propertyToSearchFor)
    {
        List<string> returnValue = new List<string>();
        try
        {
            int index = userPrincipalName.IndexOf("@");
            string originatingServer = userPrincipalName.Remove(0, index + 1);
            string path = "LDAP://" + originatingServer; //+ @"/" + distinguishedName;
            DirectoryEntry objRootDSE = new DirectoryEntry(path, PSUsername, PSPassword);
            var objSearcher = new System.DirectoryServices.DirectorySearcher(objRootDSE);
            objSearcher.Filter = string.Format("(&(UserPrincipalName={0}))", userPrincipalName);
            SearchResultCollection properties = objSearcher.FindAll();

            ResultPropertyValueCollection resPropertyCollection = properties[0].Properties[propertyToSearchFor];
            foreach (string resProperty in resPropertyCollection)
            {
                returnValue.Add(resProperty);
            }
        }
        catch (Exception ex)
        {
            returnValue.Add(ex.Message);
            throw;
        }

        return returnValue;
    }

Add text to textarea - Jquery

Just append() the text nodes:

$('#replyBox').append(quote); 

http://jsfiddle.net/nQErc/

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

See some of the answers to my similar question why-cant-i-push-from-a-shallow-clone and the link to the recent thread on the git list.

Ultimately, the 'depth' measurement isn't consistent between repos, because they measure from their individual HEADs, rather than (a) your Head, or (b) the commit(s) you cloned/fetched, or (c) something else you had in mind.

The hard bit is getting one's Use Case right (i.e. self-consistent), so that distributed, and therefore probably divergent repos will still work happily together.

It does look like the checkout --orphan is the right 'set-up' stage, but still lacks clean (i.e. a simple understandable one line command) guidance on the "clone" step. Rather it looks like you have to init a repo, set up a remote tracking branch (you do want the one branch only?), and then fetch that single branch, which feels long winded with more opportunity for mistakes.

Edit: For the 'clone' step see this answer

How to update Android Studio automatically?

For this task, I recommend using Android Studio IDE and choose the automatic installation program, and not the compressed file.

  1. On the top menu, select Help -> Check for Update...
  2. Upon the updates dialog below, select Updates link to configure your IDE settings.

Platform and Plugin Updates

  1. For checking updates, my suggestion is to select the Dev channel. I

don't recommend Beta or Canary

channel which is the unstable version and they are not automatic installation, instead a zip file is provided in that case.

Updates dialog

  1. When finished with the configuration, select Update and Restart for downloading the installation EXE.
  2. Run the installation.

Warning: Among different version of Android Studio, the steps may be different. But hopefully you get the idea, as I try to be clear on my intentions.

Extra info: If you want, check for Android Studio updates @ Android Tools Project Site - Recent Builds. This web page seems to be more accurate than other Android pages about tool updates.

How come I can't remove the blue textarea border in Twitter Bootstrap?

Work out computed styles via an inspector

For future reference you can work out computed styles via an inspector

ASP.NET MVC Html.ValidationSummary(true) does not display model errors

ADD it in the lowermost part og your View:

@section Scripts { @Scripts.Render("~/bundles/jqueryval") }

Edit In Place Content Editing

Since this is a common piece of functionality it's a good idea to write a directive for this. In fact, someone already did that and open sourced it. I used editablespan library in one of my projects and it worked perfectly, highly recommended.

How to get a complete list of ticker symbols from Yahoo Finance?

I may be able to help with a list of ticker symbols for (U.S. and non-U.S.) stocks and for ETFs.

Yahoo provides an Earnings Calendar that lists all the stocks that announce earnings for a given day. This includes non-US stocks.

For example, here is today's: http://biz.yahoo.com/research/earncal/20120710.html

the last part of the URL is the date (in YYYYMMDD format) for which you want the Earnings Calendar. You can loop through several days and scrape the Symbols of all stocks that reported earnings on those days.

There is no guarantee that yahoo has data for all stocks that report earnings, especially since some stocks no longer exist (bankruptcy, acquisition, etc.), but this is probably a decent starting point.

If you are familiar with R, you can use the qmao package to do this. (See this post) if you have trouble installing it.

ec <- getEarningsCalendar(from="2011-01-01", to="2012-07-01") #this may take a while
s <- unique(ec$Symbol)
length(s)
#[1] 12223
head(s, 20) #look at the first 20 Symbols
# [1] "CVGW"    "ANGO"    "CAMP"    "LNDC"    "MOS"     "NEOG"    "SONC"   
# [8] "TISI"    "SHLM"    "FDO"     "FC"      "JPST.PK" "RECN"    "RELL"   
#[15] "RT"      "UNF"     "WOR"     "WSCI"    "ZEP"     "AEHR"   

This will not include any ETFs, futures, options, bonds, forex or mutual funds.

You can get a list of ETFs from yahoo here: http://finance.yahoo.com/etf/browser/mkt That only shows the first 20. You need the URL of the "Show All" link at the bottom of that page. You can scrape the page to find out how many ETFs there are, then construct a URL.

L <- readLines("http://finance.yahoo.com/etf/browser/mkt")
# Sorry for the ugly regex
n <- gsub("^(\\w+)\\s?(.*)$", "\\1", 
          gsub("(.*)(Showing 1 - 20 of )(.*)", "\\3",  
               L[grep("Showing 1 - 20", L)]))
URL <- paste0("http://finance.yahoo.com/etf/browser/mkt?c=0&k=5&f=0&o=d&cs=1&ce=", n)
#http://finance.yahoo.com/etf/browser/mkt?c=0&k=5&f=0&o=d&cs=1&ce=1442

Now, you can extract the Tickers from the table on that page

library(XML)
tbl <- readHTMLTable(URL, stringsAsFactors=FALSE)
dat <- tbl[[tail(grep("Ticker", tbl), 1)]][-1, ]
colnames(dat) <- dat[1, ]
dat <- dat[-1, ]
etfs <- dat$Ticker # All ETF tickers from yahoo
length(etfs)
#[1] 1442
head(etfs)
#[1] "DGAZ" "TAGS" "GASX" "KOLD" "DWTI" "RTSA"

That's about all the help I can offer, but you could do something similar to get some of the futures they offer by scraping these pages (These are only U.S. futures)

http://finance.yahoo.com/indices?e=futures, http://finance.yahoo.com/futures?t=energy, http://finance.yahoo.com/futures?t=metals, http://finance.yahoo.com/futures?t=grains, http://finance.yahoo.com/futures?t=livestock, http://finance.yahoo.com/futures?t=softs, http://finance.yahoo.com/futures?t=indices,

And, for U.S. and non-U.S. indices, you could scrape these pages

http://finance.yahoo.com/intlindices?e=americas, http://finance.yahoo.com/intlindices?e=asia, http://finance.yahoo.com/intlindices?e=europe, http://finance.yahoo.com/intlindices?e=africa, http://finance.yahoo.com/indices?e=dow_jones, http://finance.yahoo.com/indices?e=new_york, http://finance.yahoo.com/indices?e=nasdaq, http://finance.yahoo.com/indices?e=sp, http://finance.yahoo.com/indices?e=other, http://finance.yahoo.com/indices?e=treasury, http://finance.yahoo.com/indices?e=commodities

Digital Certificate: How to import .cer file in to .truststore file using?

# Copy the certificate into the directory Java_home\Jre\Lib\Security
# Change your directory to Java_home\Jre\Lib\Security>
# Import the certificate to a trust store.

keytool -import -alias ca -file somecert.cer -keystore cacerts -storepass changeit [Return]

Trust this certificate: [Yes]

changeit is the default truststore password

Configure cron job to run every 15 minutes on Jenkins

Your syntax is slightly wrong. Say:

*/15 * * * * command
  |
  |--> `*/15` would imply every 15 minutes.

* indicates that the cron expression matches for all values of the field.

/ describes increments of ranges.

center aligning a fixed position div

Center it horizontally:

display: fixed;
top: 0; 
left: 0;
transform: translate(calc(50vw - 50%));

Center it horizontally and vertically:

display: fixed;
top: 0; 
left: 0;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));

No side effect: It will not limit element's width when using margins in flexbox

Call a function after previous function is complete

Try this :

function method1(){
   // some code

}

function method2(){
   // some code
}

$.ajax({
   url:method1(),
   success:function(){
   method2();
}
})

How to set bot's status

.setGame is discontinued. Use:

client.user.setActivity("Game"); 

To set a playing game status.

As an addition, if you were using an earlier version of discord.js, try this:

client.user.setGame("Game");

In newer versions of discord.js, this is deprecated.

How to display a loading screen while site content loads

You said you didn't want to do this in AJAX. While AJAX is great for this, there is a way to show one DIV while waiting for the entire <body> to load. It goes something like this:

<html>
  <head>
    <style media="screen" type="text/css">
      .layer1_class { position: absolute; z-index: 1; top: 100px; left: 0px; visibility: visible; }
      .layer2_class { position: absolute; z-index: 2; top: 10px; left: 10px; visibility: hidden }
    </style>
    <script>
      function downLoad(){
        if (document.all){
            document.all["layer1"].style.visibility="hidden";
            document.all["layer2"].style.visibility="visible";
        } else if (document.getElementById){
            node = document.getElementById("layer1").style.visibility='hidden';
            node = document.getElementById("layer2").style.visibility='visible';
        }
      }
    </script>
  </head>
  <body onload="downLoad()">
    <div id="layer1" class="layer1_class">
      <table width="100%">
        <tr>
          <td align="center"><strong><em>Please wait while this page is loading...</em></strong></p></td>
        </tr>
      </table>
    </div>
    <div id="layer2" class="layer2_class">
        <script type="text/javascript">
                alert('Just holding things up here.  While you are reading this, the body of the page is not loading and the onload event is being delayed');
        </script>
        Final content.      
    </div>
  </body>
</html>

The onload event won't fire until all of the page has loaded. So the layer2 <DIV> won't be displayed until the page has finished loading, after which onload will fire.

How to find a min/max with Ruby

In addition to the provided answers, if you want to convert Enumerable#max into a max method that can call a variable number or arguments, like in some other programming languages, you could write:

def max(*values)
 values.max
end

Output:

max(7, 1234, 9, -78, 156)
=> 1234

This abuses the properties of the splat operator to create an array object containing all the arguments provided, or an empty array object if no arguments were provided. In the latter case, the method will return nil, since calling Enumerable#max on an empty array object returns nil.

If you want to define this method on the Math module, this should do the trick:

module Math
 def self.max(*values)
  values.max
 end
end

Note that Enumerable.max is, at least, two times slower compared to the ternary operator (?:). See Dave Morse's answer for a simpler and faster method.

Passing multiple variables to another page in url

Your first variable declartion must start with a ? while any additional must be concatenated with a &

Display a view from another controller in ASP.NET MVC

Yes, you can. Return an Action like this :

return RedirectToAction("View", "Name of Controller");

An example:

return RedirectToAction("Details/" + id.ToString(), "FullTimeEmployees");

This approach will call the GET method

Also you could pass values to action like this:

return RedirectToAction("Details/" + id.ToString(), "FullTimeEmployees", new {id = id.ToString(), viewtype = "extended" });

Powershell: How can I stop errors from being displayed in a script?

You're way off track here.

You already have a nice, big error message. Why on Earth would you want to write code that checks $? explicitly after every single command? This is enormously cumbersome and error prone. The correct solution is stop checking $?.

Instead, use PowerShell's built in mechanism to blow up for you. You enable it by setting the error preference to the highest level:

$ErrorActionPreference = 'Stop'

I put this at the top of every single script I ever write, and now I don't have to check $?. This makes my code vastly simpler and more reliable.

If you run into situations where you really need to disable this behavior, you can either catch the error or pass a setting to a particular function using the common -ErrorAction. In your case, you probably want your process to stop on the first error, catch the error, and then log it.

Do note that this doesn't handle the case when external executables fail (exit code nonzero, conventionally), so you do still need to check $LASTEXITCODE if you invoke any. Despite this limitation, the setting still saves a lot of code and effort.

Additional reliability

You might also want to consider using strict mode:

Set-StrictMode -Version Latest

This prevents PowerShell from silently proceeding when you use a non-existent variable and in other weird situations. (See the -Version parameter for details about what it restricts.)

Combining these two settings makes PowerShell much more of fail-fast language, which makes programming in it vastly easier.

Authentication versus Authorization

As Authentication vs Authorization puts it:

Authentication is the mechanism whereby systems may securely identify their users. Authentication systems provide an answers to the questions:

  • Who is the user?
  • Is the user really who he/she represents himself to be?

Authorization, by contrast, is the mechanism by which a system determines what level of access a particular authenticated user should have to secured resources controlled by the system. For example, a database management system might be designed so as to provide certain specified individuals with the ability to retrieve information from a database but not the ability to change data stored in the datbase, while giving other individuals the ability to change data. Authorization systems provide answers to the questions:

  • Is user X authorized to access resource R?
  • Is user X authorized to perform operation P?
  • Is user X authorized to perform operation P on resource R?

See also:

How correctly produce JSON by RESTful web service?

Use this annotation

@RequestMapping(value = "/url", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON})

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

Instances of the String constructor have a .search() method which accepts a RegExp and returns the index of the first match.

To start the search from a particular position (faking the second parameter of .indexOf()) you can slice off the first i characters:

str.slice(i).search(/re/)

But this will get the index in the shorter string (after the first part was sliced off) so you'll want to then add the length of the chopped off part (i) to the returned index if it wasn't -1. This will give you the index in the original string:

function regexIndexOf(text, re, i) {
    var indexInSuffix = text.slice(i).search(re);
    return indexInSuffix < 0 ? indexInSuffix : indexInSuffix + i;
}

What are the differences between virtual memory and physical memory?

I am shamelessly copying the excerpts from man page of top

VIRT -- Virtual Image (kb) The total amount of virtual memory used by the task. It includes all code, data and shared libraries plus pages that have been swapped out and pages that have been mapped but not used.

SWAP -- Swapped size (kb) Memory that is not resident but is present in a task. This is memory that has been swapped out but could include additional non- resident memory. This column is calculated by subtracting physical memory from virtual memory

log4j logging hierarchy order

Use the force, read the source (excerpt from the Priority and Level class compiled, TRACE level was introduced in version 1.2.12):

public final static int OFF_INT = Integer.MAX_VALUE;
public final static int FATAL_INT = 50000;
public final static int ERROR_INT = 40000;
public final static int WARN_INT  = 30000;
public final static int INFO_INT  = 20000;
public final static int DEBUG_INT = 10000;
public static final int TRACE_INT = 5000; 
public final static int ALL_INT = Integer.MIN_VALUE; 

or the log4j API for the Level class, which makes it quite clear.

When the library decides whether to print a certain statement or not, it computes the effective level of the responsible Logger object (based on configuration) and compares it with the LogEvent's level (depends on which method was used in the code – trace/debug/.../fatal). If LogEvent's level is greater or equal to the Logger's level, the LogEvent is sent to appender(s) – "printed". At the core, it all boils down to an integer comparison and this is where these constants come to action.

What is the difference between git clone and checkout?

Simply git checkout have 2 uses

  1. Switching between existing local branches like git checkout <existing_local_branch_name>
  2. Create a new branch from current branch using flag -b. Suppose if you are at master branch then git checkout -b <new_feature_branch_name> will create a new branch with the contents of master and switch to newly created branch

You can find more options at the official site

Speech input for visually impaired users without the need to tap the screen

The only way to get the iOS dictation is to sign up yourself through Nuance: http://dragonmobile.nuancemobiledeveloper.com/ - it's expensive, because it's the best. Presumably, Apple's contract prevents them from exposing an API.

The built in iOS accessibility features allow immobilized users to access dictation (and other keyboard buttons) through tools like VoiceOver and Assistive Touch. It may not be worth reinventing this if your users might be familiar with these tools.

Difference between web server, web container and application server

Web Server: It provides HTTP Request and HTTP response. It handles request from client only through HTTP protocol. It contains Web Container. Web Application mostly deployed on web Server. EX: Servlet JSP

Web Container: it maintains the life cycle for Servlet Object. Calls the service method for that servlet object. pass the HttpServletRequest and HttpServletResponse Object

Application Server: It holds big Enterprise application having big business logic. It is Heavy Weight or it holds Heavy weight Applications. Ex: EJB

How do you copy a record in a SQL table but swap out the unique id of the new row?

I'm guessing you're trying to avoid writing out all the column names. If you're using SQL Management Studio you can easily right click on the table and Script As Insert.. then you can mess around with that output to create your query.

how to save canvas as png image?

To accomodate all three points:

  • button
  • save the image as a png file
  • open up the save, open, close dialog box

The file dialog is a setting in the browser.

For the button/save part assign the following function, boiled down from other answers, to your buttons onclick:

function DownloadCanvasAsImage(){
    let downloadLink = document.createElement('a');
    downloadLink.setAttribute('download', 'CanvasAsImage.png');
    let canvas = document.getElementById('myCanvas');
    let dataURL = canvas.toDataURL('image/png');
    let url = dataURL.replace(/^data:image\/png/,'data:application/octet-stream');
    downloadLink.setAttribute('href', url);
    downloadLink.click();
}

Example on Codepen

Another, somewhat cleaner, approach is using Canvas.toBlob():

function DownloadCanvasAsImage(){
    let downloadLink = document.createElement('a');
    downloadLink.setAttribute('download', 'CanvasAsImage.png');
    let canvas = document.getElementById('myCanvas');
    canvas.toBlob(function(blob) {
      let url = URL.createObjectURL(blob);
      downloadLink.setAttribute('href', url);
      downloadLink.click();
    });
}

Example on Codepen

Neither solution is 100% cross browser compatible, so check the client

Entity Framework - Code First - Can't Store List<String>

I Know this is a old question, and Pawel has given the correct answer, I just wanted to show a code example of how to do some string processing, and avoid an extra class for the list of a primitive type.

public class Test
{
    public Test()
    {
        _strings = new List<string>
        {
            "test",
            "test2",
            "test3",
            "test4"
        };
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    private List<String> _strings { get; set; }

    public List<string> Strings
    {
        get { return _strings; }
        set { _strings = value; }
    }

    [Required]
    public string StringsAsString
    {
        get { return String.Join(',', _strings); }
        set { _strings = value.Split(',').ToList(); }
    }
}

How to uncheck a checkbox in pure JavaScript?

There is another way to do this:

//elem - get the checkbox element and then
elem.setAttribute('checked', 'checked'); //check
elem.removeAttribute('checked'); //uncheck

How to send a simple string between two programs using pipes?

Here's a sample:

int main()
{
    char buff[1024] = {0};
    FILE* cvt;
    int status;
    /* Launch converter and open a pipe through which the parent will write to it */
    cvt = popen("converter", "w");
    if (!cvt)
    {
        printf("couldn't open a pipe; quitting\n");
        exit(1)
    }
    printf("enter Fahrenheit degrees: " );
    fgets(buff, sizeof (buff), stdin); /*read user's input */
    /* Send expression to converter for evaluation */
    fprintf(cvt, "%s\n", buff);
    fflush(cvt);
    /* Close pipe to converter and wait for it to exit */
    status=pclose(cvt);
    /* Check the exit status of pclose() */
    if (!WIFEXITED(status))
        printf("error on closing the pipe\n");
    return 0;
}

The important steps in this program are:

  1. The popen() call which establishes the association between a child process and a pipe in the parent.
  2. The fprintf() call that uses the pipe as an ordinary file to write to the child process's stdin or read from its stdout.
  3. The pclose() call that closes the pipe and causes the child process to terminate.

How do I add PHP code/file to HTML(.html) files?

You can't run PHP in .html files because the server does not recognize that as a valid PHP extension unless you tell it to. To do this you need to create a .htaccess file in your root web directory and add this line to it:

AddType application/x-httpd-php .htm .html

This will tell Apache to process files with a .htm or .html file extension as PHP files.

Polymorphism vs Overriding vs Overloading

what is polymorphism?

From java tutorial

The dictionary definition of polymorphism refers to a principle in biology in which an organism or species can have many different forms or stages. This principle can also be applied to object-oriented programming and languages like the Java language. Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class.

By considering the examples and definition, overriding should be accepted answer.

Regarding your second query:

IF you had a abstract base class that defined a method with no implementation, and you defined that method in the sub class, is that still overridding?

It should be called overriding.

Have a look at this example to understand different types of overriding.

  1. Base class provides no implementation and sub-class has to override complete method - (abstract)
  2. Base class provides default implementation and sub-class can change the behaviour
  3. Sub-class adds extension to base class implementation by calling super.methodName() as first statement
  4. Base class defines structure of the algorithm (Template method) and sub-class will override a part of algorithm

code snippet:

import java.util.HashMap;

abstract class Game implements Runnable{

    protected boolean runGame = true;
    protected Player player1 = null;
    protected Player player2 = null;
    protected Player currentPlayer = null;

    public Game(){
        player1 = new Player("Player 1");
        player2 = new Player("Player 2");
        currentPlayer = player1;
        initializeGame();
    }

    /* Type 1: Let subclass define own implementation. Base class defines abstract method to force
        sub-classes to define implementation    
    */

    protected abstract void initializeGame();

    /* Type 2: Sub-class can change the behaviour. If not, base class behaviour is applicable */
    protected void logTimeBetweenMoves(Player player){
        System.out.println("Base class: Move Duration: player.PlayerActTime - player.MoveShownTime");
    }

    /* Type 3: Base class provides implementation. Sub-class can enhance base class implementation by calling
        super.methodName() in first line of the child class method and specific implementation later */
    protected void logGameStatistics(){
        System.out.println("Base class: logGameStatistics:");
    }
    /* Type 4: Template method: Structure of base class can't be changed but sub-class can some part of behaviour */
    protected void runGame() throws Exception{
        System.out.println("Base class: Defining the flow for Game:");  
        while ( runGame) {
            /*
            1. Set current player
            2. Get Player Move
            */
            validatePlayerMove(currentPlayer);  
            logTimeBetweenMoves(currentPlayer);
            Thread.sleep(500);
            setNextPlayer();
        }
        logGameStatistics();
    }
    /* sub-part of the template method, which define child class behaviour */
    protected abstract void validatePlayerMove(Player p);

    protected void setRunGame(boolean status){
        this.runGame = status;
    }
    public void setCurrentPlayer(Player p){
        this.currentPlayer = p;
    }
    public void setNextPlayer(){
        if ( currentPlayer == player1) {
            currentPlayer = player2;
        }else{
            currentPlayer = player1;
        }
    }
    public void run(){
        try{
            runGame();
        }catch(Exception err){
            err.printStackTrace();
        }
    }
}

class Player{
    String name;
    Player(String name){
        this.name = name;
    }
    public String getName(){
        return name;
    }
}

/* Concrete Game implementation  */
class Chess extends Game{
    public Chess(){
        super();
    }
    public void initializeGame(){
        System.out.println("Child class: Initialized Chess game");
    }
    protected void validatePlayerMove(Player p){
        System.out.println("Child class: Validate Chess move:"+p.getName());
    }
    protected void logGameStatistics(){
        super.logGameStatistics();
        System.out.println("Child class: Add Chess specific logGameStatistics:");
    }
}
class TicTacToe extends Game{
    public TicTacToe(){
        super();
    }
    public void initializeGame(){
        System.out.println("Child class: Initialized TicTacToe game");
    }
    protected void validatePlayerMove(Player p){
        System.out.println("Child class: Validate TicTacToe move:"+p.getName());
    }
}

public class Polymorphism{
    public static void main(String args[]){
        try{

            Game game = new Chess();
            Thread t1 = new Thread(game);
            t1.start();
            Thread.sleep(1000);
            game.setRunGame(false);
            Thread.sleep(1000);

            game = new TicTacToe();
            Thread t2 = new Thread(game);
            t2.start();
            Thread.sleep(1000);
            game.setRunGame(false);

        }catch(Exception err){
            err.printStackTrace();
        }       
    }
}

output:

Child class: Initialized Chess game
Base class: Defining the flow for Game:
Child class: Validate Chess move:Player 1
Base class: Move Duration: player.PlayerActTime - player.MoveShownTime
Child class: Validate Chess move:Player 2
Base class: Move Duration: player.PlayerActTime - player.MoveShownTime
Base class: logGameStatistics:
Child class: Add Chess specific logGameStatistics:
Child class: Initialized TicTacToe game
Base class: Defining the flow for Game:
Child class: Validate TicTacToe move:Player 1
Base class: Move Duration: player.PlayerActTime - player.MoveShownTime
Child class: Validate TicTacToe move:Player 2
Base class: Move Duration: player.PlayerActTime - player.MoveShownTime
Base class: logGameStatistics:

Use the XmlInclude or SoapInclude attribute to specify types that are not known statically

I agree with bizl

[XmlInclude(typeof(ParentOfTheItem))]
[Serializable]
public abstract class WarningsType{ }

also if you need to apply this included class to an object item you can do like that

[System.Xml.Serialization.XmlElementAttribute("Warnings", typeof(WarningsType))]
public object[] Items
{
    get
    {
        return this.itemsField;
    }
    set
    {
        this.itemsField = value;
    }
}

What is path of JDK on Mac ?

Have a look and see if the the JDK is at:

Library/Java/JavaVirtualMachines/ Or /System/Library/Java/JavaVirtualMachines/

Check this earlier SO post: JDK on OSX 10.7 Lion

What does mscorlib stand for?

It stands for

Microsoft's Common Object Runtime Library

and it is the primary assembly for the Framework Common Library.

It contains the following namespaces:

 System
 System.Collections
 System.Configuration.Assemblies
 System.Diagnostics
 System.Diagnostics.SymbolStore
 System.Globalization
 System.IO
 System.IO.IsolatedStorage
 System.Reflection
 System.Reflection.Emit
 System.Resources
 System.Runtime.CompilerServices
 System.Runtime.InteropServices
 System.Runtime.InteropServices.Expando
 System.Runtime.Remoting
 System.Runtime.Remoting.Activation
 System.Runtime.Remoting.Channels
 System.Runtime.Remoting.Contexts
 System.Runtime.Remoting.Lifetime
 System.Runtime.Remoting.Messaging
 System.Runtime.Remoting.Metadata
 System.Runtime.Remoting.Metadata.W3cXsd2001
 System.Runtime.Remoting.Proxies
 System.Runtime.Remoting.Services
 System.Runtime.Serialization
 System.Runtime.Serialization.Formatters
 System.Runtime.Serialization.Formatters.Binary
 System.Security
 System.Security.Cryptography
 System.Security.Cryptography.X509Certificates
 System.Security.Permissions
 System.Security.Policy
 System.Security.Principal
 System.Text
 System.Threading
 Microsoft.Win32 

Interesting info about MSCorlib:

  • The .NET 2.0 assembly will reference and use the 2.0 mscorlib.The .NET 1.1 assembly will reference the 1.1 mscorlib but will use the 2.0 mscorlib at runtime (due to hard-coded version redirects in theruntime itself)
  • In GAC there is only one version of mscorlib, you dont find 1.1 version on GAC even if you have 1.1 framework installed on your machine. It would be good if somebody can explain why MSCorlib 2.0 alone is in GAC whereas 1.x version live inside framework folder
  • Is it possible to force a different runtime to be loaded by the application by making a config setting in your app / web.config? you won’t be able to choose the CLR version by settings in the ConfigurationFile – at that point, a CLR will already be running, and there can only be one per process. Immediately after the CLR is chosen the MSCorlib appropriate for that CLR is loaded.

Difference between volatile and synchronized in Java

tl;dr:

There are 3 main issues with multithreading:

1) Race Conditions

2) Caching / stale memory

3) Complier and CPU optimisations

volatile can solve 2 & 3, but can't solve 1. synchronized/explicit locks can solve 1, 2 & 3.

Elaboration:

1) Consider this thread unsafe code:

x++;

While it may look like one operation, it's actually 3: reading the current value of x from memory, adding 1 to it, and saving it back to memory. If few threads try to do it at the same time, the result of the operation is undefined. If x originally was 1, after 2 threads operating the code it may be 2 and it may be 3, depending on which thread completed which part of the operation before control was transferred to the other thread. This is a form of race condition.

Using synchronized on a block of code makes it atomic - meaning it make it as if the 3 operations happen at once, and there's no way for another thread to come in the middle and interfere. So if x was 1, and 2 threads try to preform x++ we know in the end it will be equal to 3. So it solves the race condition problem.

synchronized (this) {
   x++; // no problem now
}

Marking x as volatile does not make x++; atomic, so it doesn't solve this problem.

2) In addition, threads have their own context - i.e. they can cache values from main memory. That means that a few threads can have copies of a variable, but they operate on their working copy without sharing the new state of the variable among other threads.

Consider that on one thread, x = 10;. And somewhat later, in another thread, x = 20;. The change in value of x might not appear in the first thread, because the other thread has saved the new value to its working memory, but hasn't copied it to the main memory. Or that it did copy it to the main memory, but the first thread hasn't updated its working copy. So if now the first thread checks if (x == 20) the answer will be false.

Marking a variable as volatile basically tells all threads to do read and write operations on main memory only. synchronized tells every thread to go update their value from main memory when they enter the block, and flush the result back to main memory when they exit the block.

Note that unlike data races, stale memory is not so easy to (re)produce, as flushes to main memory occur anyway.

3) The complier and CPU can (without any form of synchronization between threads) treat all code as single threaded. Meaning it can look at some code, that is very meaningful in a multithreading aspect, and treat it as if it’s single threaded, where it’s not so meaningful. So it can look at a code and decide, in sake of optimisation, to reorder it, or even remove parts of it completely, if it doesn’t know that this code is designed to work on multiple threads.

Consider the following code:

boolean b = false;
int x = 10;

void threadA() {
    x = 20;
    b = true;
}

void threadB() {
    if (b) {
        System.out.println(x);
    }
}

You would think that threadB could only print 20 (or not print anything at all if threadB if-check is executed before setting b to true), as b is set to true only after x is set to 20, but the compiler/CPU might decide to reorder threadA, in that case threadB could also print 10. Marking b as volatile ensures that it won’t be reordered (or discarded in certain cases). Which mean threadB could only print 20 (or nothing at all). Marking the methods as syncrhonized will achieve the same result. Also marking a variable as volatile only ensures that it won’t get reordered, but everything before/after it can still be reordered, so synchronization can be more suited in some scenarios.

Note that before Java 5 New Memory Model, volatile didn’t solve this issue.

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

Sometimes all you have to do to make sure the cursor is inside the text box is: click on the text box and when a menu is displayed, click on "Format text box" then click on the "text box" tab and finally modify all four margins (left, right, upper and bottom) by arrowing down until "0" appear on each margin.

Which command do I use to generate the build of a Vue app?

if you used vue-cli and webpack when you created your project.

you can use just

npm run build command in command line, and it will create dist folder in your project. Just upload content of this folder to your ftp and done.

Java HashMap: How to get a key and value by index?

HashMaps don't keep your key/value pairs in a specific order. They are ordered based on the hash that each key's returns from its Object.hashCode() method. You can however iterate over the set of key/value pairs using an iterator with:

for (String key : hashmap.keySet()) 
{
    for (list : hashmap.get(key))
    {
        //list.toString()
    }
}

How to get the caller class in Java

SecurityManager has a protected method getClassContext

By creating a utility class which extends SecurityManager, you can access this.

public class CallingClass extends SecurityManager {
    public static final CallingClass INSTANCE = new CallingClass();

    public Class[] getCallingClasses() {
        return getClassContext();
    }
}

Use CallingClass.INSTANCE.getCallingClasses() to retrieve the calling classes.

There is also a small library (disclaimer: mine) WhoCalled which exposes this information. It uses Reflection.getCallerClass when available, else falls back to SecurityManager.

Get Bitmap attached to ImageView

For those who are looking for Kotlin solution to get Bitmap from ImageView.

var bitmap = (image.drawable as BitmapDrawable).bitmap

How can I display a tooltip message on hover using jQuery?

take a look at the jQuery Tooltip plugin. You can pass in an options object for different options.

There are also other alternative tooltip plugins available, of which a few are

Take look at the demos and documentation and please update your question if you have specific questions about how to use them in your code.

How to make Java 6, which fails SSL connection with "SSL peer shut down incorrectly", succeed like Java 7?

It seems that in the debug log for Java 6 the request is send in SSLv2 format.

main, WRITE: SSLv2 client hello message, length = 110

This is not mentioned as enabled by default in Java 7.
Change the client to use SSLv3 and above to avoid such interoperability issues.

Look for differences in JSSE providers in Java 7 and Java 6

Which is the best IDE for Python For Windows

U can use eclipse. but u need to download pydev addon for that.

CASE (Contains) rather than equal statement

CASE WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%' 
  THEN 'BP Medication' ELSE '' END AS [BP Medication]

The leading ', ' and trailing ',' are added so that you can handle the match regardless of where it is in the string (first entry, last entry, or anywhere in between).

That said, why are you storing data you want to search on as a comma-separated string? This violates all kinds of forms and best practices. You should consider normalizing your schema.

In addition: don't use 'single quotes' as identifier delimiters; this syntax is deprecated. Use [square brackets] (preferred) or "double quotes" if you must. See "string literals as column aliases" here: http://msdn.microsoft.com/en-us/library/bb510662%28SQL.100%29.aspx

EDIT If you have multiple values, you can do this (you can't short-hand this with the other CASE syntax variant or by using something like IN()):

CASE 
  WHEN ', ' + dbo.Table.Column +',' LIKE '%, lactulose,%' 
  WHEN ', ' + dbo.Table.Column +',' LIKE '%, amlodipine,%' 
  THEN 'BP Medication' ELSE '' END AS [BP Medication]

If you have more values, it might be worthwhile to use a split function, e.g.

USE tempdb;
GO

CREATE FUNCTION dbo.SplitStrings(@List NVARCHAR(MAX))
RETURNS TABLE
AS
   RETURN ( SELECT DISTINCT Item FROM
       ( SELECT Item = x.i.value('(./text())[1]', 'nvarchar(max)')
         FROM ( SELECT [XML] = CONVERT(XML, '<i>'
         + REPLACE(@List,',', '</i><i>') + '</i>').query('.')
           ) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
       WHERE Item IS NOT NULL
   );
GO

CREATE TABLE dbo.[Table](ID INT, [Column] VARCHAR(255));
GO

INSERT dbo.[Table] VALUES
(1,'lactulose, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(2,'lactulite, Lasix (furosemide), lactulose, propranolol, rabeprazole, sertraline,'),
(3,'lactulite, Lasix (furosemide), oxazepam, propranolol, rabeprazole, sertraline,'),
(4,'lactulite, Lasix (furosemide), lactulose, amlodipine, rabeprazole, sertraline,');

SELECT t.ID
  FROM dbo.[Table] AS t
  INNER JOIN dbo.SplitStrings('lactulose,amlodipine') AS s
  ON ', ' + t.[Column] + ',' LIKE '%, ' + s.Item + ',%'
  GROUP BY t.ID;
GO

Results:

ID
----
1
2
4

How to specify the private SSH-key to use when executing shell command on Git?

I use zsh and different keys are loaded to my zsh shell's ssh-agent automatically for other purposes (i.e. access to remote servers) on my laptop. I modified @Nick's answer and I'm using it for one of my repos that needs to be refreshed often. (In this case it's my dotfiles which I want same and latest version across my all machines, wherever I'm working.)

bash -c 'eval `ssh-agent`; ssh-add /home/myname/.dotfiles/gitread; ssh-add -L; cd /home/myname/.dotfiles && git pull; kill $SSH_AGENT_PID'
  • Spawn an ssh-agent
  • Add read-only key to agent
  • Change directory to my git repo
  • If cd to repo dir is successful, pull from remote repo
  • Kill spawned ssh-agent. (I wouldn't want many of agents lingering around.)

HttpClient does not exist in .net 4.0: what can I do?

Agreeing with TrueWill's comment on a separate answer, the best way I've seen to use system.web.http on a .NET 4 targeted project under current Visual Studio is Install-Package Microsoft.AspNet.WebApi.Client -Version 4.0.30506

Hot to get all form elements values using jQuery?

The answer already been accepted, I just write a short technique for the same purpose.

var fieldPair = '';
$(":input").each(function(){
fieldPair += $(this).attr("name") + ':' + $(this).val() + ';';
});

console.log(fieldPair);

Error LNK2019 unresolved external symbol _main referenced in function "int __cdecl invoke_main(void)" (?invoke_main@@YAHXZ)

This worked for me:

(I don't have enough rep to embed pictures yet -- sorry about this.)

I went into Project --> Properties --> Linker --> System.

IMG: Located here, as of Dec 2019 Visual Studio for Windows

My platform was set to Active(Win32) with the Subsystem as "Windows". I was making a console app, so I set it to "Console".

IMG: Changing "Windows" --> "Console"

Then, I switched my platform to "x64".

IMG: Switched my platform from Active(32) to x64

Creating a new user and password with Ansible

I know that I'm late to the party, but there is another solution that I'm using. It might be handy for distros that don't have --stdin in passwd binary.

- hosts: localhost
  become: True
  tasks:
    - name: Change user password
      shell: "yes '{{ item.pass }}' | passwd {{ item.user }}"
      loop:
       - { pass: 123123, user: foo }
       - { pass: asdf, user: bar }
      loop_control:
        label: "{{ item.user }}"

Label in loop_control is responsible for printing only username. The whole playbook or just user variables (you can use vars_files:) should be encrypted with ansible-vault.

What is the "Illegal Instruction: 4" error and why does "-mmacosx-version-min=10.x" fix it?

I'm consciously writing this answer to an old question with this in mind, because the other answers didn't help me.

I got the Illegal Instruction: 4 while running the binary on the same system I had compiled it on, so -mmacosx-version-min didn't help.

I was using gcc in Code Blocks 16 on Mac OS X 10.11.

However, turning off all of Code Blocks' compiler flags for optimization worked. So look at all the flags Code Blocks set (right-click on the Project -> "Build Properties") and turn off all the flags you are sure you don't need, especially -s and the -Oflags for optimization. That did it for me.

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

In my case git push was trying to push more that just the current branch, therefore, I got this error since the other branches were not in sync.

To fix that you could use: git config --global push.default simple That will make git to only push the current branch.

This will only work on more recent versions of git. i.e.: won't work on 1.7.9.5

Setting mime type for excel document

For anyone who is still stumbling with this after using all of the possible MIME types listed in the question:

I have found that iMacs tend to also throw a MIME type of "text/xls" for XLS Excel files, hope this helps.

What's the difference between .bashrc, .bash_profile, and .environment?

I have used Debian-family distros which appear to execute .profile, but not .bash_profile, whereas RHEL derivatives execute .bash_profile before .profile.

It seems to be a mess when you have to set up environment variables to work in any Linux OS.

Is there a way to break a list into columns?

The mobile-first way is to use CSS Columns to create an experience for smaller screens then use Media Queries to increase the number of columns at each of your layout's defined breakpoints.

_x000D_
_x000D_
ul {_x000D_
  column-count: 2;_x000D_
  column-gap: 2rem;_x000D_
}_x000D_
@media screen and (min-width: 768px)) {_x000D_
  ul {_x000D_
    column-count: 3;_x000D_
    column-gap: 5rem;_x000D_
  }_x000D_
}
_x000D_
<ul>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
  <li>Item</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How to extract closed caption transcript from YouTube video?

Here's how to get the transcript of a YouTube video (when available):

  • Go to YouTube and open the video of your choice.
  • Click on the "More actions" button (3 horizontal dots) located next to the Share button.
  • Click "Open transcript"

Although the syntax may be a little goofy this is a pretty good solution.

Source: http://ccm.net/faq/40644-youtube-how-to-get-the-transcript-of-a-video

hexadecimal string to byte array in python

You should be able to build a string holding the binary data using something like:

data = "fef0babe"
bits = ""
for x in xrange(0, len(data), 2)
  bits += chr(int(data[x:x+2], 16))

This is probably not the fastest way (many string appends), but quite simple using only core Python.

How to set True as default value for BooleanField on Django?

If you're just using a vanilla form (not a ModelForm), you can set a Field initial value ( https://docs.djangoproject.com/en/2.2/ref/forms/fields/#django.forms.Field.initial ) like

class MyForm(forms.Form):
    my_field = forms.BooleanField(initial=True)

If you're using a ModelForm, you can set a default value on the model field ( https://docs.djangoproject.com/en/2.2/ref/models/fields/#default ), which will apply to the resulting ModelForm, like

class MyModel(models.Model):
    my_field = models.BooleanField(default=True)

Finally, if you want to dynamically choose at runtime whether or not your field will be selected by default, you can use the initial parameter to the form when you initialize it:

form = MyForm(initial={'my_field':True})

maximum value of int

Why not write a piece of code like:

int  max_neg = ~(1 << 31);
int  all_ones = -1;
int max_pos = all_ones & max_neg;

What does "res.render" do, and what does the html file look like?

Renders a view and sends the rendered HTML string to the client.

res.render('index');

Or

res.render('index', function(err, html) {
  if(err) {...}
  res.send(html);
});

DOCS HERE: https://expressjs.com/en/api.html#res.render

How to set custom favicon in Express?

No need for custom middleware?! In express:

 //you probably have something like this already    
app.use("/public", express.static('public')); 

Then put your favicon in public and add the following line in your html's head:

<link rel="icon" href="/public/favicon.ico">

take(1) vs first()

Here are three Observables A, B, and C with marble diagrams to explore the difference between first, take, and single operators:

first vs take vs single operators comparison

* Legend:
--o-- value
----! error
----| completion

Play with it at https://thinkrx.io/rxjs/first-vs-take-vs-single/ .

Already having all the answers, I wanted to add a more visual explanation

Hope it helps someone

How to change default text color using custom theme?

You can't use @android:style/TextAppearance as the parent for the whole app's theme; that's why koopaking3's solution seems quite broken.

To change default text colour everywhere in your app using a custom theme, try something like this. Works at least on Android 4.0+ (API level 14+).

res/values/themes.xml:

<resources>    
    <style name="MyAppTheme" parent="android:Theme.Holo.Light">
        <!-- Change default text colour from dark grey to black -->
        <item name="android:textColor">@android:color/black</item>
    </style>
</resources>

Manifest:

<application
    ...
    android:theme="@style/MyAppTheme">

Update

A shortcoming with the above is that also disabled Action Bar overflow menu items use the default colour, instead of being greyed out. (Of course, if you don't use disabled menu items anywhere in your app, this may not matter.)

As I learned by asking this question, a better way is to define the colour using a drawable:

<item name="android:textColor">@drawable/default_text_color</item>

...with res/drawable/default_text_color.xml specifying separate state_enabled="false" colour:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_enabled="false" android:color="@android:color/darker_gray"/>
    <item android:color="@android:color/black"/>
</selector>

The create-react-app imports restriction outside of src directory

Image inside public folder

  use image inside html extension
  <img src="%PUBLIC_URL%/resumepic.png"/>

  use image inside  js extension
  <img src={process.env.PUBLIC_URL+"/resumepic.png"}/>
  • use image inside js Extension

Can I pass variable to select statement as column name in SQL Server

You can't use variable names to bind columns or other system objects, you need dynamic sql

DECLARE @value varchar(10)  
SET @value = 'intStep'  
DECLARE @sqlText nvarchar(1000); 

SET @sqlText = N'SELECT ' + @value + ' FROM dbo.tblBatchDetail'
Exec (@sqlText)

How to Get True Size of MySQL Database?

If you use phpMyAdmin, it can tell you this information.

Just go to "Databases" (menu on top) and click "Enable Statistics".

You will see something like this:

phpMyAdmin screenshot

This will probably lose some accuracy as the sizes go up, but it should be accurate enough for your purposes.

Difference between string and StringBuilder in C#

Major difference:

String is immutable. It means that you can't modify a string at all; the result of modification is a new string. This is not effective if you plan to append to a string.

StringBuilder is mutable. It can be modified in any way and it doesn't require creation of a new instance. When the work is done, ToString() can be called to get the string.

Strings can participate in interning. It means that strings with same contents may have same addresses. StringBuilder can't be interned.

String is the only class that can have a reference literal.

How to get a value from a Pandas DataFrame and not the index and object type

Use the values attribute to return the values as a np array and then use [0] to get the first value:

In [4]:
df.loc[df.Letters=='C','Letters'].values[0]

Out[4]:
'C'

EDIT

I personally prefer to access the columns using subscript operators:

df.loc[df['Letters'] == 'C', 'Letters'].values[0]

This avoids issues where the column names can have spaces or dashes - which mean that accessing using ..

Catch KeyError in Python

Try print(e.message) this should be able to print your exception.

try:
    connection = manager.connect("I2Cx")
except Exception, e:
    print(e.message)

How to place a div below another div?

You have set #slider as absolute, which means that it "is positioned relative to the nearest positioned ancestor" (confusing, right?). Meanwhile, #content div is placed relative, which means "relative to its normal position". So the position of the 2 divs is not related.

You can read about CSS positioning here

If you set both to relative, the divs will be one after the other, as shown here:

#slider {
    position:relative;
    left:0;
    height:400px;

    border-style:solid;
    border-width:5px;
}
#slider img {
    width:100%;
}

#content {
    position:relative;
}

#content #text {
    position:relative;
    width:950px;
    height:215px;
    color:red;
}

http://jsfiddle.net/uorgj4e1/

RSpec: how to test if a method was called?

The below should work

describe "#foo"
  it "should call 'bar' with appropriate arguments" do
     subject.stub(:bar)
     subject.foo
     expect(subject).to have_received(:bar).with("Invalid number of arguments")
  end
end

Documentation: https://github.com/rspec/rspec-mocks#expecting-arguments

Cannot bulk load. Operating system error code 5 (Access is denied.)

This is quite simple the way I resolved this problem:

  1. open SQL Server
  2. right click on database (you want to be backup)
  3. select properties
  4. select permissions
  5. select your database role (local or cloud)
  6. in the you bottom you will see explicit permissions table
  7. find " backup database " permission and click Grant permission .

your problem is resolved .

How to fix curl: (60) SSL certificate: Invalid certificate chain

First off, you should be wary of urls that throw SSL errors. That being said, you can suppress certificate errors in curl with

curl -k https://insecure.url/content-i-really-really-trust

#pragma pack effect

Note that there are other ways of achieving data consistency that #pragma pack offers (for instance some people use #pragma pack(1) for structures that should be sent across the network). For instance, see the following code and its subsequent output:

#include <stdio.h>

struct a {
    char one;
    char two[2];
    char eight[8];
    char four[4];
};

struct b { 
    char one;
    short two;
    long int eight;
    int four;
};

int main(int argc, char** argv) {
    struct a twoa[2] = {}; 
    struct b twob[2] = {}; 
    printf("sizeof(struct a): %i, sizeof(struct b): %i\n", sizeof(struct a), sizeof(struct b));
    printf("sizeof(twoa): %i, sizeof(twob): %i\n", sizeof(twoa), sizeof(twob));
}

The output is as follows: sizeof(struct a): 15, sizeof(struct b): 24 sizeof(twoa): 30, sizeof(twob): 48

Notice how the size of struct a is exactly what the byte count is, but struct b has padding added (see this for details on the padding). By doing this as opposed to the #pragma pack you can have control of converting the "wire format" into the appropriate types. For instance, "char two[2]" into a "short int" et cetera.

How can I verify if an AD account is locked?

The LockedOut property is what you are looking for among all the properties you returned. You are only seeing incomplete output in TechNet. The information is still there. You can isolate that one property using Select-Object

Get-ADUser matt -Properties * | Select-Object LockedOut

LockedOut
---------
False

The link you referenced doesn't contain this information which is obviously misleading. Test the command with your own account and you will see much more information.

Note: Try to avoid -Properties *. While it is great for simple testing it can make queries, especially ones with multiple accounts, unnecessarily slow. So, in this case, since you only need lockedout:

Get-ADUser matt -Properties LockedOut | Select-Object LockedOut

How to create new folder?

You probably want os.makedirs as it will create intermediate directories as well, if needed.

import os

#dir is not keyword
def makemydir(whatever):
  try:
    os.makedirs(whatever)
  except OSError:
    pass
  # let exception propagate if we just can't
  # cd into the specified directory
  os.chdir(whatever)

How to make a Java Generic method static?

the only thing you can do is to change your signature to

public static <E> E[] appendToArray(E[] array, E item)

Important details:

Generic expressions preceding the return value always introduce (declare) a new generic type variable.

Additionally, type variables between types (ArrayUtils) and static methods (appendToArray) never interfere with each other.

So, what does this mean: In my answer <E> would hide the E from ArrayUtils<E> if the method wouldn't be static. AND <E> has nothing to do with the E from ArrayUtils<E>.

To reflect this fact better, a more correct answer would be:

public static <I> I[] appendToArray(I[] array, I item)

Check if String contains only letters

        String expression = "^[a-zA-Z]*$";
        CharSequence inputStr = str;
        Pattern pattern = Pattern.compile(expression);
        Matcher matcher = pattern.matcher(inputStr);
        if(matcher.matches())
        {
              //if pattern matches 
        }
        else
        {
             //if pattern does not matches
        }

Unsupported method: BaseConfig.getApplicationIdSuffix()

You can do this by changing the gradle file.

 build.gradle > change
    dependencies {
    classpath 'com.android.tools.build:gradle:3.0.1'
    }
    gradle-wrapper.properties > update
    distributionUrl=https://services.gradle.org/distributions/gradle-4.6-all.zip

Linux bash script to extract IP address

A slight modification to one of the previous ip route ... solutions, which eliminates the need for a grep:

ip route get 8.8.8.8 | sed -n 's|^.*src \(.*\)$|\1|gp'

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

Very often this error appears if you use incompatible versions of Selenium and ChromeDriver.

Selenium 3.0.1 for Maven project:

    <dependency>
        <groupId>org.seleniumhq.selenium</groupId>
        <artifactId>selenium-java</artifactId>
        <version>3.0.1</version>
    </dependency>

ChromeDriver 2.27: https://sites.google.com/a/chromium.org/chromedriver/downloads

Request failed: unacceptable content-type: text/html using AFNetworking 2.0

Setting my RequestOperationManager Response Serializer to HTTPResponseSerializer fixed the issue.

Objective-C

manager.responseSerializer = [AFHTTPResponseSerializer serializer];

Swift

manager.responseSerializer = AFHTTPResponseSerializer()

Making this change means I don't need to add acceptableContentTypes to every request I make.

Rotate a div using javascript

To rotate a DIV we can add some CSS that, well, rotates the DIV using CSS transform rotate.

To toggle the rotation we can keep a flag, a simple variable with a boolean value that tells us what way to rotate.

var rotated = false;

document.getElementById('button').onclick = function() {
    var div = document.getElementById('div'),
        deg = rotated ? 0 : 66;

    div.style.webkitTransform = 'rotate('+deg+'deg)'; 
    div.style.mozTransform    = 'rotate('+deg+'deg)'; 
    div.style.msTransform     = 'rotate('+deg+'deg)'; 
    div.style.oTransform      = 'rotate('+deg+'deg)'; 
    div.style.transform       = 'rotate('+deg+'deg)'; 

    rotated = !rotated;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

To add some animation to the rotation all we have to do is add CSS transitions

div {
    -webkit-transition: all 0.5s ease-in-out;
    -moz-transition: all 0.5s ease-in-out;
    -o-transition: all 0.5s ease-in-out;
    transition: all 0.5s ease-in-out;
}

_x000D_
_x000D_
var rotated = false;_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    var div = document.getElementById('div'),_x000D_
        deg = rotated ? 0 : 66;_x000D_
_x000D_
    div.style.webkitTransform = 'rotate('+deg+'deg)'; _x000D_
    div.style.mozTransform    = 'rotate('+deg+'deg)'; _x000D_
    div.style.msTransform     = 'rotate('+deg+'deg)'; _x000D_
    div.style.oTransform      = 'rotate('+deg+'deg)'; _x000D_
    div.style.transform       = 'rotate('+deg+'deg)'; _x000D_
    _x000D_
    rotated = !rotated;_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

Another way to do it is using classes, and setting all the styles in a stylesheet, thus keeping them out of the javascript

document.getElementById('button').onclick = function() {
    document.getElementById('div').classList.toggle('rotated');
}

_x000D_
_x000D_
document.getElementById('button').onclick = function() {_x000D_
    document.getElementById('div').classList.toggle('rotated');_x000D_
}
_x000D_
#div {_x000D_
    position:relative; _x000D_
    height: 200px; _x000D_
    width: 200px; _x000D_
    margin: 30px;_x000D_
    background: red;_x000D_
    -webkit-transition: all 0.5s ease-in-out;_x000D_
    -moz-transition: all 0.5s ease-in-out;_x000D_
    -o-transition: all 0.5s ease-in-out;_x000D_
    transition: all 0.5s ease-in-out;_x000D_
}_x000D_
_x000D_
#div.rotated {_x000D_
    -webkit-transform : rotate(66deg); _x000D_
    -moz-transform : rotate(66deg); _x000D_
    -ms-transform : rotate(66deg); _x000D_
    -o-transform : rotate(66deg); _x000D_
    transform : rotate(66deg); _x000D_
}
_x000D_
<button id="button">rotate</button>_x000D_
<br /><br />_x000D_
<div id="div"></div>
_x000D_
_x000D_
_x000D_

MySQL DAYOFWEEK() - my week begins with monday

Could write a udf and take a value to tell it which day of the week should be 1 would look like this (drawing on answer from John to use MOD instead of CASE):

DROP FUNCTION IF EXISTS `reporting`.`udfDayOfWeek`;
DELIMITER |
CREATE FUNCTION `reporting`.`udfDayOfWeek` (
  _date DATETIME,
  _firstDay TINYINT
) RETURNS tinyint(4)
FUNCTION_BLOCK: BEGIN
  DECLARE _dayOfWeek, _offset TINYINT;
  SET _offset = 8 - _firstDay;
  SET _dayOfWeek = (DAYOFWEEK(_date) + _offset) MOD 7;
  IF _dayOfWeek = 0 THEN
    SET _dayOfWeek = 7;
  END IF;
  RETURN _dayOfWeek;
END FUNCTION_BLOCK

To call this function to give you the current day of week value when your week starts on a Tuesday for instance, you'd call:

SELECT udfDayOfWeek(NOW(), 3);

Nice thing about having it as a udf is you could also call it on a result set field like this:

SELECT
  udfDayOfWeek(p.SignupDate, 3) AS SignupDayOfWeek,
  p.FirstName,
  p.LastName
FROM Profile p;

How to drop a table if it exists?

A better visual and easy way, if you are using Visual Studio, just open from menu bar,

View -> SQL Server Object Explorer

it should open like shown here

enter image description here

Select and Right Click the Table you wish to delete, then delete. Such a screen should be displayed. Click Update Database to confirm.

enter image description here

This method is very safe as it gives you the feedback and will warn of any relations of the deleted table with other tables.

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.

Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload

json.net has key method?

JObject implements IDictionary<string, JToken>, so you can use:

IDictionary<string, JToken> dictionary = x;
if (dictionary.ContainsKey("error_msg"))

... or you could use TryGetValue. It implements both methods using explicit interface implementation, so you can't use them without first converting to IDictionary<string, JToken> though.

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

It is important to highlight that the Property (MaximumErrorCount) that needs to be changed must be set as more than 0 (which is the default) in the Package level and not in the specific control that is showing the error (I tried this and it does not work!)

Be sure that in the Properties Window, the Pull down menu is set to "Package", then look for the property MaximumErrorCount to change it.

add controls vertically instead of horizontally using flow layout

I used a BoxLayout and set its second parameter as BoxLayout.Y_AXIS and it worked for me:

panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));

How to combine two strings together in PHP?

No one mentioned this but there is other possibility. I'm using it for huge sql queries. You can use .= operator :)

$string = "the color is ";
$string .= "red";

echo $string; // gives: the color is red

Negative regex for Perl string pattern match

If my understanding is correct then you want to match any line which has Clinton and Reagan, in any order, but not Bush. As suggested by Stuck, here is a version with lookahead assertions:

#!/usr/bin/perl

use strict;
use warnings;

my $regex = qr/
    (?=.*clinton)  
    (?!.*bush) 
    .*reagan       
    /ix;

while (<DATA>) {
    chomp;
    next unless (/$regex/);
    print $_, "\n";
}


__DATA__
shouldn't match - reagan came first, then clinton, finally bush
first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan
shouldn't match - last two: clinton and bush
shouldn't match - reverse: bush and clinton
shouldn't match - and then came obama, along comes mary
shouldn't match - to clinton with perl

Results

first match - first two: reagan and clinton
second match - first two reverse: clinton and reagan

as desired it matches any line which has Reagan and Clinton in any order.

You may want to try reading how lookahead assertions work with examples at http://www252.pair.com/comdog/mastering_perl/Chapters/02.advanced_regular_expressions.html

they are very tasty :)

Insert 2 million rows into SQL Server quickly

You can try with SqlBulkCopy class.

Lets you efficiently bulk load a SQL Server table with data from another source.

There is a cool blog post about how you can use it.

C# An established connection was aborted by the software in your host machine

This problem appear if two software use same port for connecting to the server
try to close the port by cmd according to your operating system
then reboot your Android studio or your Eclipse or your Software.

What are some good Python ORM solutions?

We use Elixir alongside SQLAlchemy and have liked it so far. Elixir puts a layer on top of SQLAlchemy that makes it look more like the "ActiveRecord pattern" counter parts.

Angular2 - TypeScript : Increment a number after timeout in AppComponent

This is not valid TypeScript code. You can not have method invocations in the body of a class.

// INVALID CODE
export class AppComponent {
  public n: number = 1;
  setTimeout(function() {
    n = n + 10;
  }, 1000);
}

Instead move the setTimeout call to the constructor of the class. Additionally, use the arrow function => to gain access to this.

export class AppComponent {
  public n: number = 1;

  constructor() {
    setTimeout(() => {
      this.n = this.n + 10;
    }, 1000);
  }

}

In TypeScript, you can only refer to class properties or methods via this. That's why the arrow function => is important.

Select an Option from the Right-Click Menu in Selenium Webdriver - Java

this is better approach and its successful :

Actions oAction = new Actions(driver);
oAction.moveToElement(Webelement);
oAction.contextClick(Webelement).build().perform();  /* this will perform right click */
WebElement elementOpen = driver.findElement(By.linkText("Open")); /*This will select menu after right click */

elementOpen.click();

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

Regular Expression for alphanumeric and underscores

In Computer Science, an Alphanumeric value often means the first character is not a number but is an alphabet or underscore. Thereafter the character can be 0-9, A-Z, a-z, or underscore (_).

Here is how you would do that:

Tested under php:

$regex = '/^[A-Za-z_][A-Za-z\d_]*$/'

or take this

^[A-Za-z_][A-Za-z\d_]*$

and place it in your development language.

How to print instances of a class using print()?

You need to use __repr__. This is a standard function like __init__. For example:

class Foobar():
    """This will create Foobar type object."""

    def __init__(self):
        print "Foobar object is created."

    def __repr__(self):
        return "Type what do you want to see here."

a = Foobar()

print a

HashSet vs. List performance

The breakeven will depend on the cost of computing the hash. Hash computations can be trivial, or not... :-) There is always the System.Collections.Specialized.HybridDictionary class to help you not have to worry about the breakeven point.

How to get name of the computer in VBA?

A shell method to read the environmental variable for this courtesy of devhut

Debug.Print CreateObject("WScript.Shell").ExpandEnvironmentStrings("%COMPUTERNAME%")

Same source gives an API method:

Option Explicit

#If VBA7 And Win64 Then
    'x64 Declarations
    Declare PtrSafe Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#Else
    'x32 Declaration
    Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#End If

Public Sub test()

    Debug.Print ComputerName
    
End Sub

Public Function ComputerName() As String
    Dim sBuff                 As String * 255
    Dim lBuffLen              As Long
    Dim lResult               As Long
 
    lBuffLen = 255
    lResult = GetComputerName(sBuff, lBuffLen)
    If lBuffLen > 0 Then
        ComputerName = Left(sBuff, lBuffLen)
    End If
End Function

JQuery string contains check

I use,

var text = "some/String"; text.includes("/") <-- returns bool; true if "/" exists in string, false otherwise.

VBA Public Array : how to?

Declare array as global across subs in a application:

Public GlobalArray(10) as String
GlobalArray = Array('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L')

Sub DisplayArray()
    Dim i As Integer

    For i = 0 to UBound(GlobalArray, 1)
        MsgBox GlobalArray(i)

    Next i
End Sub

Method 2: Pass an array to sub. Use ParamArray.

Sub DisplayArray(Name As String, ParamArray Arr() As Variant)
    Dim i As Integer

    For i = 0 To UBound(Arr())
        MsgBox Name & ": " & Arr(i)
    Next i
End Sub

ParamArray must be the last parameter.

How to set background color of a View

This should work fine: v.setBackgroundColor(0xFF00FF00);

How do I convert hex to decimal in Python?

You could use a literal eval:

>>> ast.literal_eval('0xdeadbeef')
3735928559

Or just specify the base as argument to int:

>>> int('deadbeef', 16)
3735928559

A trick that is not well known, if you specify the base 0 to int, then Python will attempt to determine the base from the string prefix:

>>> int("0xff", 0)
255
>>> int("0o644", 0)
420
>>> int("0b100", 0)
4
>>> int("100", 0)
100

How can I set a custom baud rate on Linux?

I noticed the same thing about BOTHER not being defined. Like Jamey Sharp said, you can find it in <asm/termios.h>. Just a forewarning, I think I ran into problems including both it and the regular <termios.h> file at the same time.

Aside from that, I found with the glibc I have, it still didn't work because glibc's tcsetattr was doing the ioctl for the old-style version of struct termios which doesn't pay attention to the speed setting. I was able to set a custom speed by manually doing an ioctl with the new style termios2 struct, which should also be available by including <asm/termios.h>:

struct termios2 tio;

ioctl(fd, TCGETS2, &tio);
tio.c_cflag &= ~CBAUD;
tio.c_cflag |= BOTHER;
tio.c_ispeed = 12345;
tio.c_ospeed = 12345;
ioctl(fd, TCSETS2, &tio);

How do I shut down a python simpleHTTPserver?

It seems like overkill but you can use supervisor to start and stop your simpleHttpserver, and completely manage it as a service.

Or just run it in the foreground as suggested and kill it with control c

Throw away local commits in Git

If your excess commits are only visible to you, you can just do git reset --hard origin/<branch_name> to move back to where the origin is. This will reset the state of the repository to the previous commit, and it will discard all local changes.

Doing a git revert makes new commits to remove old commits in a way that keeps everyone's history sane.

How do I POST an array of objects with $.ajax (jQuery or Zepto)

edit: I guess it's now starting to be safe to use the native JSON.stringify() method, supported by most browsers (yes, even IE8+ if you're wondering).

As simple as:

JSON.stringify(yourData)

You should encode you data in JSON before sending it, you can't just send an object like this as POST data.

I recommand using the jQuery json plugin to do so. You can then use something like this in jQuery:

$.post(_saveDeviceUrl, {
    data : $.toJSON(postData)
}, function(response){
    //Process your response here
}
);

Turn off enclosing <p> tags in CKEditor 3.0

CKEDITOR.config.enterMode = CKEDITOR.ENTER_BR; - this works perfectly for me. Have you tried clearing your browser cache - this is an issue sometimes.
You can also check it out with the jQuery adapter:

<script type="text/javascript" src="/js/ckeditor/ckeditor.js"></script>
<script type="text/javascript" src="/js/ckeditor/adapters/jquery.js"></script>
<script type="text/javascript">
$(function() {
    $('#your_textarea').ckeditor({
        toolbar: 'Full',
        enterMode : CKEDITOR.ENTER_BR,
        shiftEnterMode: CKEDITOR.ENTER_P
    });
});
</script>


UPDATE according to @Tomkay's comment:

Since version 3.6 of CKEditor you can configure if you want inline content to be automatically wrapped with tags like <p></p>. This is the correct setting:

CKEDITOR.config.autoParagraph = false;

Source: http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.config.html#.autoParagraph

How to check if a file is a valid image file?

Additionally to the PIL image check you can also add file name extension check like this:

filename.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif'))

Note that this only checks if the file name has a valid image extension, it does not actually open the image to see if it's a valid image, that's why you need to use additionally PIL or one of the libraries suggested in the other answers.

How to convert a List<String> into a comma separated string without iterating List explicitly

One Liner (pure Java)

list.toString().replace(", ", ",").replaceAll("[\\[.\\]]", "");

Apk location in New Android Studio

As of version 0.8.6 of Android Studio generating an APK file (signed and I believe unsigned, too) will be placed inside ProjectName/device/build/outputs/apk

For example, I am making something for Google Glass and my signed APK gets dropped in /Users/MyName/AndroidStudioProjects/HelloGlass/glass/build/outputs/apk

What is the best project structure for a Python application?

The "Python Packaging Authority" has a sampleproject:

https://github.com/pypa/sampleproject

It is a sample project that exists as an aid to the Python Packaging User Guide's Tutorial on Packaging and Distributing Projects.

.NET unique object identifier

If you are writing a module in your own code for a specific usage, majkinetor's method MIGHT have worked. But there are some problems.

First, the official document does NOT guarantee that the GetHashCode() returns an unique identifier (see Object.GetHashCode Method ()):

You should not assume that equal hash codes imply object equality.

Second, assume you have a very small amount of objects so that GetHashCode() will work in most cases, this method can be overridden by some types.
For example, you are using some class C and it overrides GetHashCode() to always return 0. Then every object of C will get the same hash code. Unfortunately, Dictionary, HashTable and some other associative containers will make use this method:

A hash code is a numeric value that is used to insert and identify an object in a hash-based collection such as the Dictionary<TKey, TValue> class, the Hashtable class, or a type derived from the DictionaryBase class. The GetHashCode method provides this hash code for algorithms that need quick checks of object equality.

So, this approach has great limitations.

And even more, what if you want to build a general purpose library? Not only are you not able to modify the source code of the used classes, but their behavior is also unpredictable.

I appreciate that Jon and Simon have posted their answers, and I will post a code example and a suggestion on performance below.

using System;
using System.Diagnostics;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Collections.Generic;


namespace ObjectSet
{
    public interface IObjectSet
    {
        /// <summary> check the existence of an object. </summary>
        /// <returns> true if object is exist, false otherwise. </returns>
        bool IsExist(object obj);

        /// <summary> if the object is not in the set, add it in. else do nothing. </summary>
        /// <returns> true if successfully added, false otherwise. </returns>
        bool Add(object obj);
    }

    public sealed class ObjectSetUsingConditionalWeakTable : IObjectSet
    {
        /// <summary> unit test on object set. </summary>
        internal static void Main() {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ObjectSetUsingConditionalWeakTable objSet = new ObjectSetUsingConditionalWeakTable();
            for (int i = 0; i < 10000000; ++i) {
                object obj = new object();
                if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }


        public bool IsExist(object obj) {
            return objectSet.TryGetValue(obj, out tryGetValue_out0);
        }

        public bool Add(object obj) {
            if (IsExist(obj)) {
                return false;
            } else {
                objectSet.Add(obj, null);
                return true;
            }
        }

        /// <summary> internal representation of the set. (only use the key) </summary>
        private ConditionalWeakTable<object, object> objectSet = new ConditionalWeakTable<object, object>();

        /// <summary> used to fill the out parameter of ConditionalWeakTable.TryGetValue(). </summary>
        private static object tryGetValue_out0 = null;
    }

    [Obsolete("It will crash if there are too many objects and ObjectSetUsingConditionalWeakTable get a better performance.")]
    public sealed class ObjectSetUsingObjectIDGenerator : IObjectSet
    {
        /// <summary> unit test on object set. </summary>
        internal static void Main() {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            ObjectSetUsingObjectIDGenerator objSet = new ObjectSetUsingObjectIDGenerator();
            for (int i = 0; i < 10000000; ++i) {
                object obj = new object();
                if (objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.Add(obj)) { Console.WriteLine("bug!!!"); }
                if (!objSet.IsExist(obj)) { Console.WriteLine("bug!!!"); }
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
        }


        public bool IsExist(object obj) {
            bool firstTime;
            idGenerator.HasId(obj, out firstTime);
            return !firstTime;
        }

        public bool Add(object obj) {
            bool firstTime;
            idGenerator.GetId(obj, out firstTime);
            return firstTime;
        }


        /// <summary> internal representation of the set. </summary>
        private ObjectIDGenerator idGenerator = new ObjectIDGenerator();
    }
}

In my test, the ObjectIDGenerator will throw an exception to complain that there are too many objects when creating 10,000,000 objects (10x than in the code above) in the for loop.

Also, the benchmark result is that the ConditionalWeakTable implementation is 1.8x faster than the ObjectIDGenerator implementation.

How to get class object's name as a string in Javascript?

This is pretty old, but I ran across this question via Google, so perhaps this solution might be useful to others.

function GetObjectName(myObject){
    var objectName=JSON.stringify(myObject).match(/"(.*?)"/)[1];
    return objectName;
}

It just uses the browser's JSON parser and regex without cluttering up the DOM or your object too much.

Install Application programmatically on Android

Do not forget to request permissions:

android.Manifest.permission.WRITE_EXTERNAL_STORAGE 
android.Manifest.permission.READ_EXTERNAL_STORAGE

Add in AndroidManifest.xml the provider and permission:

<uses-permission android:name="android.permission.REQUEST_INSTALL_PACKAGES"/>
...
<application>
    ...
    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths"/>
    </provider>
</application>

Create XML file provider res/xml/provider_paths.xml

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-path
        name="external"
        path="." />
    <external-files-path
        name="external_files"
        path="." />
    <cache-path
        name="cache"
        path="." />
    <external-cache-path
        name="external_cache"
        path="." />
    <files-path
        name="files"
        path="." />
</paths>

Use below example code:

   public class InstallManagerApk extends AppCompatActivity {

    static final String NAME_APK_FILE = "some.apk";
    public static final int REQUEST_INSTALL = 0;

     @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // required permission:
        // android.Manifest.permission.WRITE_EXTERNAL_STORAGE 
        // android.Manifest.permission.READ_EXTERNAL_STORAGE

        installApk();

    }

    ...

    /**
     * Install APK File
     */
    private void installApk() {

        try {

            File filePath = Environment.getExternalStorageDirectory();// path to file apk
            File file = new File(filePath, LoadManagerApkFile.NAME_APK_FILE);

            Uri uri = getApkUri( file.getPath() ); // get Uri for  each SDK Android

            Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE);
            intent.setData( uri );
            intent.setFlags( Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_ACTIVITY_NEW_TASK );
            intent.putExtra(Intent.EXTRA_NOT_UNKNOWN_SOURCE, true);
            intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
            intent.putExtra(Intent.EXTRA_INSTALLER_PACKAGE_NAME, getApplicationInfo().packageName);

            if ( getPackageManager().queryIntentActivities(intent, 0 ) != null ) {// checked on start Activity

                startActivityForResult(intent, REQUEST_INSTALL);

            } else {
                throw new Exception("don`t start Activity.");
            }

        } catch ( Exception e ) {

            Log.i(TAG + ":InstallApk", "Failed installl APK file", e);
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG)
                .show();

        }

    }

    /**
     * Returns a Uri pointing to the APK to install.
     */
    private Uri getApkUri(String path) {

        // Before N, a MODE_WORLD_READABLE file could be passed via the ACTION_INSTALL_PACKAGE
        // Intent. Since N, MODE_WORLD_READABLE files are forbidden, and a FileProvider is
        // recommended.
        boolean useFileProvider = Build.VERSION.SDK_INT >= Build.VERSION_CODES.N;

        String tempFilename = "tmp.apk";
        byte[] buffer = new byte[16384];
        int fileMode = useFileProvider ? Context.MODE_PRIVATE : Context.MODE_WORLD_READABLE;
        try (InputStream is = new FileInputStream(new File(path));
             FileOutputStream fout = openFileOutput(tempFilename, fileMode)) {

            int n;
            while ((n = is.read(buffer)) >= 0) {
                fout.write(buffer, 0, n);
            }

        } catch (IOException e) {
            Log.i(TAG + ":getApkUri", "Failed to write temporary APK file", e);
        }

        if (useFileProvider) {

            File toInstall = new File(this.getFilesDir(), tempFilename);
            return FileProvider.getUriForFile(this,  BuildConfig.APPLICATION_ID, toInstall);

        } else {

            return Uri.fromFile(getFileStreamPath(tempFilename));

        }

    }

    /**
     * Listener event on installation APK file
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if(requestCode == REQUEST_INSTALL) {

            if (resultCode == Activity.RESULT_OK) {
                Toast.makeText(this,"Install succeeded!", Toast.LENGTH_SHORT).show();
            } else if (resultCode == Activity.RESULT_CANCELED) {
                Toast.makeText(this,"Install canceled!", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this,"Install Failed!", Toast.LENGTH_SHORT).show();
            }

        }

    }

    ...

}

Java Immutable Collections

Unmodifiable collections are usually read-only views (wrappers) of other collections. You can't add, remove or clear them, but the underlying collection can change.

Immutable collections can't be changed at all - they don't wrap another collection - they have their own elements.

Here's a quote from guava's ImmutableList

Unlike Collections.unmodifiableList(java.util.List<? extends T>), which is a view of a separate collection that can still change, an instance of ImmutableList contains its own private data and will never change.

So, basically, in order to get an immutable collection out of a mutable one, you have to copy its elements to the new collection, and disallow all operations.

Extract Data from PDF and Add to Worksheet

You can open the PDF file and extract its contents using the Adobe library (which I believe you can download from Adobe as part of the SDK, but it comes with certain versions of Acrobat as well)

Make sure to add the Library to your references too (On my machine it is the Adobe Acrobat 10.0 Type Library, but not sure if that is the newest version)

Even with the Adobe library it is not trivial (you'll need to add your own error-trapping etc):

Function getTextFromPDF(ByVal strFilename As String) As String
   Dim objAVDoc As New AcroAVDoc
   Dim objPDDoc As New AcroPDDoc
   Dim objPage As AcroPDPage
   Dim objSelection As AcroPDTextSelect
   Dim objHighlight As AcroHiliteList
   Dim pageNum As Long
   Dim strText As String

   strText = ""
   If (objAvDoc.Open(strFilename, "") Then
      Set objPDDoc = objAVDoc.GetPDDoc
      For pageNum = 0 To objPDDoc.GetNumPages() - 1
         Set objPage = objPDDoc.AcquirePage(pageNum)
         Set objHighlight = New AcroHiliteList
         objHighlight.Add 0, 10000 ' Adjust this up if it's not getting all the text on the page
         Set objSelection = objPage.CreatePageHilite(objHighlight)

         If Not objSelection Is Nothing Then
            For tCount = 0 To objSelection.GetNumText - 1
               strText = strText & objSelection.GetText(tCount)
            Next tCount
         End If
      Next pageNum
      objAVDoc.Close 1
   End If

   getTextFromPDF = strText

End Function

What this does is essentially the same thing you are trying to do - only using Adobe's own library. It's going through the PDF one page at a time, highlighting all of the text on the page, then dropping it (one text element at a time) into a string.

Keep in mind what you get from this could be full of all kinds of non-printing characters (line feeds, newlines, etc) that could even end up in the middle of what look like contiguous blocks of text, so you may need additional code to clean it up before you can use it.

Hope that helps!

How do I pass a list as a parameter in a stored procedure?

Maybe you could use:

select last_name+', '+first_name 
from user_mstr
where ',' + @user_id_list + ',' like '%,' + convert(nvarchar, user_id) + ',%'

What is the single most influential book every programmer should read?

The practice of programming. By Brian W. Kernighan, Rob Pike.

The style shown here is excellent - the code just speaks for itself, and the whole book follows the KISS principle. Personally not my languages of choice, but still influential to me.

Angular.js directive dynamic templateURL

You don't need custom directive here. Just use ng-include src attribute. It's compiled so you can put code inside. See plunker with solution for your issue.

<div ng-repeat="week in [1,2]">
  <div ng-repeat="day in ['monday', 'tuesday']">
    <ng-include src="'content/before-'+ week + '-' + day + '.html'"></ng-include>
  </div>
</div>

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

For Kotlin Users don't forget to add ? in data: Intent? like

public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {}

How to download image using requests

There are 2 main ways:

  1. Using .content (simplest/official) (see Zhenyi Zhang's answer):

    import io  # Note: io.BytesIO is StringIO.StringIO on Python2.
    import requests
    
    r = requests.get('http://lorempixel.com/400/200')
    r.raise_for_status()
    with io.BytesIO(r.content) as f:
        with Image.open(f) as img:
            img.show()
    
  2. Using .raw (see Martijn Pieters's answer):

    import requests
    
    r = requests.get('http://lorempixel.com/400/200', stream=True)
    r.raise_for_status()
    r.raw.decode_content = True  # Required to decompress gzip/deflate compressed responses.
    with PIL.Image.open(r.raw) as img:
        img.show()
    r.close()  # Safety when stream=True ensure the connection is released.
    

Timing both shows no noticeable difference.

Excluding directory when creating a .tar.gz file

You can also exclude more than one using only one --exclude. Like this example:

tar -pczf MyBackup.tar.gz --exclude={"/home/user/public_html/tmp","/home/user/public_html/data"} /home/user/public_html/

In --exclude= you must finish the directory name without / and must in between MyBackup.tar.gz and /home/user/public_html/

The syntax is:

tar <OPTIONS> <TARBALL_WILL_CREATE> <ARGS> <PATH_TO_COMPRESS>

How to control the line spacing in UILabel

I've made this simple extension that works very well for me:

extension UILabel {
    func setLineHeight(lineHeight: CGFloat) {
        let paragraphStyle = NSMutableParagraphStyle()
        paragraphStyle.lineSpacing = 1.0
        paragraphStyle.lineHeightMultiple = lineHeight
        paragraphStyle.alignment = self.textAlignment

        let attrString = NSMutableAttributedString()
        if (self.attributedText != nil) {
            attrString.append( self.attributedText!)
        } else {
            attrString.append( NSMutableAttributedString(string: self.text!))
            attrString.addAttribute(NSAttributedStringKey.font, value: self.font, range: NSMakeRange(0, attrString.length))
        }
        attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value:paragraphStyle, range:NSMakeRange(0, attrString.length))
        self.attributedText = attrString
    }
}

Copy this in a file, so then you can use it like this

myLabel.setLineHeight(0.7)

Subtract two dates in Java

Edit 2018-05-28 I have changed the example to use Java 8's Time API:

LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();

Maximum value of maxRequestLength?

Maximum is 2097151, If you try set more error occurred.

How to do parallel programming in Python?

You can use the multiprocessing module. For this case I might use a processing pool:

from multiprocessing import Pool
pool = Pool()
result1 = pool.apply_async(solve1, [A])    # evaluate "solve1(A)" asynchronously
result2 = pool.apply_async(solve2, [B])    # evaluate "solve2(B)" asynchronously
answer1 = result1.get(timeout=10)
answer2 = result2.get(timeout=10)

This will spawn processes that can do generic work for you. Since we did not pass processes, it will spawn one process for each CPU core on your machine. Each CPU core can execute one process simultaneously.

If you want to map a list to a single function you would do this:

args = [A, B]
results = pool.map(solve1, args)

Don't use threads because the GIL locks any operations on python objects.

jquery drop down menu closing by clicking outside

You would need to attach your click event to some element. If there are lots of other elements on the page you would not want to attach a click event to all of them.

One potential way would be to create a transparent div below your dropdown menu but above all other elements on the page. You would show it when the drop down was shown. Have the element have a click hander that hides the drop down and the transparent div.

_x000D_
_x000D_
$('#clickCatcher').click(function () { _x000D_
  $('#dropContainer').hide();_x000D_
  $(this).hide();_x000D_
});
_x000D_
#dropContainer { z-index: 101; ... }_x000D_
#clickCatcher { position: absolute; top: 0; left: 0; width: 100%; height: 100%; z-index: 100; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="dropDown"></div>_x000D_
<div id="clickCatcher"></div>
_x000D_
_x000D_
_x000D_

Origin is not allowed by Access-Control-Allow-Origin

if you're under apache, just add an .htaccess file to your directory with this content:

Header set Access-Control-Allow-Origin: *

Header set Access-Control-Allow-Headers: content-type

Header set Access-Control-Allow-Methods: *

Execute Python script via crontab

As you have mentioned it doesn't change anything.

First, you should redirect both standard input and standard error from the crontab execution like below:

*/2 * * * * /usr/bin/python /home/souza/Documets/Listener/listener.py > /tmp/listener.log 2>&1

Then you can view the file /tmp/listener.log to see if the script executed as you expected.

Second, I guess what you mean by change anything is by watching the files created by your program:

f = file('counter', 'r+w')
json_file = file('json_file_create_server.json', 'r+w')

The crontab job above won't create these file in directory /home/souza/Documets/Listener, as the cron job is not executed in this directory, and you use relative path in the program. So to create this file in directory /home/souza/Documets/Listener, the following cron job will do the trick:

*/2 * * * * cd /home/souza/Documets/Listener && /usr/bin/python listener.py > /tmp/listener.log 2>&1

Change to the working directory and execute the script from there, and then you can view the files created in place.

Check if inputs are empty using jQuery

You can try something like this:

$('#apply-form input[value!=""]').blur(function() {
    $(this).parents('p').addClass('warning');
});

It will apply .blur() event only to the inputs with empty values.

Git - Ignore files during merge

You could use .gitignore to keep the config.xml out of the repository, and then use a post commit hook to upload the appropriate config.xml file to the server.

Create a table without a header in Markdown

@thamme-gowda's solution works for images too!

| | |:----------------------------------------------------------------------------:| | ![](https://gravatar.com/avatar/4cc702785290b4934c531c56f6061e5e "Tonejito") |

You can check this out on a gist I made for that. Here is a render of the table hack on GitHub and GitLab:

What exactly is a Maven Snapshot and why do we need it?

The "SNAPSHOT" term means that the build is a snapshot of your code at a given time.

It usually means that this version is still under heavy development.

When the code is ready and it is time to release it, you will want to change the version listed in the POM. Then instead of having a "SNAPSHOT" you would use a label like "1.0".

For some help with versioning, check out the Semantic Versioning specification.

How to access the php.ini file in godaddy shared hosting linux

It's an older question, but if anyone has a problem with setting this, their documentation is outdated. I made a copy of the php.ini file named php5.ini and now it works.

SQL permissions for roles

USE DataBaseName; GO --------- CREATE ROLE --------- CREATE ROLE Doctors ; GO  ---- Assign Role To users -------  CREATE USER [Username] FOR LOGIN [Domain\Username] EXEC sp_addrolemember N'Doctors', N'Username'  ----- GRANT Permission to Users Assinged with this Role----- GRANT ALL ON Table1, Table2, Table3 TO Doctors; GO 

View list of all JavaScript variables in Google Chrome Console

The window object contains all the public variables, so you can type it in the console and then expand to view all variables/attributes/functions.

chrome-show-all-variables-expand-window-object

How can I mock an ES6 module import using Jest?

You have to mock the module and set the spy by yourself:

import myModule from '../myModule';
import dependency from '../dependency';
jest.mock('../dependency', () => ({
  doSomething: jest.fn()
}))

describe('myModule', () => {
  it('calls the dependency with double the input', () => {
    myModule(2);
    expect(dependency.doSomething).toBeCalledWith(4);
  });
});

How to split a string in two and store it in a field

I would suggest the following:

String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName); 

SQL Server Regular expressions in T-SQL

In case anyone else is still looking at this question, http://www.sqlsharp.com/ is a free, easy way to add regular expression CLR functions into your database.

SaveFileDialog setting default path and file type?

The SaveFileDialog control won't do any saving at all. All it does is providing you a convenient interface to actually display Windows' default file save dialog.

  1. Set the property InitialDirectory to the drive you'd like it to show some other default. Just think of other computers that might have a different layout. By default windows will save the directory used the last time and present it again.

  2. That is handled outside the control. You'll have to check the dialog's results and then do the saving yourself (e.g. write a text or binary file).

Just as a quick example (there are alternative ways to do it). savefile is a control of type SaveFileDialog

SaveFileDialog savefile = new SaveFileDialog(); 
// set a default file name
savefile.FileName = "unknown.txt";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";

if (savefile.ShowDialog() == DialogResult.OK)
{
    using (StreamWriter sw = new StreamWriter(savefile.FileName))
        sw.WriteLine ("Hello World!");
}

CSS Background Opacity

Just make sure to put width and height for the foreground the same with the background, or try to have top, bottom, left and right properties.

<style>
    .foreground, .background {
        position: absolute;
    }
    .foreground {
        z-index: 1;
    }
    .background {
        background-image: url(your/image/here.jpg);
        opacity: 0.4;
    }
</style>

<div class="foreground"></div>
<div class="background"></div>

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

Actually the minimum amount of Angular to be used (as requested in the original question) is just adding a class to the DOM element when show variable is true, and perform the animation/transition via CSS.

So your minimum Angular code is this:

<div class="box-opener" (click)="show = !show">
    Open/close the box
</div>

<div class="box" [class.opened]="show">
    <!-- Content -->
</div>

With this solution, you need to create CSS rules for the transition, something like this:

.box {
    background-color: #FFCC55;
    max-height: 0px;
    overflow-y: hidden;
    transition: ease-in-out 400ms max-height;
}

.box.opened {
    max-height: 500px;
    transition: ease-in-out 600ms max-height;
}

If you have retro-browser-compatibility issues, just remember to add the vendor prefixes in the transitions.

See the example here

Why "no projects found to import"?

In new updated eclipse the option "create project from existing source" is found here, File>New>Project>Android>Android Project from Existing Code. Then browse to root directory.

enter image description here

Is there an equivalent of CSS max-width that works in HTML emails?

There is a trick you can do for Outlook 2007 using conditional html comments.
The code below will make sure that Outlook table is 800px wide, its not max-width but it works better than letting the table span across the entire window.

<!--[if gte mso 9]>
<style>
#tableForOutlook {
  width:800px;
}
</style>
<![endif]-->

<table style="width:98%;max-width:800px">
<!--[if gte mso 9]>
  <table id="tableForOutlook"><tr><td>
<![endif]-->
    <tr><td>
    [Your Content Goes Here]
    </td></tr>
<!--[if gte mso 9]>
  </td></tr></table>
<![endif]-->
<table>

HTTP Ajax Request via HTTPS Page

Without any server side solution, Theres is only one way in which a secure page can get something from a insecure page/request and that's thought postMessage and a popup

I said popup cuz the site isn't allowed to mix content. But a popup isn't really mixing. It has it's own window but are still able to communicate with the opener with postMessage.

So you can open a new http-page with window.open(...) and have that making the request for you (that is if the site is using CORS as well)


XDomain came to mind when i wrote this but here is a modern approach using the new fetch api, the advantage is the streaming of large files, the downside is that it won't work in all browser

You put this proxy script on any http page

onmessage = evt => {
  const port = evt.ports[0]

  fetch(...evt.data).then(res => {
    // the response is not clonable
    // so we make a new plain object
    const obj = {
      bodyUsed: false,
      headers: [...res.headers],
      ok: res.ok,
      redirected: res.redurected,
      status: res.status,
      statusText: res.statusText,
      type: res.type,
      url: res.url
    }

    port.postMessage(obj)

    // Pipe the request to the port (MessageChannel)
    const reader = res.body.getReader()
    const pump = () => reader.read()
    .then(({value, done}) => done 
      ? port.postMessage(done)
      : (port.postMessage(value), pump())
    )

    // start the pipe
    pump()
  })
}

Then you open a popup window in your https page (note that you can only do this on a user interaction event or else it will be blocked)

window.popup = window.open(http://.../proxy.html)

create your utility function

function xfetch(...args) {
  // tell the proxy to make the request
  const ms = new MessageChannel
  popup.postMessage(args, '*', [ms.port1])

  // Resolves when the headers comes
  return new Promise((rs, rj) => {

    // First message will resolve the Response Object
    ms.port2.onmessage = ({data}) => {
      const stream = new ReadableStream({
        start(controller) {

          // Change the onmessage to pipe the remaning request
          ms.port2.onmessage = evt => {
            if (evt.data === true) // Done?
              controller.close()
            else // enqueue the buffer to the stream
              controller.enqueue(evt.data)
          }
        }
      })

      // Construct a new response with the 
      // response headers and a stream
      rs(new Response(stream, data))
    }
  })
}

And make the request like you normally do with the fetch api

xfetch('http://httpbin.org/get')
  .then(res => res.text())
  .then(console.log)

Check if inputs form are empty jQuery

You could do it like this :

bool areFieldEmpty = YES;
//Label to leave the loops
outer_loop;

//For each input (except of submit) in your form
$('form input[type!=submit]').each(function(){
   //If the field's empty
   if($(this).val() != '')
   {
      //Mark it
      areFieldEmpty = NO;
      //Then leave all the loops
      break outer_loop;
   }
});

//Then test your bool 

What is the opposite of :hover (on mouse leave)?

Although answers here are sufficient, I really think W3Schools example on this issue is very straightforward (it cleared up the confusion (for me) right away).

Use the :hover selector to change the style of a button when you move the mouse over it.

Tip: Use the transition-duration property to determine the speed of the "hover" effect:

Example

.button {
    -webkit-transition-duration: 0.4s; /* Safari & Chrome */
    transition-duration: 0.4s;
}

.button:hover {
    background-color: #4CAF50; /* Green */
    color: white;
}

In summary, for transitions where you want the "enter" and "exit" animations to be the same, you need to employ transitions on the main selector .button rather than the hover selector .button:hover. For transitions where you want the "enter" and "exit" animations to be different, you will need specify different main selector and hover selector transitions.

Bash integer comparison

The zeroth parameter of a shell command is the command itself (or sometimes the shell itself). You should be using $1.

(("$#" < 1)) && ( (("$1" != 1)) ||  (("$1" -ne 0q)) )

Your boolean logic is also a bit confused:

(( "$#" < 1 && # If the number of arguments is less than one…
  "$1" != 1 || "$1" -ne 0)) # …how can the first argument possibly be 1 or 0?

This is probably what you want:

(( "$#" )) && (( $1 == 1 || $1 == 0 )) # If true, there is at least one argument and its value is 0 or 1

Fastest way to zero out a 2d array in C?

memset(array, 0, sizeof(int [n][n]));

How to pass command line arguments to a rake task

I use a regular ruby argument in the rake file:

DB = ARGV[1]

then I stub out the rake tasks at the bottom of the file (since rake will look for a task based on that argument name).

task :database_name1
task :database_name2

command line:

rake mytask db_name

this feels cleaner to me than the var=foo ENV var and the task args[blah, blah2] solutions.
the stub is a little jenky, but not too bad if you just have a few environments that are a one-time setup

How to pass a parameter to Vue @click event handler

When you are using Vue directives, the expressions are evaluated in the context of Vue, so you don't need to wrap things in {}.

@click is just shorthand for v-on:click directive so the same rules apply.

In your case, simply use @click="addToCount(item.contactID)"

How to return a html page from a restful controller in spring boot?

I did three things:

  • Put the HTML page in {project.basedir}/resources/static/myPage.html;
  • Switch @RestController to @Controller;
  • This is my controller:
@RequestMapping(method = RequestMethod.GET, value = "/")
public String aName() {
    return "myPage.html";
}

No particular dependency is needed.

Spring Boot - Loading Initial Data

The most compact (for dynamic data) put @mathias-dpunkt solution into MainApp (with Lombok @AllArgsConstructor):

@SpringBootApplication
@AllArgsConstructor
public class RestaurantVotingApplication implements ApplicationRunner {
  private final VoteRepository voteRepository;
  private final UserRepository userRepository;

  public static void main(String[] args) {
    SpringApplication.run(RestaurantVotingApplication.class, args);
  }

  @Override
  public void run(ApplicationArguments args) {
    voteRepository.save(new Vote(userRepository.getOne(1), LocalDate.now(), LocalTime.now()));
  }
}

error: package javax.servlet does not exist

I needed to import javaee-api as well.

  <dependency>
     <groupId>javax</groupId>
     <artifactId>javaee-api</artifactId>
     <version>7.0</version>
  </dependency>

Unless I got following error:

package javax.servlet.http does not exist
javax.servlet.annotation does not exist
javax.servlet.http does not exist
...

Custom HTTP headers : naming conventions

RFC6648 recommends that you assume that your custom header "might become standardized, public, commonly deployed, or usable across multiple implementations." Therefore, it recommends not to prefix it with "X-" or similar constructs.

However, there is an exception "when it is extremely unlikely that [your header] will ever be standardized." For such "implementation-specific and private-use" headers, the RFC says a namespace such as a vendor prefix is justified.

How to echo in PHP, HTML tags

There isn't any need to use echo, sir. Just use the tag <plaintext>:

<plaintext>
    <div>
        <h3><a href="#">First</a></h3>
        <div>Lorem ipsum dolor sit amet.</div>
    </div>

Including another class in SCSS

@extend .myclass;
@extend #{'.my-class'};

Cassandra port usage - how are the ports used?

JMX now uses port 7199 instead of port 8080 (as of Cassandra 0.8.xx).

This is configurable in your cassandra-env.sh file, but the default is 7199.

Can you disable tabs in Bootstrap?

my tabs were in panels, so i added a class='disabled' to the tabs anchor

in javascript i added:

$(selector + ' a[data-toggle="tab"]').on('show.bs.tab', function (e) {
    if ($(this).hasClass('disabled')){
        e.preventDefault();
        return false;
    }
})

and for presentation in less i added:

.panel-heading{
    display:table;
    width:100%;
    padding-bottom:10px;
    ul.nav-tabs{
        display:table-cell;
        vertical-align:bottom;
        a.disabled{
            .text-muted;
            cursor:default;
            &:hover{
                background-color:transparent;
                border:none;
            }
        }
    }
}

How to stop java process gracefully?

Signalling in Linux can be done with "kill" (man kill for the available signals), you'd need the process ID to do that. (ps ax | grep java) or something like that, or store the process id when the process gets created (this is used in most linux startup files, see /etc/init.d)

Portable signalling can be done by integrating a SocketServer in your java application. It's not that difficult and gives you the freedom to send any command you want.

If you meant finally clauses in stead of finalizers; they do not get extecuted when System.exit() is called. Finalizers should work, but shouldn't really do anything more significant but print a debug statement. They're dangerous.

How to highlight a selected row in ngRepeat?

Each row has an ID. All you have to do is to send this ID to the function setSelected(), store it (in $scope.idSelectedVote for instance), and then check for each row if the selected ID is the same as the current one. Here is a solution (see the documentation for ngClass, if needed):

$scope.idSelectedVote = null;
$scope.setSelected = function (idSelectedVote) {
   $scope.idSelectedVote = idSelectedVote;
};
<ul ng-repeat="vote in votes" ng-click="setSelected(vote.id)" ng-class="{selected: vote.id === idSelectedVote}">
    ...
</ul>

Plunker

Replacing some characters in a string with another character

You might find this link helpful:

http://tldp.org/LDP/abs/html/string-manipulation.html

In general,

To replace the first match of $substring with $replacement:

${string/substring/replacement}

To replace all matches of $substring with $replacement:

${string//substring/replacement}

EDIT: Note that this applies to a variable named $string.

UILabel with text of two different colors

In my case I'm using Xcode 10.1. There is a option of switching between plain text and Attributed text in Label text in Interface Builder

enter image description here

Hope this may help someone else..!

XPath OR operator for different nodes

All title nodes with zipcode or book node as parent:

Version 1:

//title[parent::zipcode|parent::book]

Version 2:

//bookstore/book/title|//bookstore/city/zipcode/title

Version 3: (results are sorted based on source data rather than the order of book then zipcode)

//title[../../../*[book or magazine] or ../../../../*[city/zipcode]]

or - used within true/false - a Boolean operator in xpath

| - a Union operator in xpath that appends the query to the right of the operator to the result set from the left query.

What is the proper way to check and uncheck a checkbox in HTML5?

<form name="myForm" method="post">
  <p>Activity</p> 
  skiing:  <input type="checkbox" name="activity" value="skiing"  checked="yes" /><br /> 
  skating: <input type="checkbox" name="activity" value="skating" /><br /> 
  running: <input type="checkbox" name="activity" value="running" /><br /> 
  hiking:  <input type="checkbox" name="activity" value="hiking"  checked="yes" />
</form>

SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens on line 102

You didn't bind all your bindings here

$sql = "SELECT SQL_CALC_FOUND_ROWS *, UNIX_TIMESTAMP(publicationDate) AS publicationDate     FROM comments WHERE articleid = :art 
ORDER BY " . mysqli_escape_string($order) . " LIMIT :numRows";

$st = $conn->prepare( $sql );
$st->bindValue( ":art", $art, PDO::PARAM_INT );

You've declared a binding called :numRows but you never actually bind anything to it.

UPDATE 2019: I keep getting upvotes on this and that reminded me of another suggestion

Double quotes are string interpolation in PHP, so if you're going to use variables in a double quotes string, it's pointless to use the concat operator. On the flip side, single quotes are not string interpolation, so if you've only got like one variable at the end of a string it can make sense, or just use it for the whole string.

In fact, there's a micro op available here since the interpreter doesn't care about parsing the string for variables. The boost is nearly unnoticable and totally ignorable on a small scale. However, in a very large application, especially good old legacy monoliths, there can be a noticeable performance increase if strings are used like this. (and IMO, it's easier to read anyway)

How can I make an svg scale with its parent container?

Messing around & found this CSS seems to contain the SVG in Chrome browser up to the point where the container is larger than the image:

div.inserted-svg-logo svg { max-width:100%; }

Also seems to be working in FF + IE 11.