Programs & Examples On #Amazon sqs

Amazon Simple Queue Service (Amazon SQS) offers a reliable, highly scalable, hosted queue for storing messages as they travel between computers.

What is the difference between Amazon SNS and Amazon SQS?

You can see SNS as a traditional topic which you can have multiple Subscribers. You can have heterogeneous subscribers for one given SNS topic, including Lambda and SQS, for example. You can also send SMS messages or even e-mails out of the box using SNS. One thing to consider in SNS is only one message (notification) is received at once, so you cannot take advantage from batching.

SQS, on the other hand, is nothing but a queue, where you store messages and subscribe one consumer (yes, you can have N consumers to one SQS queue, but it would get messy very quickly and way harder to manage considering all consumers would need to read the message at least once, so one is better off with SNS combined with SQS for this use case, where SNS would push notifications to N SQS queues and every queue would have one subscriber, only) to process these messages. As of Jun 28, 2018, AWS Supports Lambda Triggers for SQS, meaning you don't have to poll for messages any more.

Furthermore, you can configure a DLQ on your source SQS queue to send messages to in case of failure. In case of success, messages are automatically deleted (this is another great improvement), so you don't have to worry about the already processed messages being read again in case you forgot to delete them manually. I suggest taking a look at Lambda Retry Behaviour to better understand how it works.

One great benefit of using SQS is that it enables batch processing. Each batch can contain up to 10 messages, so if 100 messages arrive at once in your SQS queue, then 10 Lambda functions will spin up (considering the default auto-scaling behaviour for Lambda) and they'll process these 100 messages (keep in mind this is the happy path as in practice, a few more Lambda functions could spin up reading less than the 10 messages in the batch, but you get the idea). If you posted these same 100 messages to SNS, however, 100 Lambda functions would spin up, unnecessarily increasing costs and using up your Lambda concurrency.

However, if you are still running traditional servers (like EC2 instances), you will still need to poll for messages and manage them manually.

You also have FIFO SQS queues, which guarantee the delivery order of the messages. SQS FIFO is also supported as an event source for Lambda as of November 2019

Even though there's some overlap in their use cases, both SQS and SNS have their own spotlight.

Use SNS if:

  • multiple subscribers is a requirement
  • sending SMS/E-mail out of the box is handy

Use SQS if:

  • only one subscriber is needed
  • batching is important

Ansible - read inventory hosts and variables to group_vars/all file

- name: host
   debug: msg="{{ item }}" 
   with_items:
    - "{{ groups['tests'] }}"

This piece of code will give the message:

'10.112.84.122'
'10.112.84.124'

as groups['tests'] basically return a list of unique ip addresses ['10.112.84.122','10.112.84.124'] whereas groups['tomcat'][0] returns 10.112.84.124.

Index of duplicates items in a python list

I'll mention the more obvious way of dealing with duplicates in lists. In terms of complexity, dictionaries are the way to go because each lookup is O(1). You can be more clever if you're only interested in duplicates...

my_list = [1,1,2,3,4,5,5]
my_dict = {}
for (ind,elem) in enumerate(my_list):
    if elem in my_dict:
        my_dict[elem].append(ind)
    else:
        my_dict.update({elem:[ind]})

for key,value in my_dict.iteritems():
    if len(value) > 1:
        print "key(%s) has indices (%s)" %(key,value)

which prints the following:

key(1) has indices ([0, 1])
key(5) has indices ([5, 6])

How do I use reflection to invoke a private method?

Read this (supplementary) answer (that is sometimes the answer) to understand where this is going and why some people in this thread complain that "it is still not working"

I wrote exactly same code as one of the answers here. But I still had an issue. I placed break point on

var mi = o.GetType().GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance );

It executed but mi == null

And it continued behavior like this until I did "re-build" on all projects involved. I was unit testing one assembly while the reflection method was sitting in third assembly. It was totally confusing but I used Immediate Window to discover methods and I found that a private method I tried to unit test had old name (I renamed it). This told me that old assembly or PDB is still out there even if unit test project builds - for some reason project it tests didn't built. "rebuild" worked

How do I make a JSON object with multiple arrays?

Using below method pass any value which is any array:

Input parameter: url, like Example: "/node/[any int value of array]/anyKeyWhichInArray" Example: "cars/Nissan/[0]/model"

It can be used for any response:

    public String getResponseParameterThroughUrl(Response r, String url) throws JsonProcessingException, IOException {
    String value = "";
    String[] xpathOrder = url.split("/");
    ObjectMapper objectMapper = new ObjectMapper();
    String responseData = r.getBody().asString();       
    JSONObject jsonObject = new JSONObject(responseData);
    byte[] jsonData = jsonObject.toString().getBytes();
    JsonNode rootNode = objectMapper.readTree(jsonData);
    JsonNode node = null;
    for(int i=1;i<xpathOrder.length;i++) {
        if(node==null)
            node = rootNode;
        if(xpathOrder[i].contains("[")){
            xpathOrder[i] = xpathOrder[i].replace("[", "");
            xpathOrder[i] = xpathOrder[i].replace("]", "");
            node = node.get(Integer.parseInt(xpathOrder[i]));
        }
        else
            node = node.path(xpathOrder[i]);
    }
    value = node.asText();
    return value;
}

Byte array to image conversion

First Install This Package:

Install-Package SixLabors.ImageSharp -Version 1.0.0-beta0007

[SixLabors.ImageSharp][1] [1]: https://www.nuget.org/packages/SixLabors.ImageSharp

Then use Below Code For Cast Byte Array To Image :

Image<Rgba32> image = Image.Load(byteArray); 

For Get ImageFormat Use Below Code:

IImageFormat format = Image.DetectFormat(byteArray);

For Mutate Image Use Below Code:

image.Mutate(x => x.Resize(new Size(1280, 960)));

cast class into another class or convert class to another

Using this code you can copy any class object to another class object for same name and same type of properties.

JavaScriptSerializer JsonConvert = new JavaScriptSerializer(); 
string serializeString = JsonConvert.Serialize(objectEntity);
objectViewModel objVM = JsonConvert.Deserialize<objectViewModel>(serializeString);

How to play videos in android from assets folder or raw folder?

It sounds maybe like you have the same issue as i do. instead of using MP4, is 3GPP possible? i think i used like HandBrake or something as the video converter... you just need to make sure you have the right encoder, like H.264x or something. sorry for being a little vague, it's been a while. Also, if it's possible, don't bother worrying about android 2.1 anymore, and also, something things just WILL NOT WORK IN EMULATOR. so if it works on a lot of devices, then just assume it works (especially with different manufacurers)

here, you can read my problem and how i solved the issue (after a long time and no one had an answer). i explained in a lot more detail here: android media player not working

Foreign key constraint may cause cycles or multiple cascade paths?

A typical situation with multiple cascasing paths will be this: A master table with two details, let's say "Master" and "Detail1" and "Detail2". Both details are cascade delete. So far no problems. But what if both details have a one-to-many-relation with some other table (say "SomeOtherTable"). SomeOtherTable has a Detail1ID-column AND a Detail2ID-column.

Master { ID, masterfields }

Detail1 { ID, MasterID, detail1fields }

Detail2 { ID, MasterID, detail2fields }

SomeOtherTable {ID, Detail1ID, Detail2ID, someothertablefields }

In other words: some of the records in SomeOtherTable are linked with Detail1-records and some of the records in SomeOtherTable are linked with Detail2 records. Even if it is guaranteed that SomeOtherTable-records never belong to both Details, it is now impossible to make SomeOhterTable's records cascade delete for both details, because there are multiple cascading paths from Master to SomeOtherTable (one via Detail1 and one via Detail2). Now you may already have understood this. Here is a possible solution:

Master { ID, masterfields }

DetailMain { ID, MasterID }

Detail1 { DetailMainID, detail1fields }

Detail2 { DetailMainID, detail2fields }

SomeOtherTable {ID, DetailMainID, someothertablefields }

All ID fields are key-fields and auto-increment. The crux lies in the DetailMainId fields of the Detail tables. These fields are both key and referential contraint. It is now possible to cascade delete everything by only deleting master-records. The downside is that for each detail1-record AND for each detail2 record, there must also be a DetailMain-record (which is actually created first to get the correct and unique id).

Alter MySQL table to add comments on columns

The information schema isn't the place to treat these things (see DDL database commands).

When you add a comment you need to change the table structure (table comments).

From MySQL 5.6 documentation:

INFORMATION_SCHEMA is a database within each MySQL instance, the place that stores information about all the other databases that the MySQL server maintains. The INFORMATION_SCHEMA database contains several read-only tables. They are actually views, not base tables, so there are no files associated with them, and you cannot set triggers on them. Also, there is no database directory with that name.

Although you can select INFORMATION_SCHEMA as the default database with a USE statement, you can only read the contents of tables, not perform INSERT, UPDATE, or DELETE operations on them.

Chapter 21 INFORMATION_SCHEMA Tables

Change default date time format on a single database in SQL Server

You do realize that format has nothing to do with how SQL Server stores datetime, right?

You can use set dateformat for each session. There is no setting for database only.

If you use parameters for data insert or update or where filtering you won't have any problems with that.

Error inflating class android.support.design.widget.NavigationView

None of the solutions above helped me. I found this on some other webpage and it worked for me - "In project.properties of design library set target to 21 or highest available, then clean design lib, appcomapt and your project and enjoy"

Hope it will help!

get launchable activity name of package from adb

Since Android 7.0 you can use adb shell cmd package resolve-activity command to get the default activity of an installed app like this:

adb shell "cmd package resolve-activity --brief com.google.android.calculator | tail -n 1"
com.google.android.calculator/com.android.calculator2.Calculator

How can I process each letter of text using Javascript?

you can convert this string into an array of chars using split(), then iterate through it.

_x000D_
_x000D_
const str = "javascript";_x000D_
const strArray = str.split('');_x000D_
_x000D_
strArray.map(s => console.log(s));
_x000D_
_x000D_
_x000D_

How to insert TIMESTAMP into my MySQL table?

Please try CURRENT_TIME() or now() functions

"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', NOW(), '$comments')"

OR

"INSERT INTO contactinfo (name, email, subject, date, comments)
VALUES ('$name', '$email', '$subject', CURRENT_TIME(), '$comments')"

OR you could try with PHP date function here:

$date = date("Y-m-d H:i:s");

Concat all strings inside a List<string> using LINQ

You can simply use:

List<string> items = new List<string>() { "foo", "boo", "john", "doe" };

Console.WriteLine(string.Join(",", items));

Happy coding!

AngularJS: Can't I set a variable value on ng-click?

While @tymeJV gave a correct answer, the way to do this to be inline with angular would be:

ng-click="hidePrefs()"

and then in your controller:

$scope.hidePrefs = function() {  
  $scope.prefs = false;
}

Print text instead of value from C enum

TheDay maps back to some integer type. So:

printf("%s", TheDay);

Attempts to parse TheDay as a string, and will either print out garbage or crash.

printf is not typesafe and trusts you to pass the right value to it. To print out the name of the value, you'd need to create some method for mapping the enum value to a string - either a lookup table, giant switch statement, etc.

What is AF_INET, and why do I need it?

You need arguments like AF_UNIX or AF_INET to specify which type of socket addressing you would be using to implement IPC socket communication. AF stands for Address Family.

As in BSD standard Socket (adopted in Python socket module) addresses are represented as follows:

  1. A single string is used for the AF_UNIX/AF_LOCAL address family. This option is used for IPC on local machines where no IP address is required.

  2. A pair (host, port) is used for the AF_INET address family, where host is a string representing either a hostname in Internet domain notation like 'daring.cwi.nl' or an IPv4 address like '100.50.200.5', and port is an integer. Used to communicate between processes over the Internet.

AF_UNIX , AF_INET6 , AF_NETLINK , AF_TIPC , AF_CAN , AF_BLUETOOTH , AF_PACKET , AF_RDS are other option which could be used instead of AF_INET.

This thread about the differences between AF_INET and PF_INET might also be useful.

Sort tuples based on second parameter

    def findMaxSales(listoftuples):
        newlist = []
        tuple = ()
        for item in listoftuples:
             movie = item[0]
             value = (item[1])
             tuple = value, movie

             newlist += [tuple]
             newlist.sort()
             highest = newlist[-1]
             result = highest[1]
       return result

             movieList = [("Finding Dory", 486), ("Captain America: Civil                      

             War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The  Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
             print(findMaxSales(movieList))

output --> Rogue One

HTML text-overflow ellipsis detection

Try this JS function, passing the span element as argument:

function isEllipsisActive(e) {
     return (e.offsetWidth < e.scrollWidth);
}

What is the most efficient way to concatenate N arrays?

Now we can combine multiple arrays using ES6 Spread. Instead of using concat() to concatenate arrays, try using the spread syntax to combine multiple arrays into one flattened array. eg:

var a = [1,2];
var b = [3,4];
var c = [5,6,7];
var d = [...a, ...b, ...c];
// resulting array will be like d = [1,2,3,4,5,6,7]

Fixed positioned div within a relative parent div

here is a more generic solution, that don't depends on the Menu/Header height. its fully responsive, Pure CSS solution, Works great on IE8+, Firefox, Chrome, Safari, opera. supports Content scrolling without affecting the Menu/Header.

Test it with that Working Fiddle

The Html:

<div class="Container">
    <div class="First">
        <p>The First div height is not fixed</p>
        <p>This Layout has been tested on: IE10, IE9, IE8, FireFox, Chrome, Safari, using Pure CSS 2.1 only</p>
    </div>
    <div class="Second">
        <div class="Wrapper">
            <div class="Centered">
                <p>The Second div should always span the available Container space.</p>
                <p>This content is vertically Centered.</p>
            </div>
        </div>
    </div>
</div>

The CSS:

*
{
    margin: 0;
    padding: 0;
}

html, body, .Container
{
    height: 100%;
}

    .Container:before
    {
        content: '';
        height: 100%;
        float: left;
    }

.First
{
    /*for demonstration only*/
    background-color: #bf5b5b;
}

.Second
{
    position: relative;
    z-index: 1;
    /*for demonstration only*/
    background-color: #6ea364;
}

    .Second:after
    {
        content: '';
        clear: both;
        display: block;
    }

/*This part his relevant only for Vertically centering*/
.Wrapper
{
    position: absolute;
    width: 100%;
    height: 100%;
    overflow: auto;
}
    .Wrapper:before
    {
        content: '';
        display: inline-block;
        vertical-align: middle;
        height: 100%;
    }

.Centered
{
    display: inline-block;
    vertical-align: middle;
}

Measure execution time for a Java method

As proposed nanoTime () is very precise on short time scales. When this precision is required you need to take care about what you really measure. Especially not to measure the nanotime call itself

long start1 = System.nanoTime();
// maybe add here a call to a return to remove call up time, too.
// Avoid optimization 
long start2 = System.nanoTime();
myCall(); 
long stop = System.nanoTime();
long diff = stop - 2*start2 + start1;

System.out.println(diff + " ns");

By the way, you will measure different values for the same call due to

  • other load on your computer (background, network, mouse movement, interrupts, task switching, threads)
  • cache fillings (cold, warm)
  • jit compiling (no optimization, performance hit due to running the compiler, performance boost due to compiler (but sometimes code with jit is slower than without!))

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

All modern browsers (tested with Chrome 4, Firefox 3.5, IE8, Opera 10 and Safari 4) will always request a favicon.ico unless you've specified a shortcut icon via <link>. So if you don't explicitly specify one, it's best to always have a favicon.ico file, to avoid a 404. Yahoo! suggests you make it small and cacheable.

And you don't have to go for a PNG just for the alpha transparency either. ICO files support alpha transparency just fine (i.e. 32-bit color), though hardly any tools allow you to create them. I regularly use Dynamic Drive's FavIcon Generator to create favicon.ico files with alpha transparency. It's the only online tool I know of that can do it.

There's also a free Photoshop plug-in that can create them.

How to interpret "loss" and "accuracy" for a machine learning model

They are two different metrics to evaluate your model's performance usually being used in different phases.

Loss is often used in the training process to find the "best" parameter values for your model (e.g. weights in neural network). It is what you try to optimize in the training by updating weights.

Accuracy is more from an applied perspective. Once you find the optimized parameters above, you use this metrics to evaluate how accurate your model's prediction is compared to the true data.

Let us use a toy classification example. You want to predict gender from one's weight and height. You have 3 data, they are as follows:(0 stands for male, 1 stands for female)

y1 = 0, x1_w = 50kg, x2_h = 160cm;

y2 = 0, x2_w = 60kg, x2_h = 170cm;

y3 = 1, x3_w = 55kg, x3_h = 175cm;

You use a simple logistic regression model that is y = 1/(1+exp-(b1*x_w+b2*x_h))

How do you find b1 and b2? you define a loss first and use optimization method to minimize the loss in an iterative way by updating b1 and b2.

In our example, a typical loss for this binary classification problem can be: (a minus sign should be added in front of the summation sign)

We don't know what b1 and b2 should be. Let us make a random guess say b1 = 0.1 and b2 = -0.03. Then what is our loss now?

so the loss is

Then you learning algorithm (e.g. gradient descent) will find a way to update b1 and b2 to decrease the loss.

What if b1=0.1 and b2=-0.03 is the final b1 and b2 (output from gradient descent), what is the accuracy now?

Let's assume if y_hat >= 0.5, we decide our prediction is female(1). otherwise it would be 0. Therefore, our algorithm predict y1 = 1, y2 = 1 and y3 = 1. What is our accuracy? We make wrong prediction on y1 and y2 and make correct one on y3. So now our accuracy is 1/3 = 33.33%

PS: In Amir's answer, back-propagation is said to be an optimization method in NN. I think it would be treated as a way to find gradient for weights in NN. Common optimization method in NN are GradientDescent and Adam.

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

How To Launch Git Bash from DOS Command Line?

I'm not sure exactly what you mean by "full Git Bash environment", but I get the nice prompt if I do

"C:\Program Files\Git\bin\sh.exe" --login

In PowerShell

& 'C:\Program Files\Git\bin\sh.exe' --login

The --login switch makes the shell execute the login shell startup files.

How does `scp` differ from `rsync`?

scp is best for one file.
OR a combination of tar & compression for smaller data sets like source code trees with small resources (ie: images, sqlite etc).


Yet, when you begin dealing with larger volumes say:

  • media folders (40 GB)
  • database backups (28 GB)
  • mp3 libraries (100 GB)

It becomes impractical to build a zip/tar.gz file to transfer with scp at this point do to the physical limits of the hosted server.

As an exercise, you can do some gymnastics like piping tar into ssh and redirecting the results into a remote file. (saving the need to build a swap or temporary clone aka zip or tar.gz)

However,

rsync simplify's this process and allows you to transfer data without consuming any additional disc space.

Also,

Continuous (cron?) updates use minimal changes vs full cloned copies speed up large data migrations over time.

tl;dr
scp == small scale (with room to build compressed files on the same drive)
rsync == large scale (with the necessity to backup large data and no room left)

Closing WebSocket correctly (HTML5, Javascript)

The thing of it is there are 2 main protocol versions of WebSockets in use today. The old version which uses the [0x00][message][0xFF] protocol, and then there's the new version using Hybi formatted packets.

The old protocol version is used by Opera and iPod/iPad/iPhones so it's actually important that backward compatibility is implemented in WebSockets servers. With these browsers using the old protocol, I discovered that refreshing the page, or navigating away from the page, or closing the browser, all result in the browser automatically closing the connection. Great!!

However with browsers using the new protocol version (eg. Firefox, Chrome and eventually IE10), only closing the browser will result in the browser automatically closing the connection. That is to say, if you refresh the page, or navigate away from the page, the browser does NOT automatically close the connection. However, what the browser does do, is send a hybi packet to the server with the first byte (the proto ident) being 0x88 (better known as the close data frame). Once the server receives this packet it can forcefully close the connection itself, if you so choose.

Git push error pre-receive hook declined

Might not be the case, but this was the solution to my "pre-receive hook declined" error:

There are some repositories that only allow modifications through Pull Request. This means that you have to

  1. Create a new branch taking as base the branch that you want to push your changes to.
  2. Commit and push your changes to the new branch.
  3. Open a Pull Request to merge your branch with the original one.

Run Stored Procedure in SQL Developer?

Use:

BEGIN

  PACKAGE_NAME.PROCEDURE_NAME(parameter_value, ...);

END;

Replace "PACKAGE_NAME", "PROCEDURE_NAME", and "parameter_value" with what you need. OUT parameters will need to be declared prior to.

The character encoding of the plain text document was not declared - mootool script

FireFox is reporting that the response did not even specify the character encoding in the header, eg. Content-Type: text/html; charset=utf-8 and not just Content-Type: text/plain;.

What web server are you using? Are you sure you are not requesting a non-existing page (404) that responds poorly?

TypeError: Image data can not convert to float

In my case image path was wrong! So firstly, you might want to check if image path is correct :)

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

As precised in the annotation documentation, the annotation indicates that the argument name is used as the property name without any modifications, but it can be specified to non-empty value to specify different name:

Laravel 5.4 Specific Table Migration

First you should to make the following commands:

Step 1:

php artisan migrate:rollback

Step 2:

php artisan migrate

Your table will be back in database .

How can I get just the first row in a result set AFTER ordering?

This question is similar to How do I limit the number of rows returned by an Oracle query after ordering?.

It talks about how to implement a MySQL limit on an oracle database which judging by your tags and post is what you are using.

The relevant section is:

select *
from  
  ( select * 
  from emp 
  order by sal desc ) 
  where ROWNUM <= 5;

How to move columns in a MySQL table?

Change column position:

ALTER TABLE Employees 
   CHANGE empName empName VARCHAR(50) NOT NULL AFTER department;

If you need to move it to the first position you have to use term FIRST at the end of ALTER TABLE CHANGE [COLUMN] query:

ALTER TABLE UserOrder 
   CHANGE order_id order_id INT(11) NOT NULL FIRST;

Counting repeated characters in a string in Python

inputString =  input("Enter a String:")
countedArray = {}

for char in inputString:
    if char in countedArray:  
        countedArray[char] += 1    
    else:
        countedArray[char] = 1
    
print(countedArray) 

How to define object in array in Mongoose schema correctly with 2d geo index

I had a similar issue with mongoose :

fields: 
    [ '[object Object]',
     '[object Object]',
     '[object Object]',
     '[object Object]' ] }

In fact, I was using "type" as a property name in my schema :

fields: [
    {
      name: String,
      type: {
        type: String
      },
      registrationEnabled: Boolean,
      checkinEnabled: Boolean
    }
  ]

To avoid that behavior, you have to change the parameter to :

fields: [
    {
      name: String,
      type: {
        type: { type: String }
      },
      registrationEnabled: Boolean,
      checkinEnabled: Boolean
    }
  ]

Javascript - How to show escape characters in a string?

If your goal is to have

str = "Hello\nWorld";

and output what it contains in string literal form, you can use JSON.stringify:

console.log(JSON.stringify(str)); // ""Hello\nWorld""

_x000D_
_x000D_
const str = "Hello\nWorld";_x000D_
const json = JSON.stringify(str);_x000D_
console.log(json); // ""Hello\nWorld""_x000D_
for (let i = 0; i < json.length; ++i) {_x000D_
    console.log(`${i}: ${json.charAt(i)}`);_x000D_
}
_x000D_
.as-console-wrapper {_x000D_
    max-height: 100% !important;_x000D_
}
_x000D_
_x000D_
_x000D_

console.log adds the outer quotes (at least in Chrome's implementation), but the content within them is a string literal (yes, that's somewhat confusing).

JSON.stringify takes what you give it (in this case, a string) and returns a string containing valid JSON for that value. So for the above, it returns an opening quote ("), the word Hello, a backslash (\), the letter n, the word World, and the closing quote ("). The linefeed in the string is escaped in the output as a \ and an n because that's how you encode a linefeed in JSON. Other escape sequences are similarly encoded.

How to auto import the necessary classes in Android Studio with shortcut?

On my Mac Auto import option was not showing it was initially hidden

Android studio ->Preferences->editor->General->Auto Import

and then typed in searched field auto then auto import option appeared. And now auto import option is now always shown as default in Editor->General. hopefully this option will also help others. See attached screenshot screenshot

NodeJS: How to decode base64 encoded string back to binary?

As of Node.js v6.0.0 using the constructor method has been deprecated and the following method should instead be used to construct a new buffer from a base64 encoded string:

var b64string = /* whatever */;
var buf = Buffer.from(b64string, 'base64'); // Ta-da

For Node.js v5.11.1 and below

Construct a new Buffer and pass 'base64' as the second argument:

var b64string = /* whatever */;
var buf = new Buffer(b64string, 'base64'); // Ta-da

If you want to be clean, you can check whether from exists :

if (typeof Buffer.from === "function") {
    // Node 5.10+
    buf = Buffer.from(b64string, 'base64'); // Ta-da
} else {
    // older Node versions, now deprecated
    buf = new Buffer(b64string, 'base64'); // Ta-da
}

How to automatically start a service when running a docker container?

I have the same problem when I want to automatically start ssh service. I found that append

/etc/init.d/ssh start
to
~/.bashrc
can resolve it ,but only you open it with bash will do.

Get the value of bootstrap Datetimepicker in JavaScript

It seems the doc evolved.

One should now use : $("#datetimepicker1").data("DateTimePicker").date().

NB : Doing so return a Moment object, not a Date object

When should a class be Comparable and/or Comparator?

Comparable is for objects with a natural ordering. The object itself knows how it is to be ordered.
Comparator is for objects without a natural ordering or when you wish to use a different ordering.

Laravel Eloquent groupBy() AND also return count of each group

Works that way as well, a bit more tidy. getQuery() just returns the underlying builder, which already contains the table reference.

$browser_total_raw = DB::raw('count(*) as total');
$user_info = Usermeta::getQuery()
                     ->select('browser', $browser_total_raw)
                     ->groupBy('browser')
                     ->pluck('total','browser');

Each GROUP BY expression must contain at least one column that is not an outer reference

I think you're not using GROUP BY properly.

The point of GROUP BY is to organize your table into sections based off a certain column or columns before performing math/aggregate functions.

For example, in this table:

Name    Age   Salary
Bob     25     20000
Sally   42     40000
John    42     90000

A SELECT statement could GROUP BY name (Bob, Sally, and John would each be separate groups), Age (Bob would be one group, Sally and John would be another), or Salary (pretty much same result as name).

Grouping by "1" doesn't make any sense because "1" is not a column name.

Defining array with multiple types in TypeScript

TypeScript 3.9+ update (May 12, 2020)

Now, TypeScript also supports named tuples. This greatly increases the understandability and maintainability of the code. Check the official TS playground.


So, now instead of unnamed:

const a: [number, string] = [ 1, "message" ];

We can add names:

const b: [id: number, message: string] = [ 1, "message" ];

Note: you need to add all names at once, you can not omit some names, e.g:

type tIncorrect = [id: number, string]; // INCORRECT, 2nd element has no name, compile-time error.
type tCorrect = [id: number, msg: string]; // CORRECT, all have a names.

Tip: if you are not sure in the count of the last elements, you can write it like this:

type t = [msg: string, ...indexes: number];// means first element is a message and there are unknown number of indexes.

Evenly space multiple views within a container view

Yes, you can do this solely in interface builder and without writing code - the one caveat is that you are resizing the label instead of distributing whitespace. In this case, align Label 2's X and Y to the superview so it is fixed in the center. Then set label 1's vertical space to the superview and to label 2 to the standard, repeat for label 3. After setting label 2 the easiest way to set label 1 and 3 is to resize them until they snap.

Here is the horizontal display, note that the vertical space between label 1 and 2 is set to standard:horizontal display

And here is the portrait version:enter image description here

I realize they are not absolutely 100% equally spaced between the baselines due to the difference between the standard space between labels and the standard space to the superview. If that bothers you, set the size to 0 instead of standard

Apply style ONLY on IE

A bit late on this one but this worked perfectly for me when trying to hide the background for IE6 & 7

.myclass{ 
    background-image: url("images/myimg.png");
    background-position: right top;
    background-repeat: no-repeat;
    background-size: 22px auto;
    padding-left: 48px;
    height: 42px;
    _background-image: none;
    *background-image: none;
}

I got this hack via: http://briancray.com/posts/target-ie6-and-ie7-with-only-1-extra-character-in-your-css/

#myelement
{
    color: #999; /* shows in all browsers */
    *color: #999; /* notice the * before the property - shows in IE7 and below */
    _color: #999; /* notice the _ before the property - shows in IE6 and below */
}

How to make a simple image upload using Javascript/HTML

<img id="output_image" height=50px width=50px\
<input type="file" accept="image/*" onchange="preview_image(event)">

<script type"text/javascript">
  function preview_image(event) {
    var reader = new FileReader();
    reader.onload = function(){
      var output = document.getElementById('output_image');
      output.src = reader.result;
    }
    reader.readAsDataURL(event.target.files[0]);
  }
</script>

Reversing an Array in Java

Collections.reverse() can do that job for you if you put your numbers in a List of Integers.

List<Integer> list = Arrays.asList(1, 4, 9, 16, 9, 7, 4, 9, 11);
System.out.println(list);
Collections.reverse(list);
System.out.println(list);

Output:

[1, 4, 9, 16, 9, 7, 4, 9, 11]
[11, 9, 4, 7, 9, 16, 9, 4, 1]

How do I navigate to another page when PHP script is done?

if ($done)
{
    header("Location: /url/to/the/other/page");
    exit;
}

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

In your component, you can call this.forceUpdate() to force a rerender.

Documentation: https://facebook.github.io/react/docs/component-api.html

Error parsing yaml file: mapping values are not allowed here

Or, if spacing is not the problem, it might want the parent directory name rather than the file name.

Not $ dev_appserver helloapp.py
But $ dev_appserver hello/

For example:

Johns-Mac:hello john$ dev_appserver.py helloworld.py
Traceback (most recent call last):
  File "/usr/local/bin/dev_appserver.py", line 82, in <module>
    _run_file(__file__, globals())
...
  File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/api/yaml_listener.py", line 212, in _GenerateEventParameters
    raise yaml_errors.EventListenerYAMLError(e)
google.appengine.api.yaml_errors.EventListenerYAMLError: mapping values are not allowed here
  in "helloworld.py", line 3, column 39

Versus

Johns-Mac:hello john$ cd ..
Johns-Mac:fbm john$ dev_appserver.py hello/
INFO     2014-09-15 11:44:27,828 api_server.py:171] Starting API server at: http://localhost:61049
INFO     2014-09-15 11:44:27,831 dispatcher.py:183] Starting module "default" running at: http://localhost:8080

Sleep function in C++

Use std::this_thread::sleep_for:

#include <chrono>
#include <thread>

std::chrono::milliseconds timespan(111605); // or whatever

std::this_thread::sleep_for(timespan);

There is also the complementary std::this_thread::sleep_until.


Prior to C++11, C++ had no thread concept and no sleep capability, so your solution was necessarily platform dependent. Here's a snippet that defines a sleep function for Windows or Unix:

#ifdef _WIN32
    #include <windows.h>

    void sleep(unsigned milliseconds)
    {
        Sleep(milliseconds);
    }
#else
    #include <unistd.h>
    
    void sleep(unsigned milliseconds)
    {
        usleep(milliseconds * 1000); // takes microseconds
    }
#endif

But a much simpler pre-C++11 method is to use boost::this_thread::sleep.

compareTo with primitives -> Integer / int

May I propose a third

((Integer) a).compareTo(b)  

Sending event when AngularJS finished loading

I had a fragment that was getting loaded-in after/by the main partial that came in via routing.

I needed to run a function after that subpartial loaded and I didn't want to write a new directive and figured out you could use a cheeky ngIf

Controller of parent partial:

$scope.subIsLoaded = function() { /*do stuff*/; return true; };

HTML of subpartial

<element ng-if="subIsLoaded()"><!-- more html --></element>

Storing Images in DB - Yea or Nay?

This might be a bit of a long shot, but if you're using (or planning on using) SQL Server 2008 I'd recommend having a look at the new FileStream data type.

FileStream solves most of the problems around storing the files in the DB:

  1. The Blobs are actually stored as files in a folder.
  2. The Blobs can be accessed using either a database connection or over the filesystem.
  3. Backups are integrated.
  4. Migration "just works".

However SQL's "Transparent Data Encryption" does not encrypt FileStream objects, so if that is a consideration, you may be better off just storing them as varbinary.

From the MSDN Article:

Transact-SQL statements can insert, update, query, search, and back up FILESTREAM data. Win32 file system interfaces provide streaming access to the data.
FILESTREAM uses the NT system cache for caching file data. This helps reduce any effect that FILESTREAM data might have on Database Engine performance. The SQL Server buffer pool is not used; therefore, this memory is available for query processing.

HTML5 Video autoplay on iPhone

I had a similar problem and I tried multiple solution. I solved it implementing 2 considerations.

  1. Using dangerouslySetInnerHtml to embed the <video> code. For example:
<div dangerouslySetInnerHTML={{ __html: `
    <video class="video-js" playsinline autoplay loop muted>
        <source src="../video_path.mp4" type="video/mp4"/>
    </video>`}}
/>
  1. Resizing the video weight. I noticed my iPhone does not autoplay videos over 3 megabytes. So I used an online compressor tool (https://www.mp4compress.com/) to go from 4mb to less than 500kb

Also, thanks to @boltcoder for his guide: Autoplay muted HTML5 video using React on mobile (Safari / iOS 10+)

How to force Laravel Project to use HTTPS for all routes?

Using the following code in your .htaccess file automatically redirects visitors to the HTTPS version of your site:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

sys.stdin.readline() reads without prompt, returning 'nothing in between'

Try this ...

import sys
buffer = []
while True:
    userinput = sys.stdin.readline().rstrip('\n')
    if userinput == 'quit':
        break
    else:
        buffer.append(userinput)

Casting to string in JavaScript

On this page you can test the performance of each method yourself :)

http://jsperf.com/cast-to-string/2

here, on all machines and browsers, ' "" + str ' is the fastest one, (String)str is the slowest

How is the default max Java heap size determined?

For the IBM JVM, the command is the following:

java -verbose:sizes -version

For more information about the IBM SDK for Java 8: http://www-01.ibm.com/support/knowledgecenter/SSYKE2_8.0.0/com.ibm.java.lnx.80.doc/diag/appendixes/defaults.html?lang=en

Remove all elements contained in another array

How about the simplest possible:

_x000D_
_x000D_
var myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];_x000D_
var toRemove = ['b', 'c', 'g'];_x000D_
_x000D_
var myArray = myArray.filter((item) => !toRemove.includes(item));_x000D_
console.log(myArray)
_x000D_
_x000D_
_x000D_

document.getElementById(id).focus() is not working for firefox or chrome

Make sure you use "id" and "getElementById" as shown here:

<FORM id="my_form" name="my_form" action="">
<INPUT TYPE="text" NAME="somefield" ID="somefield" onChange="document.getElementById('my_form').submit();">
</FORM>

How to show all of columns name on pandas dataframe?

Not a conventional answer, but I guess you could transpose the dataframe to look at the rows instead of the columns. I use this because I find looking at rows more 'intuitional' than looking at columns:

data_all2.T

This should let you view all the rows. This action is not permanent, it just lets you view the transposed version of the dataframe.

If the rows are still truncated, just use print(data_all2.T) to view everything.

find a minimum value in an array of floats

You need to iterate the 2d array in order to get the min value of each row, then you have to push any gotten min value to another array and finally you need to get the min value of the array where each min row value was pushed

def get_min_value(self, table):
    min_values = []
    for i in range(0, len(table)):
        min_value = min(table[i])
        min_values.append(min_value)

    return min(min_values)

In R, how to find the standard error of the mean?

As I'm going back to this question every now and then and because this question is old, I'm posting a benchmark for the most voted answers.

Note, that for @Ian's and @John's answers I created another version. Instead of using length(x), I used sum(!is.na(x)) (to avoid NAs). I used a vector of 10^6, with 1,000 repetitions.

library(microbenchmark)

set.seed(123)
myVec <- rnorm(10^6)

IanStd <- function(x) sd(x)/sqrt(length(x))

JohnSe <- function(x) sqrt(var(x)/length(x))

IanStdisNA <- function(x) sd(x)/sqrt(sum(!is.na(x)))

JohnSeisNA <- function(x) sqrt(var(x)/sum(!is.na(x)))

AranStderr <- function(x, na.rm=FALSE) {
  if (na.rm) x <- na.omit(x)
  sqrt(var(x)/length(x))
}

mbm <- microbenchmark(
  "plotrix" = {plotrix::std.error(myVec)},
  "IanStd" = {IanStd(myVec)},
  "JohnSe" = {JohnSe(myVec)},
  "IanStdisNA" = {IanStdisNA(myVec)},
  "JohnSeisNA" = {JohnSeisNA(myVec)},
  "AranStderr" = {AranStderr(myVec)}, 
  times = 1000)

mbm

Results:

Unit: milliseconds
       expr     min       lq      mean   median       uq      max neval cld
    plotrix 10.3033 10.89360 13.869947 11.36050 15.89165 125.8733  1000   c
     IanStd  4.3132  4.41730  4.618690  4.47425  4.63185   8.4388  1000 a  
     JohnSe  4.3324  4.41875  4.640725  4.48330  4.64935   9.4435  1000 a  
 IanStdisNA  8.4976  8.99980 11.278352  9.34315 12.62075 120.8937  1000  b 
 JohnSeisNA  8.5138  8.96600 11.127796  9.35725 12.63630 118.4796  1000  b 
 AranStderr  4.3324  4.41995  4.634949  4.47440  4.62620  14.3511  1000 a  


library(ggplot2)
autoplot(mbm)

enter image description here

Switching a DIV background image with jQuery

This works on all current browsers on WinXP. Basically just checking what the current backgrond image is. If it's image1, show image2, otherwise show image1.

The jsapi stuff just loads jQuery from the Google CDN (easier for testing a misc file on the desktop).

The replace is for cross-browser compatibility (opera and ie add quotes to the url and firefox, chrome and safari remove quotes).

<html>
    <head>
        <script src="http://www.google.com/jsapi"></script>
        <script>
          google.load("jquery", "1.2.6");
          google.setOnLoadCallback(function() {
            var original_image = 'url(http://stackoverflow.com/Content/img/wmd/link.png)';
            var second_image = 'url(http://stackoverflow.com/Content/img/wmd/code.png)';

            $('.mydiv').click(function() {
                if ($(this).css('background-image').replace(/"/g, '') == original_image) {
                    $(this).css('background-image', second_image);
                } else {
                    $(this).css('background-image', original_image);
                }

                return false;
            });
          });
        </script>

        <style>
            .mydiv {
                background-image: url('http://stackoverflow.com/Content/img/wmd/link.png');
                width: 100px;
                height: 100px;
            }
        </style>
    </head>
    <body>
        <div class="mydiv">&nbsp;</div>
    </body>
</html>

gitignore all files of extension in directory

UPDATE: Take a look at @Joey's answer: Git now supports the ** syntax in patterns. Both approaches should work fine.


The gitignore(5) man page states:

Patterns read from a .gitignore file in the same directory as the path, or in any parent directory, with patterns in the higher level files (up to the toplevel of the work tree) being overridden by those in lower level files down to the directory containing the file.

What this means is that the patterns in a .gitignore file in any given directory of your repo will affect that directory and all subdirectories.

The pattern you provided

/public/static/**/*.js

isn't quite right, firstly because (as you correctly noted) the ** syntax is not used by Git. Also, the leading / anchors that pattern to the start of the pathname. (So, /public/static/*.js will match /public/static/foo.js but not /public/static/foo/bar.js.) Removing the leading / won't work either, matching paths like public/static/foo.js and foo/public/static/bar.js. EDIT: Just removing the leading slash won't work either — because the pattern still contains a slash, it is treated by Git as a plain, non-recursive shell glob (thanks @Joey Hoer for pointing this out).

As @ptyx suggested, what you need to do is create the file <repo>/public/static/.gitignore and include just this pattern:

*.js

There is no leading /, so it will match at any part of the path, and that pattern will only ever be applied to files in the /public/static directory and its subdirectories.

How do I create a unique ID in Java?

If you want short, human-readable IDs and only need them to be unique per JVM run:

private static long idCounter = 0;

public static synchronized String createID()
{
    return String.valueOf(idCounter++);
}    

Edit: Alternative suggested in the comments - this relies on under-the-hood "magic" for thread safety, but is more scalable and just as safe:

private static AtomicLong idCounter = new AtomicLong();

public static String createID()
{
    return String.valueOf(idCounter.getAndIncrement());
}

How to get week numbers from dates?

Base package

Using the function strftime passing the argument %V to obtain the week of the year as decimal number (01–53) as defined in ISO 8601. (More details in the documentarion: ?strftime)

strftime(c("2014-03-16", "2014-03-17","2014-03-18", "2014-01-01"), format = "%V")

Output:

[1] "11" "12" "12" "01"

What order are the Junit @Before/@After called?

You can use @BeforeClass annotation to assure that setup() is always called first. Similarly, you can use @AfterClass annotation to assure that tearDown() is always called last.

This is usually not recommended, but it is supported.

It's not exactly what you want - but it'll essentially keep your DB connection open the entire time your tests are running, and then close it once and for all at the end.

scroll up and down a div on button click using jquery

Where did it come from scrollBottom this is not a valid property it should be scrollTop and this can be positive(+) or negative(-) values to scroll down(+) and up(-), so you can change:

scrollBottom 

to this scrollTop:

$("#upClick").on("click", function () {
    scrolled = scrolled - 300;

    $(".cover").animate({
        scrollTop: scrolled
    });//^^^^^^^^------------------------------this one
});

Container is running beyond memory limits

There is a check placed at Yarn level for Virtual and Physical memory usage ratio. Issue is not only that VM doesn't have sufficient physical memory. But it is because Virtual memory usage is more than expected for given physical memory.

Note : This is happening on Centos/RHEL 6 due to its aggressive allocation of virtual memory.

It can be resolved either by :

  1. Disable virtual memory usage check by setting yarn.nodemanager.vmem-check-enabled to false;

  2. Increase VM:PM ratio by setting yarn.nodemanager.vmem-pmem-ratio to some higher value.

References :

https://issues.apache.org/jira/browse/HADOOP-11364

http://blog.cloudera.com/blog/2014/04/apache-hadoop-yarn-avoiding-6-time-consuming-gotchas/

Add following property in yarn-site.xml

 <property>
   <name>yarn.nodemanager.vmem-check-enabled</name>
    <value>false</value>
    <description>Whether virtual memory limits will be enforced for containers</description>
  </property>
 <property>
   <name>yarn.nodemanager.vmem-pmem-ratio</name>
    <value>4</value>
    <description>Ratio between virtual memory to physical memory when setting memory limits for containers</description>
  </property>

Should import statements always be at the top of a module?

It's interesting that not a single answer mentioned parallel processing so far, where it might be REQUIRED that the imports are in the function, when the serialized function code is what is being pushed around to other cores, e.g. like in the case of ipyparallel.

increment date by one month

Thanks Jason, your post was very helpful. I reformatted it and added more comments to help me understand it all. In case that helps anyone, I have posted it here:

function cycle_end_date($cycle_start_date, $months) {
    $cycle_start_date_object = new DateTime($cycle_start_date);

    //Find the date interval that we will need to add to the start date
    $date_interval = find_date_interval($months, $cycle_start_date_object);

    //Add this date interval to the current date (the DateTime class handles remaining complexity like year-ends)
    $cycle_end_date_object = $cycle_start_date_object->add($date_interval);

    //Subtract (sub) 1 day from date
    $cycle_end_date_object->sub(new DateInterval('P1D')); 

    //Format final date to Y-m-d
    $cycle_end_date = $cycle_end_date_object->format('Y-m-d'); 

    return $cycle_end_date;
}

//Find the date interval we need to add to start date to get end date
function find_date_interval($n_months, DateTime $cycle_start_date_object) {
    //Create new datetime object identical to inputted one
    $date_of_last_day_next_month = new DateTime($cycle_start_date_object->format('Y-m-d'));

    //And modify it so it is the date of the last day of the next month
    $date_of_last_day_next_month->modify('last day of +'.$n_months.' month');

    //If the day of inputted date (e.g. 31) is greater than last day of next month (e.g. 28)
    if($cycle_start_date_object->format('d') > $date_of_last_day_next_month->format('d')) {
        //Return a DateInterval object equal to the number of days difference
        return $cycle_start_date_object->diff($date_of_last_day_next_month);
    //Otherwise the date is easy and we can just add a month to it
    } else {
        //Return a DateInterval object equal to a period (P) of 1 month (M)
        return new DateInterval('P'.$n_months.'M');
    }
}

$cycle_start_date = '2014-01-31'; // select date in Y-m-d format
$n_months = 1; // choose how many months you want to move ahead
$cycle_end_date = cycle_end_date($cycle_start_date, $n_months); // output: 2014-07-02

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

There is a documentation in SLf4J site to resolve this. I followed that and added slf4j-simple-1.6.1.jar to my aplication along with slf4j-api-1.6.1.jar which i already had.This solved my problem

slf4j

CSS Selector that applies to elements with two classes

Chain both class selectors (without a space in between):

.foo.bar {
    /* Styles for element(s) with foo AND bar classes */
}

If you still have to deal with ancient browsers like IE6, be aware that it doesn't read chained class selectors correctly: it'll only read the last class selector (.bar in this case) instead, regardless of what other classes you list.

To illustrate how other browsers and IE6 interpret this, consider this CSS:

* {
    color: black;
}

.foo.bar {
    color: red;
}

Output on supported browsers is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Not selected, black text [3] -->

Output on IE6 is:

<div class="foo">Hello Foo</div>       <!-- Not selected, black text [1] -->
<div class="foo bar">Hello World</div> <!-- Selected, red text [2] -->
<div class="bar">Hello Bar</div>       <!-- Selected, red text [2] -->

Footnotes:

  • Supported browsers:
    1. Not selected as this element only has class foo.
    2. Selected as this element has both classes foo and bar.
    3. Not selected as this element only has class bar.

  • IE6:
    1. Not selected as this element doesn't have class bar.
    2. Selected as this element has class bar, regardless of any other classes listed.

How to align a div to the top of its parent but keeping its inline-block behaviour?

Use vertical-align:top; for the element you want at the top, as I have demonstrated on your jsfiddle.

http://www.brunildo.org/test/inline-block.html

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

Instead of specifying a deployment target in pod post install, you can delete the pod deployment target, which causes the deployment target to be inherited from the podfile platform.

You may need to run pod install for the effect to take place.

platform :ios, '12.0'

  post_install do |installer|
    installer.pods_project.targets.each do |target|
      target.build_configurations.each do |config|
        config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
      end
    end
  end

How do I declare and assign a variable on a single line in SQL

You've nearly got it:

DECLARE @myVariable nvarchar(max) = 'hello world';

See here for the docs

For the quotes, SQL Server uses apostrophes, not quotes:

DECLARE @myVariable nvarchar(max) = 'John said to Emily "Hey there Emily"';

Use double apostrophes if you need them in a string:

DECLARE @myVariable nvarchar(max) = 'John said to Emily ''Hey there Emily''';

Is it possible to get multiple values from a subquery?

In Oracle query

select a.x
            ,(select b.y || ',' || b.z
                from   b
                where  b.v = a.v
                and    rownum = 1) as multple_columns
from   a

can be transformed to:

select a.x, b1.y, b1.z
from   a, b b1
where  b1.rowid = (
       select b.rowid
       from   b
       where  b.v = a.v
       and    rownum = 1
)

Is useful when we want to prevent duplication for table A. Similarly, we can increase the number of tables:

.... where (b1.rowid,c1.rowid) = (select b.rowid,c.rowid ....

Disable password authentication for SSH

The one-liner to disable SSH password authentication:

sed -i 's/PasswordAuthentication yes/PasswordAuthentication no/g' /etc/ssh/sshd_config && service ssh restart

Detecting a mobile browser

Here is he full function

function isMobile(){
    return (/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino|android|ipad|playbook|silk/i.test(navigator.userAgent||navigator.vendor||window.opera)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test((navigator.userAgent||navigator.vendor||window.opera).substr(0,4)))
}

jQuery.noConflict();
jQuery(document).ready(function(){
    if(isMobile()) alert("Mobile"); else alert("Not Mobile");
});

Java properties UTF-8 encoding in Eclipse

This seems to work only for some characters ... including special characters for German, Portuguese, French. However, I ran into trouble with Russian, Hindi and Mandarin characters. These are not converted to Properties format 'native2ascii', instead get saved with ?? ?? ??
The only way I could get my app to display these characters correctly is by putting them in the properties file translated to UTF-8 format - as \u0915 instead of ?, or \u044F instead of ?. Any advice?

Aren't Python strings immutable? Then why does a + " " + b work?

We r just concatenate the two string values. We never change the value of (a). Just now (a) represent another memory block that has "dogdog" value. Because in the backend, one variable never represent two memory blocks at same time. The value of (a) before concatenation was "dog". But after that (a) represent the "dogdog", because now (a) in backend rep. the block that has "dogdog" value. And "dog" is rep. by (b) and "dog" isn't counted as garbage value until (b) represent the "dog".

The confusion is we represent the memory blocks(that contain data or info.) in backend with same variable name.

How to properly validate input values with React.JS?

You can use npm install --save redux-form

Im writing a simple email and submit button form, which validates email and submits form. with redux-form, form by default runs event.preventDefault() on html onSubmit action.

import React, {Component} from 'react';
import {reduxForm} from 'redux-form';

class LoginForm extends Component {
  onSubmit(props) {
    //do your submit stuff
  }


  render() {
    const {fields: {email}, handleSubmit} = this.props;

    return (
      <form onSubmit={handleSubmit(this.onSubmit.bind(this))}>
        <input type="text" placeholder="Email"
               className={`form-control ${email.touched && email.invalid ? 'has-error' : '' }`}
          {...email}
        />
          <span className="text-help">
            {email.touched ? email.error : ''}
          </span>
        <input type="submit"/>
      </form>
    );
  }
}

function validation(values) {
  const errors = {};
  const emailPattern = /(.+)@(.+){2,}\.(.+){2,}/;
  if (!emailPattern.test(values.email)) {
    errors.email = 'Enter a valid email';
  }

  return errors;
}

LoginForm = reduxForm({
  form: 'LoginForm',
  fields: ['email'],
  validate: validation
}, null, null)(LoginForm);

export default LoginForm;

How to Select Min and Max date values in Linq Query

dim mydate = from cv in mydata.t1s
  select cv.date1 asc

datetime mindata = mydate[0];

how to set ul/li bullet point color?

Apply the color to the li and set the span (or other child element) color to whatever color the text should be.

ul
{
    list-style-type: square;
}

ul > li
{
    color: green;
}

ul > li > span
{
    color: black;
}

JSFiddle

Convert a Unicode string to a string in Python (containing extra symbols)

file contain unicode-esaped string

\"message\": \"\\u0410\\u0432\\u0442\\u043e\\u0437\\u0430\\u0446\\u0438\\u044f .....\",

for me

 f = open("56ad62-json.log", encoding="utf-8")
 qq=f.readline() 

 print(qq)                          
 {"log":\"message\": \"\\u0410\\u0432\\u0442\\u043e\\u0440\\u0438\\u0437\\u0430\\u0446\\u0438\\u044f \\u043f\\u043e\\u043b\\u044c\\u0437\\u043e\\u0432\\u0430\\u0442\\u0435\\u043b\\u044f\"}

(qq.encode().decode("unicode-escape").encode().decode("unicode-escape")) 
# '{"log":"message": "??????????? ????????????"}\n'

How to return a custom object from a Spring Data JPA GROUP BY query

I do not like java type names in query strings and handle it with a specific constructor. Spring JPA implicitly calls constructor with query result in HashMap parameter:

@Getter
public class SurveyAnswerStatistics {
  public static final String PROP_ANSWER = "answer";
  public static final String PROP_CNT = "cnt";

  private String answer;
  private Long   cnt;

  public SurveyAnswerStatistics(HashMap<String, Object> values) {
    this.answer = (String) values.get(PROP_ANSWER);
    this.count  = (Long) values.get(PROP_CNT);
  }
}

@Query("SELECT v.answer as "+PROP_ANSWER+", count(v) as "+PROP_CNT+" FROM  Survey v GROUP BY v.answer")
List<SurveyAnswerStatistics> findSurveyCount();

Code needs Lombok for resolving @Getter

How to convert a multipart file to File?

if you don't want to use MultipartFile.transferTo(). You can write file like this

    val dir = File(filePackagePath)
    if (!dir.exists()) dir.mkdirs()

    val file = File("$filePackagePath${multipartFile.originalFilename}").apply {
        createNewFile()
    }

    FileOutputStream(file).use {
        it.write(multipartFile.bytes)
    }

What is the iPad user agent?

It seems to be general consensus that every mobile apple device, iphone, ipad, or ipod uses a user agent that contains both 'Mobile' and 'Safari'.

However, using the latest SDK (4.0.1) and reading the user agent on my rails server (using request.env["HTTP_USER_AGENT"]), we never get the 'Safari' part.

No matter whether the request is being made from the simulator or a real device, debug or release, it always looks something like this:

Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_1_2 like Mac OS X; de-de) AppleWebKit/528.18 (KHTML, like Gecko) Mobile/7D11"

Just no 'Safari'. :-( So we have to use the 'iPhone' part to be sure. That is something apple does not recommend doing.

How can I avoid running ActiveRecord callbacks?

One option is to have a separate model for such manipulations, using the same table:

class NoCallbacksModel < ActiveRecord::Base
  set_table_name 'table_name_of_model_that_has_callbacks'

  include CommonModelMethods # if there are
  :
  :

end

(Same approach might make things easier for bypassing validations)

Stephan

Filter dict to contain only certain keys?

Another option:

content = dict(k1='foo', k2='nope', k3='bar')
selection = ['k1', 'k3']
filtered = filter(lambda i: i[0] in selection, content.items())

But you get a list (Python 2) or an iterator (Python 3) returned by filter(), not a dict.

Hidden Features of Xcode

Build success/failure noise; from term:

defaults write com.apple.Xcode PBXBuildSuccessSound ~/Library/Sounds/metal\ stamp.wav
defaults write com.apple.Xcode PBXBuildFailureSound ~/Library/Sounds/Elephant

Is there Unicode glyph Symbol to represent "Search"

I'd recommend using http://shapecatcher.com/ to help search for unicode characters. It allows you to draw the shape you're after, and then lists the closest matches to that shape.

How to install 2 Anacondas (Python 2 and 3) on Mac OS

Edit!: Please be sure that you should have both Python installed on your computer.

Maybe my answer is late for you but I can help someone who has the same problem!

You don't have to download both Anaconda.

If you are using Spyder and Jupyter in Anaconda environmen and,

If you have already Anaconda 2 type in Terminal:

    python3 -m pip install ipykernel

    python3 -m ipykernel install --user

If you have already Anaconda 3 then type in terminal:

    python2 -m pip install ipykernel

    python2 -m ipykernel install --user

Then before use Spyder you can choose Python environment like below! Sometimes only you can see root and your new Python environment, so root is your first anaconda environment!

Anaconda spyder Python 2.7 or 3.5

Also this is Jupyter. You can choose python version like this!

Jupyter Notebook

I hope it will help.

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

In Windows server 2012. Go to ISS -> Modules -> Remove the ServiceModel3-0.

How to preserve aspect ratio when scaling image using one (CSS) dimension in IE6?

Well, I can think of a CSS hack that will resolve this issue.

You could add the following line in your CSS file:

* html .blog_list div.postbody img { width:75px; height: SpecifyHeightHere; } 

The above code will only be seen by IE6. The aspect ratio won't be perfect, but you could make it look somewhat normal. If you really wanted to make it perfect, you would need to write some javascript that would read the original picture width, and set the ratio accordingly to specify a height.

"message failed to fetch from registry" while trying to install any module

One thing that has worked for me with random npm install errors (where the package that errors out is different under different times (but same environment) is to use this:

npm cache clean

And then repeat the process. Then the process seems to go smoother and the real problem and error message will emerge, where you can fix it and then proceed.

This is based on experience of running npm install of a whole bunch of packages under a pretty bare Ubuntu installation inside a Docker instance. Sometimes there are build/make tools missing from the Ubuntu and the npm errors will not show the real problem until you clean the cache for some reason.

AngularJS access parent scope from child controller

I've just checked

$scope.$parent.someProperty

works for me.

and it will be

{{$parent.someProperty}}

for the view.

Windows recursive grep command-line

Recursive search for import word inside src folder:

> findstr /s import .\src\*

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

Liam's link looks great, but also check out pandas.Timedelta - looks like it plays nicely with NumPy's and Python's time deltas.

https://pandas.pydata.org/pandas-docs/stable/timedeltas.html

pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)

Difference between abstraction and encapsulation?

Abstraction and Encapsulation by using a single generalized example

------------------------------------------------------------------------------------------------------------------------------------

We all use calculator for calculation of complex problems !

image

How to get difference between two rows for a column field?

select t1.rowInt,t1.Value,t2.Value-t1.Value as diff
from (select * from myTable) as t1,
     (select * from myTable where rowInt!=1
      union all select top 1 rowInt=COUNT(*)+1,Value=0 from myTable) as t2
where t1.rowInt=t2.rowInt-1

Custom Date/Time formatting in SQL Server

You can use the following command in SQL server to make it:

select FORMAT(getdate(), N'yyyy-MM-ddThh:mm:ss')

DateTime2 vs DateTime in SQL Server

while there is increased precision with datetime2, some clients doesn't support date, time, or datetime2 and force you to convert to a string literal. Specifically Microsoft mentions "down level" ODBC, OLE DB, JDBC, and SqlClient issues with these data types and has a chart showing how each can map the type.

If value compatability over precision, use datetime

How to delete history of last 10 commands in shell?

Combining answers from above:

history -w vi ~/.bash_history history -r

Double border with different color

You can use outline with outline offset

<div class="double-border"></div>
.double-border{
background-color:#ccc;
outline: 1px solid #f00;
outline-offset: 3px;
}

Create dynamic URLs in Flask with url_for()

Refer to the Flask API document for flask.url_for()

Other sample snippets of usage for linking js or css to your template are below.

<script src="{{ url_for('static', filename='jquery.min.js') }}"></script>

<link rel=stylesheet type=text/css href="{{ url_for('static', filename='style.css') }}">

PHP Remove elements from associative array

Your array is quite strange : why not just use the key as index, and the value as... the value ?

Wouldn't it be a lot easier if your array was declared like this :

$array = array(
    1 => 'Awaiting for Confirmation', 
    2 => 'Asssigned', 
    3 => 'In Progress', 
    4 => 'Completed', 
    5 => 'Mark As Spam', 
);

That would allow you to use your values of key as indexes to access the array...

And you'd be able to use functions to search on the values, such as array_search() :

$indexCompleted = array_search('Completed', $array);
unset($array[$indexCompleted]);

$indexSpam = array_search('Mark As Spam', $array);
unset($array[$indexSpam]);

var_dump($array);

Easier than with your array, no ?



Instead, with your array that looks like this :

$array = array(
    array('key' => 1, 'value' => 'Awaiting for Confirmation'), 
    array('key' => 2, 'value' => 'Asssigned'), 
    array('key' => 3, 'value' => 'In Progress'), 
    array('key' => 4, 'value' => 'Completed'), 
    array('key' => 5, 'value' => 'Mark As Spam'), 
);

You'll have to loop over all items, to analyse the value, and unset the right items :

foreach ($array as $index => $data) {
    if ($data['value'] == 'Completed' || $data['value'] == 'Mark As Spam') {
        unset($array[$index]);
    }
}
var_dump($array);

Even if do-able, it's not that simple... and I insist : can you not change the format of your array, to work with a simpler key/value system ?

Best database field type for a URL

Most web servers have a URL length limit (which is why there is an error code for "URI too long"), meaning there is a practical upper size. Find the default length limit for the most popular web servers, and use the largest of them as the field's maximum size; it should be more than enough.

Count distinct value pairs in multiple columns in SQL

Another (probably not production-ready or recommended) method I just came up with is to concat the values to a string and count this string distinctively:

SELECT count(DISTINCT concat(id, name, address)) FROM mytable;

Can an html element have multiple ids?

Any ID assigned to a div element is unique.
However, you can assign multiple IDs "under", and not "to" a div element.
In that case, you have to represent those IDs as <span></span> IDs.

Say, you want two links in the same HTML page to point to the same div element in  the page.

The two different links
<p><a href="#exponentialEquationsCalculator">Exponential Equations</a></p>         

<p><a href="#logarithmicExpressionsCalculator"><Logarithmic Expressions</a></p>

Point to the same section of the page. 
<!-- Exponential / Logarithmic Equations Calculator -->
<div class="w3-container w3-card white w3-margin-bottom">      
   <span id="exponentialEquationsCalculator"></span>
   <span id="logarithmicEquationsCalculator"></span>
</div>

Golang read request body

Inspecting and mocking request body

When you first read the body, you have to store it so once you're done with it, you can set a new io.ReadCloser as the request body constructed from the original data. So when you advance in the chain, the next handler can read the same body.

One option is to read the whole body using ioutil.ReadAll(), which gives you the body as a byte slice.

You may use bytes.NewBuffer() to obtain an io.Reader from a byte slice.

The last missing piece is to make the io.Reader an io.ReadCloser, because bytes.Buffer does not have a Close() method. For this you may use ioutil.NopCloser() which wraps an io.Reader, and returns an io.ReadCloser, whose added Close() method will be a no-op (does nothing).

Note that you may even modify the contents of the byte slice you use to create the "new" body. You have full control over it.

Care must be taken though, as there might be other HTTP fields like content-length and checksums which may become invalid if you modify only the data. If subsequent handlers check those, you would also need to modify those too!

Inspecting / modifying response body

If you also want to read the response body, then you have to wrap the http.ResponseWriter you get, and pass the wrapper on the chain. This wrapper may cache the data sent out, which you can inspect either after, on on-the-fly (as the subsequent handlers write to it).

Here's a simple ResponseWriter wrapper, which just caches the data, so it'll be available after the subsequent handler returns:

type MyResponseWriter struct {
    http.ResponseWriter
    buf *bytes.Buffer
}

func (mrw *MyResponseWriter) Write(p []byte) (int, error) {
    return mrw.buf.Write(p)
}

Note that MyResponseWriter.Write() just writes the data to a buffer. You may also choose to inspect it on-the-fly (in the Write() method) and write the data immediately to the wrapped / embedded ResponseWriter. You may even modify the data. You have full control.

Care must be taken again though, as the subsequent handlers may also send HTTP response headers related to the response data –such as length or checksums– which may also become invalid if you alter the response data.

Full example

Putting the pieces together, here's a full working example:

func loginmw(handler http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        body, err := ioutil.ReadAll(r.Body)
        if err != nil {
            log.Printf("Error reading body: %v", err)
            http.Error(w, "can't read body", http.StatusBadRequest)
            return
        }

        // Work / inspect body. You may even modify it!

        // And now set a new body, which will simulate the same data we read:
        r.Body = ioutil.NopCloser(bytes.NewBuffer(body))

        // Create a response wrapper:
        mrw := &MyResponseWriter{
            ResponseWriter: w,
            buf:            &bytes.Buffer{},
        }

        // Call next handler, passing the response wrapper:
        handler.ServeHTTP(mrw, r)

        // Now inspect response, and finally send it out:
        // (You can also modify it before sending it out!)
        if _, err := io.Copy(w, mrw.buf); err != nil {
            log.Printf("Failed to send out response: %v", err)
        }
    })
}

Laravel 5.2 - pluck() method returns array

In the original example, why not use the select() method in your database query?

$name = DB::table('users')->where('name', 'John')->select("id");

This will be faster than using a PHP framework, for it'll utilize the SQL query to do the row selection for you. For ordinary collections, I don't believe this applies, but since you're using a database...

Larvel 5.3: Specifying a Select Clause

How to split data into trainset and testset randomly?

from sklearn.model_selection import train_test_split
import numpy

with open("datafile.txt", "rb") as f:
   data = f.read().split('\n')
   data = numpy.array(data)  #convert array to numpy type array

   x_train ,x_test = train_test_split(data,test_size=0.5)       #test_size=0.5(whole_data)

Message 'src refspec master does not match any' when pushing commits in Git

Permissions issue? Resolution: fork it

I got this error because I had no push permission to the repository so I had to fork it, And then I did execute pull, commit, and push commands once again on the forked repository.

How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?

object[,] valueArray = (object[,])excelRange.get_Value(XlRangeValueDataType.xlRangeValueDefault);

//Get the column names
for (int k = 0; k < valueArray.GetLength(1); )
{
    //add columns to the data table.
    dt.Columns.Add((string)valueArray[1,++k]);
}

//Load data into data table
object[] singleDValue = new object[valueArray.GetLength(1)];
//value array first row contains column names. so loop starts from 1 instead of 0
for (int i = 1; i < valueArray.GetLength(0); i++)
{
    Console.WriteLine(valueArray.GetLength(0) + ":" + valueArray.GetLength(1));
    for (int k = 0; k < valueArray.GetLength(1); )
    {
        singleDValue[k] = valueArray[i+1, ++k];
    }
    dt.LoadDataRow(singleDValue, System.Data.LoadOption.PreserveChanges);
}

How do I create an abstract base class in JavaScript?

Another thing you might want to enforce is making sure your abstract class is not instantiated. You can do that by defining a function that acts as FLAG ones set as the Abstract class constructor. This will then try to construct the FLAG which will call its constructor containing exception to be thrown. Example below:

(function(){

    var FLAG_ABSTRACT = function(__class){

        throw "Error: Trying to instantiate an abstract class:"+__class
    }

    var Class = function (){

        Class.prototype.constructor = new FLAG_ABSTRACT("Class");       
    }

    //will throw exception
    var  foo = new Class();

})()

How can I view live MySQL queries?

I've been looking to do the same, and have cobbled together a solution from various posts, plus created a small console app to output the live query text as it's written to the log file. This was important in my case as I'm using Entity Framework with MySQL and I need to be able to inspect the generated SQL.

Steps to create the log file (some duplication of other posts, all here for simplicity):

  1. Edit the file located at:

    C:\Program Files (x86)\MySQL\MySQL Server 5.5\my.ini
    

    Add "log=development.log" to the bottom of the file. (Note saving this file required me to run my text editor as an admin).

  2. Use MySql workbench to open a command line, enter the password.

    Run the following to turn on general logging which will record all queries ran:

    SET GLOBAL general_log = 'ON';
    
    To turn off:
    
    SET GLOBAL general_log = 'OFF';
    

    This will cause running queries to be written to a text file at the following location.

    C:\ProgramData\MySQL\MySQL Server 5.5\data\development.log
    
  3. Create / Run a console app that will output the log information in real time:

    Source available to download here

    Source:

    using System;
    using System.Configuration;
    using System.IO;
    using System.Threading;
    
    namespace LiveLogs.ConsoleApp
    {
      class Program
      {
        static void Main(string[] args)
        {
            // Console sizing can cause exceptions if you are using a 
            // small monitor. Change as required.
    
            Console.SetWindowSize(152, 58);
            Console.BufferHeight = 1500;
    
            string filePath = ConfigurationManager.AppSettings["MonitoredTextFilePath"];
    
            Console.Title = string.Format("Live Logs {0}", filePath);
    
            var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
    
            // Move to the end of the stream so we do not read in existing
            // log text, only watch for new text.
    
            fileStream.Position = fileStream.Length;
    
            StreamReader streamReader;
    
            // Commented lines are for duplicating the log output as it's written to 
            // allow verification via a diff that the contents are the same and all 
            // is being output.
    
            // var fsWrite = new FileStream(@"C:\DuplicateFile.txt", FileMode.Create);
            // var sw = new StreamWriter(fsWrite);
    
            int rowNum = 0;
    
            while (true)
            {
                streamReader = new StreamReader(fileStream);
    
                string line;
                string rowStr;
    
                while (streamReader.Peek() != -1)
                {
                    rowNum++;
    
                    line = streamReader.ReadLine();
                    rowStr = rowNum.ToString();
    
                    string output = String.Format("{0} {1}:\t{2}", rowStr.PadLeft(6, '0'), DateTime.Now.ToLongTimeString(), line);
    
                    Console.WriteLine(output);
    
                    // sw.WriteLine(output);
                }
    
                // sw.Flush();
    
                Thread.Sleep(500);
            }
        }
      }
    }
    

Select data from "show tables" MySQL query

I don't understand why you want to use SELECT * FROM as part of the statement.

12.5.5.30. SHOW TABLES Syntax

How to convert char to integer in C?

In the old days, when we could assume that most computers used ASCII, we would just do

int i = c[0] - '0';

But in these days of Unicode, it's not a good idea. It was never a good idea if your code had to run on a non-ASCII computer.

Edit: Although it looks hackish, evidently it is guaranteed by the standard to work. Thanks @Earwicker.

Notepad++ Setting for Disabling Auto-open Previous Files

For versions 6.6+ you need to uncheck "Remember the current session for next launch" on Settings -> Preferences -> Backup.

this is it in 6.6+

For older versions you need to uncheck "Remember the current session for next launch" on Settings -> Preferences.

this is it

How to use a jQuery plugin inside Vue

import jquery within <script> tag in your vue file.

I think this is the easiest way.

For example,

<script>
import $ from "jquery";

export default {
    name: 'welcome',
    mounted: function() {
        window.setTimeout(function() {
            $('.logo').css('opacity', 0);   
        }, 1000);
    } 
}
</script>

.htaccess: Invalid command 'RewriteEngine', perhaps misspelled or defined by a module not included in the server configuration

or defined by a module not included in the server configuration

Check to make sure you have mod_rewrite enabled.

From: https://webdevdoor.com/php/mod_rewrite-windows-apache-url-rewriting

  1. Find the httpd.conf file (usually you will find it in a folder called conf, config or something along those lines)
  2. Inside the httpd.conf file uncomment the line LoadModule rewrite_module modules/mod_rewrite.so (remove the pound '#' sign from in front of the line)
  3. Also find the line ClearModuleList is uncommented then find and make sure that the line AddModule mod_rewrite.c is not commented out.

If the LoadModule rewrite_module modules/mod_rewrite.so line is missing from the httpd.conf file entirely, just add it.

Sample command

To enable the module in a standard ubuntu do this:

a2enmod rewrite
systemctl restart apache2

Get the last three chars from any string - Java

Why not just String substr = word.substring(word.length() - 3)?

Update

Please make sure you check that the String is at least 3 characters long before calling substring():

if (word.length() == 3) {
  return word;
} else if (word.length() > 3) {
  return word.substring(word.length() - 3);
} else {
  // whatever is appropriate in this case
  throw new IllegalArgumentException("word has less than 3 characters!");
}

Autocomplete syntax for HTML or PHP in Notepad++. Not auto-close, autocompelete

Its supported in notepad++ 5.0+ but not enabled by default. You can enable it from settings -> preferences

How do I debug a stand-alone VBScript script?

This is for future readers. I found that the simplest method for me was to use Visual Studio -> Tools -> External Tools. More details in this answer.

Easier to use and good debugging tools.

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

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

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

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

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

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

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

Build and Install unsigned apk on device without the development server?

It can be possible to generate an unsigned apk version for testing purpose so you can run on your mobile.

Initially i got the red screen errors as most mentioned here. but i followed the same which was mentioned here and it worked for me.

On your console from working directory, run these four commands

react-native bundle --dev false --platform android --entry-file index.js --bundle-output ./android/app/build/intermediates/assets/debug/index.android.bundle --assets-dest ./android/app/build/intermediates/res/merged/debug

cd android

gradlew assembleDebug

gradlew assembleRelease

And then APK file will produce on : android\app\build\outputs\apk\debug\app-debug.apk

How to use OpenCV SimpleBlobDetector

You may store the parameters for the blob detector in a file, but this is not necessary. Example:

// set up the parameters (check the defaults in opencv's code in blobdetector.cpp)
cv::SimpleBlobDetector::Params params;
params.minDistBetweenBlobs = 50.0f;
params.filterByInertia = false;
params.filterByConvexity = false;
params.filterByColor = false;
params.filterByCircularity = false;
params.filterByArea = true;
params.minArea = 20.0f;
params.maxArea = 500.0f;
// ... any other params you don't want default value

// set up and create the detector using the parameters
cv::SimpleBlobDetector blob_detector(params);
// or cv::Ptr<cv::SimpleBlobDetector> detector = cv::SimpleBlobDetector::create(params)

// detect!
vector<cv::KeyPoint> keypoints;
blob_detector.detect(image, keypoints);

// extract the x y coordinates of the keypoints: 

for (int i=0; i<keypoints.size(); i++){
    float X = keypoints[i].pt.x; 
    float Y = keypoints[i].pt.y;
}

Copying an array of objects into another array in javascript

There are two important notes.

  1. Using array.concat() does not work using Angular 1.4.4 and jQuery 3.2.1 (this is my environment).
  2. The array.slice(0) is an object. So if you do something like newArray1 = oldArray.slice(0); newArray2 = oldArray.slice(0), the two new arrays will reference to just 1 array and changing one will affect the other.

Alternatively, using newArray1 = JSON.parse(JSON.stringify(old array)) will only copy the value, thus it creates a new array each time.

PostgreSQL psql terminal command

These are not command line args. Run psql. Manage to log into database (so pass the hostname, port, user and database if needed). And then write it in the psql program.

Example (below are two commands, write the first one, press enter, wait for psql to login, write the second):

psql -h host -p 5900 -U username database
\pset format aligned

How to check for palindrome using Python logic

maybe you can try this one:

list=input('enter a string:')

if (list==list[::-1]):
    print ("It is a palindrome")
else:
   print("it is not palindrome")

org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

if The given id is not exist in the DB ,then you may get this exception.

Exception in thread "main" org.springframework.orm.hibernate3.HibernateOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; nested exception is org.hibernate.StaleStateException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1

What’s the best way to get an HTTP response code from a URL?

Addressing @Niklas R's comment to @nickanor's answer:

from urllib.error import HTTPError
import urllib.request

def getResponseCode(url):
    try:
        conn = urllib.request.urlopen(url)
        return conn.getcode()
    except HTTPError as e:
        return e.code

How to get the excel file name / path in VBA

this is a simple alternative that gives all responses, Fullname, Path, filename.

Dim FilePath, FileOnly, PathOnly As String

FilePath = ThisWorkbook.FullName
FileOnly = ThisWorkbook.Name
PathOnly = Left(FilePath, Len(FilePath) - Len(FileOnly))

How to change the default port of mysql from 3306 to 3360

try changing the connection port to 8012

open xampp as administrator

Mysql config => my.ini change the port from 3306 to 8012

close and run it again I hope it will work.

How do I center an SVG in a div?

You can also do this:

<center>
<div style="width: 40px; height: 40px;">
    <svg class="sqs-svg-icon--social" viewBox="0 0 64 64">
        <use class="sqs-use--icon" xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="#twitter-icon">
            <svg id="twitter-icon" viewBox="0 0 64 64" width="100%" height="100%">
                <path
                    d="M48,22.1c-1.2,0.5-2.4,0.9-3.8,1c1.4-0.8,2.4-2.1,2.9-3.6c-1.3,0.8-2.7,1.3-4.2,1.6 C41.7,19.8,40,19,38.2,19c-3.6,0-6.6,2.9-6.6,6.6c0,0.5,0.1,1,0.2,1.5c-5.5-0.3-10.3-2.9-13.5-6.9c-0.6,1-0.9,2.1-0.9,3.3 c0,2.3,1.2,4.3,2.9,5.5c-1.1,0-2.1-0.3-3-0.8c0,0,0,0.1,0,0.1c0,3.2,2.3,5.8,5.3,6.4c-0.6,0.1-1.1,0.2-1.7,0.2c-0.4,0-0.8,0-1.2-0.1 c0.8,2.6,3.3,4.5,6.1,4.6c-2.2,1.8-5.1,2.8-8.2,2.8c-0.5,0-1.1,0-1.6-0.1c2.9,1.9,6.4,2.9,10.1,2.9c12.1,0,18.7-10,18.7-18.7 c0-0.3,0-0.6,0-0.8C46,24.5,47.1,23.4,48,22.1z"
                    />
            </svg>
        </use>
    </svg>
</div>
</center>

When is std::weak_ptr useful?

I see std::weak_ptr<T> as a handle to a std::shared_ptr<T>: It allows me to get the std::shared_ptr<T> if it still exists, but it will not extend its lifetime. There are several scenarios when such point of view is useful:

// Some sort of image; very expensive to create.
std::shared_ptr< Texture > texture;

// A Widget should be able to quickly get a handle to a Texture. On the
// other hand, I don't want to keep Textures around just because a widget
// may need it.

struct Widget {
    std::weak_ptr< Texture > texture_handle;
    void render() {
        if (auto texture = texture_handle.get(); texture) {
            // do stuff with texture. Warning: `texture`
            // is now extending the lifetime because it
            // is a std::shared_ptr< Texture >.
        } else {
            // gracefully degrade; there's no texture.
        }
    }
};

Another important scenario is to break cycles in data structures.

// Asking for trouble because a node owns the next node, and the next node owns
// the previous node: memory leak; no destructors automatically called.
struct Node {
    std::shared_ptr< Node > next;
    std::shared_ptr< Node > prev;
};

// Asking for trouble because a parent owns its children and children own their
// parents: memory leak; no destructors automatically called.
struct Node {
    std::shared_ptr< Node > parent;
    std::shared_ptr< Node > left_child;
    std::shared_ptr< Node > right_child;
};

// Better: break dependencies using a std::weak_ptr (but not best way to do it;
// see Herb Sutter's talk).
struct Node {
    std::shared_ptr< Node > next;
    std::weak_ptr< Node > prev;
};

// Better: break dependencies using a std::weak_ptr (but not best way to do it;
// see Herb Sutter's talk).
struct Node {
    std::weak_ptr< Node > parent;
    std::shared_ptr< Node > left_child;
    std::shared_ptr< Node > right_child;
};

Herb Sutter has an excellent talk that explains the best use of language features (in this case smart pointers) to ensure Leak Freedom by Default (meaning: everything clicks in place by construction; you can hardly screw it up). It is a must watch.

Excel Date to String conversion

In some contexts using a ' character beforehand will work, but if you save to CSV and load again this is impossible.

'01/01/2010 14:30:00

Is there a way to comment out markup in an .ASPX page?

Another way assuming it's not server side code you want to comment out is...

<asp:panel runat="server" visible="false">
    html here
</asp:panel>

How to save LogCat contents to file?

If you are in the console window for the device and if you use Teraterm, then from the Menu do a File | Log and it will automatically save to file.

git - Server host key not cached

Working environment:

  • Windows 10
  • git
  • putty

First: Delete putty known_hosts in registy according to the Regedit.
Then: Executing the command %GIT_SSH% user@hostname in Window's cmd solves the problem.

Hope it helps you all.

Safari 3rd party cookie iframe trick no longer working?

Safari now blocks all third party cookies. You can only use the Storage API to try to get user access to their third party cookies.

https://www.infoq.com/news/2020/04/safari-third-party-cookies-block/

What is event bubbling and capturing?

Description:

quirksmode.org has a nice description of this. In a nutshell (copied from quirksmode):

Event capturing

When you use event capturing

               | |
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  \ /          |     |
|   -------------------------     |
|        Event CAPTURING          |
-----------------------------------

the event handler of element1 fires first, the event handler of element2 fires last.

Event bubbling

When you use event bubbling

               / \
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  | |          |     |
|   -------------------------     |
|        Event BUBBLING           |
-----------------------------------

the event handler of element2 fires first, the event handler of element1 fires last.


What to use?

It depends on what you want to do. There is no better. The difference is the order of the execution of the event handlers. Most of the time it will be fine to fire event handlers in the bubbling phase but it can also be necessary to fire them earlier.

Python Remove last 3 characters of a string

Aren't you performing the operations in the wrong order? You requirement seems to be foo[:-3].replace(" ", "").upper()

Find and replace - Add carriage return OR Newline

If you want to avoid the hassle of escaping the special characters in your search and replacement string when using regular expressions, do the following steps:

  1. Search for your original string, and replace it with "UniqueString42", with regular expressions off.
  2. Search for "UniqueString42" and replace it with "UniqueString42\nUniqueString1337", with regular expressions on
  3. Search for "UniqueString42" and replace it with the first line of your replacement (often your original string), with regular expressions off.
  4. Search for "UniqueString42" and replace it with the second line of your replacement, with regular expressions off.

Note that even if you want to manually pich matches for the first search and replace, you can safely use "replace all" for the three last steps.

Example

For example, if you want to replace this:

public IFoo SomeField { get { return this.SomeField; } }

with that:

public IFoo Foo { get { return this.MyFoo; } }
public IBar Bar { get { return this.MyBar; } }

You would do the following substitutions:

  1. public IFoo SomeField { get { return this.SomeField; } } ? XOXOXOXO (regex off).
  2. XOXOXOXO ? XOXOXOXO\nHUHUHUHU (regex on).
  3. XOXOXOXO ? public IFoo Foo { get { return this.MyFoo; } } (regex off).
  4. HUHUHUHU ? public IFoo Bar { get { return this.MyBar; } } (regex off).

How to get Client location using Google Maps API v3?

Try this :)

    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">
    function initialize() {
        var loc = {};
        var geocoder = new google.maps.Geocoder();
        if(google.loader.ClientLocation) {
            loc.lat = google.loader.ClientLocation.latitude;
            loc.lng = google.loader.ClientLocation.longitude;

            var latlng = new google.maps.LatLng(loc.lat, loc.lng);
            geocoder.geocode({'latLng': latlng}, function(results, status) {
                if(status == google.maps.GeocoderStatus.OK) {
                    alert(results[0]['formatted_address']);
                };
            });
        }
    }

    google.load("maps", "3.x", {other_params: "sensor=false", callback:initialize});

    </script>

How to get last inserted id?

If you're using executeScalar:

cmd.ExecuteScalar();
result_id=cmd.LastInsertedId.ToString();

Post to another page within a PHP script

index.php

$url = 'http://[host]/test.php';
$json = json_encode(['name' => 'Jhonn', 'phone' => '128000000000']);

$options = ['http' => [
    'method' => 'POST',
    'header' => 'Content-type:application/json',
    'content' => $json
]];

$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);

test.php

$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
echo $data['name']; // Jhonn

How to iterate std::set?

One more thing that might be useful for beginners is , since std::set is not allocated with contiguous memory chunks , if someone want to iterate till kth element normal way will not work. example:

std::vector<int > vec{1,2,3,4,5};
int k=3;
for(auto itr=vec.begin();itr<vec.begin()+k;itr++) cout<<*itr<<" ";

std::unordered_set<int > s{1,2,3,4,5};
int k=3;
int index=0;
auto itr=s.begin();
while(true){
   if(index==k) break;
   cout<<*itr++<<" ";
   index++;
}

Java parsing XML document gives "Content not allowed in prolog." error

Make sure there's no hidden whitespace at the start of your XML file. Also maybe include encoding="UTF-8" (or 16? No clue) in the node.

estimating of testing effort as a percentage of development time

Gartner in Oct 2006 states that testing typically consumes between 10% and 35% of work on a system integration project. I assume that it applies to the waterfall method. This is quite a wide range - but there are many dependencies on the amount of customisations to a standard product and the number of systems to be integrated.

What is Bootstrap?

Bootstrap is an HTML, CSS, JS framework with many components that let you create beautiful and modern web sites or web applications very fast.

The following websites contain examples, elements and reusable components that you can integrate into your project using bootstrap framework

bootsnipp.com

startbootstrap.com

bootdey.com

jQuery changing font family and font size

If you only want to change the font in the TEXTAREA then you only need to change the changeFont() function in the original code to:

function changeFont(_name) {
    document.getElementById("mytextarea").style.fontFamily = _name;
}

Then selecting a font will change on the font only in the TEXTAREA.

How can I save multiple documents concurrently in Mongoose/Node.js?

Here is another way without using additional libraries (no error checking included)

function saveAll( callback ){
  var count = 0;
  docs.forEach(function(doc){
      doc.save(function(err){
          count++;
          if( count == docs.length ){
             callback();
          }
      });
  });
}

Cannot install NodeJs: /usr/bin/env: node: No such file or directory

if you are able to access node on ubuntu terminal using nodejs command,then this problem can be simply solved using -creating a symbolic link of nodejs and node using

ln -s /usr/bin/nodejs /usr/bin/node

and this may solve the problem

Rollback a Git merge

Reverting a merge commit has been exhaustively covered in other questions. When you do a fast-forward merge, the second one you describe, you can use git reset to get back to the previous state:

git reset --hard <commit_before_merge>

You can find the <commit_before_merge> with git reflog, git log, or, if you're feeling the moxy (and haven't done anything else): git reset --hard HEAD@{1}

HTML / CSS Popup div on text click

DEMO

In the content area you can provide whatever you want to display in it.

_x000D_
_x000D_
.black_overlay {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 0%;_x000D_
  left: 0%;_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  background-color: black;_x000D_
  z-index: 1001;_x000D_
  -moz-opacity: 0.8;_x000D_
  opacity: .80;_x000D_
  filter: alpha(opacity=80);_x000D_
}_x000D_
.white_content {_x000D_
  display: none;_x000D_
  position: absolute;_x000D_
  top: 25%;_x000D_
  left: 25%;_x000D_
  width: 50%;_x000D_
  height: 50%;_x000D_
  padding: 16px;_x000D_
  border: 16px solid orange;_x000D_
  background-color: white;_x000D_
  z-index: 1002;_x000D_
  overflow: auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>LIGHTBOX EXAMPLE</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <p>This is the main content. To display a lightbox click <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='block';document.getElementById('fade').style.display='block'">here</a>_x000D_
  </p>_x000D_
  <div id="light" class="white_content">This is the lightbox content. <a href="javascript:void(0)" onclick="document.getElementById('light').style.display='none';document.getElementById('fade').style.display='none'">Close</a>_x000D_
  </div>_x000D_
  <div id="fade" class="black_overlay"></div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Browse files and subfolders in Python

I had a similar thing to work on, and this is how I did it.

import os

rootdir = os.getcwd()

for subdir, dirs, files in os.walk(rootdir):
    for file in files:
        #print os.path.join(subdir, file)
        filepath = subdir + os.sep + file

        if filepath.endswith(".html"):
            print (filepath)

Hope this helps.

Adding a simple spacer to twitter bootstrap

My approach. Tricky, but works well for me

<p>&nbsp;</p>

Use sudo with password as parameter

echo -e "YOURPASSWORD\n" | sudo -S yourcommand

configuring project ':app' failed to find Build Tools revision

I had c++ codes in my project but i didn't have NDK installed, installing it solved the problem

Using HTML5/Canvas/JavaScript to take in-browser screenshots

JavaScript can read the DOM and render a fairly accurate representation of that using canvas. I have been working on a script which converts HTML into a canvas image. Decided today to make an implementation of it into sending feedbacks like you described.

The script allows you to create feedback forms which include a screenshot, created on the client's browser, along with the form. The screenshot is based on the DOM and as such may not be 100% accurate to the real representation as it does not make an actual screenshot, but builds the screenshot based on the information available on the page.

It does not require any rendering from the server, as the whole image is created on the client's browser. The HTML2Canvas script itself is still in a very experimental state, as it does not parse nearly as much of the CSS3 attributes I would want it to, nor does it have any support to load CORS images even if a proxy was available.

Still quite limited browser compatibility (not because more couldn't be supported, just haven't had time to make it more cross browser supported).

For more information, have a look at the examples here:

http://hertzen.com/experiments/jsfeedback/

edit The html2canvas script is now available separately here and some examples here.

edit 2 Another confirmation that Google uses a very similar method (in fact, based on the documentation, the only major difference is their async method of traversing/drawing) can be found in this presentation by Elliott Sprehn from the Google Feedback team: http://www.elliottsprehn.com/preso/fluentconf/

Could not find an implementation of the query pattern

Make sure these references are included:

  • System.Data.Linq
  • System.Data.Entity

Then add the using statement

using System.Linq;

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

How to get MD5 sum of a string using python?

Have you tried using the MD5 implementation in hashlib? Note that hashing algorithms typically act on binary data rather than text data, so you may want to be careful about which character encoding is used to convert from text to binary data before hashing.

The result of a hash is also binary data - it looks like Flickr's example has then been converted into text using hex encoding. Use the hexdigest function in hashlib to get this.

pandas python how to count the number of records or rows in a dataframe

Regards to your question... counting one Field? I decided to make it a question, but I hope it helps...

Say I have the following DataFrame

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.normal(0, 1, (5, 2)), columns=["A", "B"])

You could count a single column by

df.A.count()
#or
df['A'].count()

both evaluate to 5.

The cool thing (or one of many w.r.t. pandas) is that if you have NA values, count takes that into consideration.

So if I did

df['A'][1::2] = np.NAN
df.count()

The result would be

 A    3
 B    5

What are pipe and tap methods in Angular tutorial?

You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:

  /**
   * Used to stitch together functional operators into a chain.
   * @method pipe
   * @return {Observable} the Observable result of all of the operators having
   * been called in the order they were passed in.
   *
   * @example
   *
   * import { map, filter, scan } from 'rxjs/operators';
   *
   * Rx.Observable.interval(1000)
   *   .pipe(
   *     filter(x => x % 2 === 0),
   *     map(x => x + x),
   *     scan((acc, x) => acc + x)
   *   )
   *   .subscribe(x => console.log(x))
   */

In brief:

Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan(), but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe() to make a chain of those operators (see example above).

Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do(). You can think of it as if observable was an array over time, then tap() would be an equivalent to Array.forEach().

How to convert a SVG to a PNG with ImageMagick?

On Linux with Inkscape 1.0 to convert from svg to png need to use

inkscape -w 1024 -h 1024 input.svg --export-file output.png

not

inkscape -w 1024 -h 1024 input.svg --export-filename output.png

Refused to apply inline style because it violates the following Content Security Policy directive

Another method is to use the CSSOM (CSS Object Model), via the style property on a DOM node.

var myElem = document.querySelector('.my-selector');
myElem.style.color = 'blue';

More details on CSSOM: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement.style

As mentioned by others, enabling unsafe-line for css is another method to solve this.

How do Common Names (CN) and Subject Alternative Names (SAN) work together?

This depends on implementation, but the general rule is that the domain is checked against all SANs and the common name. If the domain is found there, then the certificate is ok for connection.

RFC 5280, section 4.1.2.6 says "The subject name MAY be carried in the subject field and/or the subjectAltName extension". This means that the domain name must be checked against both SubjectAltName extension and Subject property (namely it's common name parameter) of the certificate. These two places complement each other, and not duplicate it. And SubjectAltName is a proper place to put additional names, such as www.domain.com or www2.domain.com

Update: as per RFC 6125, published in 2011, the validator must check SAN first, and if SAN exists, then CN should not be checked. Note that RFC 6125 is relatively recent and there still exist certificates and CAs that issue certificates, which include the "main" domain name in CN and alternative domain names in SAN. I.e. by excluding CN from validation if SAN is present, you can deny some otherwise valid certificate.

How can I add a column that doesn't allow nulls in a Postgresql database?

You have to set a default value.

ALTER TABLE mytable ADD COLUMN mycolumn character varying(50) NOT NULL DEFAULT 'foo';

... some work (set real values as you want)...

ALTER TABLE mytable ALTER COLUMN mycolumn DROP DEFAULT;

How to import local packages without gopath

Go dependency management summary:

  • vgo if your go version is: x >= go 1.11
  • dep or vendor if your go version is: go 1.6 >= x < go 1.11
  • Manually if your go version is: x < go 1.6

Edit 3: Go 1.11 has a feature vgo which will replace dep.

To use vgo, see Modules documentation. TLDR below:

export GO111MODULE=on
go mod init
go mod vendor # if you have vendor/ folder, will automatically integrate
go build

This method creates a file called go.mod in your projects directory. You can then build your project with go build. If GO111MODULE=auto is set, then your project cannot be in $GOPATH.


Edit 2: The vendoring method is still valid and works without issue. vendor is largely a manual process, because of this dep and vgo were created.


Edit 1: While my old way works it's not longer the "correct" way to do it. You should be using vendor capabilities, vgo, or dep (for now) that are enabled by default in Go 1.6; see. You basically add your "external" or "dependent" packages within a vendor directory; upon compilation the compiler will use these packages first.


Found. I was able import local package with GOPATH by creating a subfolder of package1 and then importing with import "./package1" in binary1.go and binary2.go scripts like this :

binary1.go

...
import (
        "./package1"
      )
...

So my current directory structure looks like this:

myproject/
+-- binary1.go
+-- binary2.go
+-- package1/
¦   +-- package1.go
+-- package2.go

I should also note that relative paths (at least in go 1.5) also work; for example:

import "../packageX"

Add onclick event to newly added element in JavaScript

you can't assign an event by string. Use that:

elemm.onclick = function(){ alert('blah'); };

How to use basic authorization in PHP curl

Can you try this,

 $ch = curl_init($url);
 ...
 curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);  
 ...

REF: http://php.net/manual/en/function.curl-setopt.php

RestSharp JSON Parameter Posting

In the current version of RestSharp (105.2.3.0) you can add a JSON object to the request body with:

request.AddJsonBody(new { A = "foo", B = "bar" });

This method sets content type to application/json and serializes the object to a JSON string.

What's the difference between "2*2" and "2**2" in Python?

A double asterisk means to the power of. A single asterisk means multiplied by. 22 is the same as 2x2 which is why both answers came out as 4.

java.net.ConnectException :connection timed out: connect?

If you're pointing the config at a domain (eg fabrikam.com), do an NSLOOKUP to ensure all the responding IPs are valid, and can be connected to on port 389:

NSLOOKUP fabrikam.com

Test-NetConnection <IP returned from NSLOOKUP> -port 389

git push to specific branch

If your Local branch and remote branch is the same name then you can just do it:

git push origin branchName

When your local and remote branch name is different then you can just do it:

git push origin localBranchName:remoteBranchName

Github "Updates were rejected because the remote contains work that you do not have locally."

I followed these steps:

Pull the master:

git pull origin master

This will sync your local repo with the Github repo. Add your new file and then:

git add .

Commit the changes:

git commit -m "adding new file  Xyz"

Finally, push the origin master:

git push origin master

Refresh your Github repo, you will see the newly added files.

Resolve host name to an ip address

Try tracert to resolve the hostname. IE you have Ip address 8.8.8.8 so you would use; tracert 8.8.8.8

Read a file line by line with VB.NET

Replaced the reader declaration with this one and now it works!

Dim reader As New StreamReader(filetoimport.Text, Encoding.Default)

Encoding.Default represents the ANSI code page that is set under Windows Control Panel.

Flutter: Run method on Widget build complete

There are 3 possible ways:

1) WidgetsBinding.instance.addPostFrameCallback((_) => yourFunc(context));

2) Future.delayed(Duration.zero, () => yourFunc(context));

3) Timer.run(() => yourFunc(context));

As for context, I needed it for use in Scaffold.of(context) after all my widgets were rendered.

But in my humble opinion, the best way to do it is this:

void main() async {
  WidgetsFlutterBinding.ensureInitialized(); //all widgets are rendered here
  await yourFunc();
  runApp( MyApp() );
}

The differences between initialize, define, declare a variable

Declaration

Declaration, generally, refers to the introduction of a new name in the program. For example, you can declare a new function by describing it's "signature":

void xyz();

or declare an incomplete type:

class klass;
struct ztruct;

and last but not least, to declare an object:

int x;

It is described, in the C++ standard, at §3.1/1 as:

A declaration (Clause 7) may introduce one or more names into a translation unit or redeclare names introduced by previous declarations.

Definition

A definition is a definition of a previously declared name (or it can be both definition and declaration). For example:

int x;
void xyz() {...}
class klass {...};
struct ztruct {...};
enum { x, y, z };

Specifically the C++ standard defines it, at §3.1/1, as:

A declaration is a definition unless it declares a function without specifying the function’s body (8.4), it contains the extern specifier (7.1.1) or a linkage-specification25 (7.5) and neither an initializer nor a function- body, it declares a static data member in a class definition (9.2, 9.4), it is a class name declaration (9.1), it is an opaque-enum-declaration (7.2), it is a template-parameter (14.1), it is a parameter-declaration (8.3.5) in a function declarator that is not the declarator of a function-definition, or it is a typedef declaration (7.1.3), an alias-declaration (7.1.3), a using-declaration (7.3.3), a static_assert-declaration (Clause 7), an attribute- declaration (Clause 7), an empty-declaration (Clause 7), or a using-directive (7.3.4).

Initialization

Initialization refers to the "assignment" of a value, at construction time. For a generic object of type T, it's often in the form:

T x = i;

but in C++ it can be:

T x(i);

or even:

T x {i};

with C++11.

Conclusion

So does it mean definition equals declaration plus initialization?

It depends. On what you are talking about. If you are talking about an object, for example:

int x;

This is a definition without initialization. The following, instead, is a definition with initialization:

int x = 0;

In certain context, it doesn't make sense to talk about "initialization", "definition" and "declaration". If you are talking about a function, for example, initialization does not mean much.

So, the answer is no: definition does not automatically mean declaration plus initialization.

How do I configure Maven for offline development?

Before going offline you have to make sure that everything is in your local repo, which is required while working offline. Running "mvn dependency:go-offline" for the project(s)/pom(s), you intend to work on, will reduce the efforts to achieve this.

But it´s usually not the whole story, because dependency:go-offline will only download the "bare build" plugins (go-offline / resolve-plugins does not resolve all plugin dependencies). So you have to find a way to download deploy / test / site plugins (and maybe others) and their dependencies into your repo.

Furthermore dependency:go-offline does not download the pom´s artifact itself, so you have to dependency:copy it if required.

Sometimes - as MaDa wrote - you do not know, what you will need, while being offline, which makes it pretty impossible to have a "sufficient" repo.

Anyway having a properly filled repo you only have to add "<offline>true</offline>" to Maven´s settings.xml to go offline.

Do not change the Maven profile (id) you used to fill your repo, while being offline. Maven recognizes the downloaded artifacts in its metadata with an "identity", which is bound to the profile id.

What's is the difference between include and extend in use case diagram?

To simplify,

for include

  1. When the base use case is executed, the included use case is executed EVERYTIME.
  2. The base use case required the completion of the included use case in order to be completed.

a typical example: between login and verify password

(login) --- << include >> ---> (verify password)

for the login process to success, "verify password" must be successful as well.


for extend

  1. When the base use case is executed, the extended use case is executed only SOMETIMES
  2. The extended use case will happen only when certain criteria are met.

a typical example: between login and show error message (only happened sometimes)

(login) <--- << extend >> --- (show error message)

"show error message" only happens sometimes when the login process failed.

How to Delete node_modules - Deep Nested Folder in Windows

On Windows my go to solution is using the rmdir command:

rd /S .\node_modules\

If it fails the first time -- try one more time. Also check if you have running scripts currently using the modules (npm run serve or similar).

Vba macro to copy row from table if value in table meets condition

Selects are slow and unnescsaary. The following code will be far faster:

Sub CopyRowsAcross() 
Dim i As Integer 
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Sheets("Sheet1") 
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Sheets("Sheet2") 

For i = 2 To ws1.Range("B65536").End(xlUp).Row 
    If ws1.Cells(i, 2) = "Your Critera" Then ws1.Rows(i).Copy ws2.Rows(ws2.Cells(ws2.Rows.Count, 2).End(xlUp).Row + 1) 
Next i 
End Sub 

How to add (vertical) divider to a horizontal LinearLayout?

use this for horizontal divider

<View
    android:layout_width="1dp"
    android:layout_height="match_parent"
    android:background="@color/honeycombish_blue" />

and this for vertical divider

<View
    android:layout_width="match_parent"
    android:layout_height="1dp"
    android:background="@color/honeycombish_blue" />

OR if you can use the LinearLayout divider, for horizontal divider

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <size android:height="1dp"/>
    <solid android:color="#f6f6f6"/>
</shape>

and in LinearLayout

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="@drawable/divider"
    android:orientation="vertical"
    android:showDividers="middle" >

If you want to user vertical divider then in place of android:height="1dp" in shape use android:width="1dp"

Tip: Don't forget the android:showDividers item.

HTML5 Canvas and Anti-aliasing

Anti-aliasing cannot be turned on or off, and is controlled by the browser.

Can I turn off antialiasing on an HTML <canvas> element?

Pro JavaScript programmer interview questions (with answers)

Basic JS programmming

  • Scope of variable
  • What is Associative Array? How do we use it?

OOPS JS

  • Difference between Classic Inheritance and Prototypical Inheritance
  • What is difference between private variable, public variable and static variable? How we achieve this in JS?
  • How to add/remove properties to object in run time?
  • How to achieve inheritance ?
  • How to extend built-in objects?
  • Why extending array is bad idea?

DOM and JS

  • Difference between browser detection and feature detection
  • DOM Event Propagation
  • Event Delegation
  • Event bubbling V/s Event Capturing

Misc

  • Graceful Degradation V/s Progressive Enhancement

SET NAMES utf8 in MySQL?

From the manual:

SET NAMES indicates what character set the client will use to send SQL statements to the server.

More elaborately, (and once again, gratuitously lifted from the manual):

SET NAMES indicates what character set the client will use to send SQL statements to the server. Thus, SET NAMES 'cp1251' tells the server, “future incoming messages from this client are in character set cp1251.” It also specifies the character set that the server should use for sending results back to the client. (For example, it indicates what character set to use for column values if you use a SELECT statement.)