Programs & Examples On #Recursive datastructures

What do I use for a max-heap implementation in Python?

The easiest and ideal solution

Multiply the values by -1

There you go. All the highest numbers are now the lowest and vice versa.

Just remember that when you pop an element to multiply it with -1 in order to get the original value again.

Regex match entire words only

Using \b can yield surprising results. You would be better off figuring out what separates a word from its definition and incorporating that information into your pattern.

#!/usr/bin/perl

use strict; use warnings;

use re 'debug';

my $str = 'S.P.E.C.T.R.E. (Special Executive for Counter-intelligence,
Terrorism, Revenge and Extortion) is a fictional global terrorist
organisation';

my $word = 'S.P.E.C.T.R.E.';

if ( $str =~ /\b(\Q$word\E)\b/ ) {
    print $1, "\n";
}

Output:

Compiling REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b"
Final program:
   1: BOUND (2)
   2: OPEN1 (4)
   4:   EXACT  (9)
   9: CLOSE1 (11)
  11: BOUND (12)
  12: END (0)
anchored "S.P.E.C.T.R.E." at 0 (checking anchored) stclass BOUND minlen 14
Guessing start of match in sv for REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b" against "S.P
.E.C.T.R.E. (Special Executive for Counter-intelligence,"...
Found anchored substr "S.P.E.C.T.R.E." at offset 0...
start_shift: 0 check_at: 0 s: 0 endpos: 1
Does not contradict STCLASS...
Guessed: match at offset 0
Matching REx "\b(S\.P\.E\.C\.T\.R\.E\.)\b" against "S.P.E.C.T.R.E. (Special Exec
utive for Counter-intelligence,"...
   0           |  1:BOUND(2)
   0           |  2:OPEN1(4)
   0           |  4:EXACT (9)
  14      |  9:CLOSE1(11)
  14      | 11:BOUND(12)
                                  failed...
Match failed
Freeing REx: "\b(S\.P\.E\.C\.T\.R\.E\.)\b"

What is the difference between Jupyter Notebook and JupyterLab?

Jupyter Notebook is a web-based interactive computational environment for creating Jupyter notebook documents. It supports several languages like Python (IPython), Julia, R etc. and is largely used for data analysis, data visualization and further interactive, exploratory computing.

JupyterLab is the next-generation user interface including notebooks. It has a modular structure, where you can open several notebooks or files (e.g. HTML, Text, Markdowns etc) as tabs in the same window. It offers more of an IDE-like experience.

For a beginner I would suggest starting with Jupyter Notebook as it just consists of a filebrowser and an (notebook) editor view. It might be easier to use. If you want more features, switch to JupyterLab. JupyterLab offers much more features and an enhanced interface, which can be extended through extensions: JupyterLab Extensions (GitHub)

Getting Git to work with a proxy server - fails with "Request timed out"

Set a system variable named http_proxy with the value of ProxyServer:Port. That is the simplest solution. Respectively, use https_proxy as daefu pointed out in the comments.

Setting gitproxy (as sleske mentions) is another option, but that requires a "command", which is not as straightforward as the above solution.

References: http://bardofschool.blogspot.com/2008/11/use-git-behind-proxy.html

What does the "no version information available" error from linux dynamic linker mean?

How are you compiling your app? What compiler flags?

In my experience, when targeting the vast realm of Linux systems out there, build your packages on the oldest version you are willing to support, and because more systems tend to be backwards compatible, your app will continue to work. Actually this is the whole reason for library versioning - ensuring backward compatibility.

Adding +1 to a variable inside a function

points is not within the function's scope. You can grab a reference to the variable by using nonlocal:

points = 0
def test():
    nonlocal points
    points += 1

If points inside test() should refer to the outermost (module) scope, use global:

points = 0
def test():
    global points
    points += 1

List of strings to one string

My vote is string.Join

No need for lambda evaluations and temporary functions to be created, fewer function calls, less stack pushing and popping.

Run on server option not appearing in Eclipse

Right click on the project, go to "Run as", select "Run configurations" and create a run configuration.

mongoError: Topology was destroyed

In my case, this error was caused by a db.close(); out of a 'await' section inside of 'async'

MongoClient.connect(url, {poolSize: 10, reconnectTries: Number.MAX_VALUE, reconnectInterval: 1000}, function(err, db) {
    // Validate the connection to Mongo
    assert.equal(null, err);    
    // Query the SQL table 
    querySQL()
    .then(function (result) {
        console.log('Print results SQL');
        console.log(result);
        if(result.length > 0){

            processArray(db, result)
            .then(function (result) {
                console.log('Res');
                console.log(result);
            })
            .catch(function (err) {
                console.log('Err');
                console.log(err);
            })
        } else {
            console.log('Nothing to show in MySQL');
        }
    })
    .catch(function (err) {
        console.log(err);
    });
    db.close(); // <--------------------------------THIS LINE
});

Converting a character code to char (VB.NET)

The Chr function in VB.NET converts the integer back to the character:

Dim i As Integer = Asc("x") ' Convert to ASCII integer.
Dim x As Char = Chr(i)      ' Convert ASCII integer to char.

What is the maximum characters for the NVARCHAR(MAX)?

From MSDN Documentation

nvarchar [ ( n | max ) ]

Variable-length Unicode string data. n defines the string length and can be a value from 1 through 4,000. max indicates that the maximum storage size is 2^31-1 bytes (2 GB). The storage size, in bytes, is two times the actual length of data entered + 2 bytes

How to sort a list of strings?

list.sort()

It really is that simple :)

How to align flexbox columns left and right?

Another option is to add another tag with flex: auto style in between your tags that you want to fill in the remaining space.

https://jsfiddle.net/tsey5qu4/

The HTML:

<div class="parent">
  <div class="left">Left</div>
  <div class="fill-remaining-space"></div>
  <div class="right">Right</div>
</div>

The CSS:

.fill-remaining-space {
  flex: auto;
}

This is equivalent to flex: 1 1 auto, which absorbs any extra space along the main axis.

What is the purpose of using WHERE 1=1 in SQL statements?

Using 1=1 is actually not a very good idea as this can cause full table scans by itself.

See this--> T-SQL 1=1 Performance Hit

Using LIKE in an Oracle IN clause

Yes, you can use this query (Instead of 'Specialist' and 'Developer', type any strings you want separated by comma and change employees table with your table)

SELECT * FROM employees em
    WHERE EXISTS (select 1 from table(sys.dbms_debug_vc2coll('Specialist', 'Developer')) mt where em.job like ('%' || mt.column_value || '%'));

Why my query is better than the accepted answer: You don't need a CREATE TABLE permission to run it. This can be executed with just SELECT permissions.

How can I have two fixed width columns with one flexible column in the center?

Instead of using width (which is a suggestion when using flexbox), you could use flex: 0 0 230px; which means:

  • 0 = don't grow (shorthand for flex-grow)
  • 0 = don't shrink (shorthand for flex-shrink)
  • 230px = start at 230px (shorthand for flex-basis)

which means: always be 230px.

See fiddle, thanks @TylerH

Oh, and you don't need the justify-content and align-items here.

img {
    max-width: 100%;
}
#container {
    display: flex;
    x-justify-content: space-around;
    x-align-items: stretch;
    max-width: 1200px;
}
.column.left {
    width: 230px;
    flex: 0 0 230px;
}
.column.right {
    width: 230px;
    flex: 0 0 230px;
    border-left: 1px solid #eee;
}
.column.center {
    border-left: 1px solid #eee;
}

Spring Boot Adding Http Request Interceptors

You might also consider using the open source SpringSandwich library which lets you directly annotate in your Spring Boot controllers which interceptors to apply, much in the same way you annotate your url routes.

That way, no typo-prone Strings floating around -- SpringSandwich's method and class annotations easily survive refactoring and make it clear what's being applied where. (Disclosure: I'm the author).

http://springsandwich.com/

npm install private github repositories by dependency in package.json

Try this:

"dependencies" : {
  "name1" : "git://github.com/user/project.git#commit-ish",
  "name2" : "git://github.com/user/project.git#commit-ish"
}

You could also try this, where visionmedia/express is name/repo:

"dependencies" : {
   "express" : "visionmedia/express"
}

Or (if the npm package module exists):

"dependencies" : {
  "name": "*"
}

Taken from NPM docs

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

I had the same error. Resizing the images resolved the issue. However, I used online tools to resize the images because using pillow to resize them did not solve my problem.

Android sample bluetooth code to send a simple string via bluetooth

private OutputStream outputStream;
private InputStream inStream;

private void init() throws IOException {
    BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
    if (blueAdapter != null) {
        if (blueAdapter.isEnabled()) {
            Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();

            if(bondedDevices.size() > 0) {
                Object[] devices = (Object []) bondedDevices.toArray();
                BluetoothDevice device = (BluetoothDevice) devices[position];
                ParcelUuid[] uuids = device.getUuids();
                BluetoothSocket socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
                socket.connect();
                outputStream = socket.getOutputStream();
                inStream = socket.getInputStream();
            }

            Log.e("error", "No appropriate paired devices.");
        } else {
            Log.e("error", "Bluetooth is disabled.");
        }
    }
}

public void write(String s) throws IOException {
    outputStream.write(s.getBytes());
}

public void run() {
    final int BUFFER_SIZE = 1024;
    byte[] buffer = new byte[BUFFER_SIZE];
    int bytes = 0;
    int b = BUFFER_SIZE;

    while (true) {
        try {
            bytes = inStream.read(buffer, bytes, BUFFER_SIZE - bytes);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Add Auto-Increment ID to existing table?

If you want to add AUTO_INCREMENT in an existing table, need to run following SQL command:

 ALTER TABLE users ADD id int NOT NULL AUTO_INCREMENT primary key

iPhone X / 8 / 8 Plus CSS media queries

I noticed that the answers here are using: device-width, device-height, min-device-width, min-device-height, max-device-width, max-device-height.

Please refrain from using them since they are deprecated. see MDN for reference. Instead use the regular min-width, max-width and so on. For extra assurance, you can set the min and max to the same px amount. For example:

iPhone X

@media only screen 
    and (width : 375px) 
    and (height : 635px)
    and (orientation : portrait)  
    and (-webkit-device-pixel-ratio : 3) { }

You may also notice that I am using 635px for height. Try it yourself the window height is actually 635px. run iOS simulator for iPhone X and in Safari Web inspector do window.innerHeight. Here are a few useful links on this subject:

What is the correct way to check for string equality in JavaScript?

always Until you fully understand the differences and implications of using the == and === operators, use the === operator since it will save you from obscure (non-obvious) bugs and WTFs. The "regular" == operator can have very unexpected results due to the type-coercion internally, so using === is always the recommended approach.

For insight into this, and other "good vs. bad" parts of Javascript read up on Mr. Douglas Crockford and his work. There's a great Google Tech Talk where he summarizes lots of good info: http://www.youtube.com/watch?v=hQVTIJBZook


Update:

The You Don't Know JS series by Kyle Simpson is excellent (and free to read online). The series goes into the commonly misunderstood areas of the language and explains the "bad parts" that Crockford suggests you avoid. By understanding them you can make proper use of them and avoid the pitfalls.

The "Up & Going" book includes a section on Equality, with this specific summary of when to use the loose (==) vs strict (===) operators:

To boil down a whole lot of details to a few simple takeaways, and help you know whether to use == or === in various situations, here are my simple rules:

  • If either value (aka side) in a comparison could be the true or false value, avoid == and use ===.
  • If either value in a comparison could be of these specific values (0, "", or [] -- empty array), avoid == and use ===.
  • In all other cases, you're safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

I still recommend Crockford's talk for developers who don't want to invest the time to really understand Javascript—it's good advice for a developer who only occasionally works in Javascript.

Python dictionary : TypeError: unhashable type: 'list'

You can also use defaultdict to address this situation. It goes something like this:

from collections import defaultdict

#initialises the dictionary with values as list
aTargetDictionary = defaultdict(list)

for aKey in aSourceDictionary:
    aTargetDictionary[aKey].append(aSourceDictionary[aKey])

How do I import a namespace in Razor View Page?

Depending on your need you can use one of following method:

Could not load file or assembly '***.dll' or one of its dependencies

I had the same issue - a .dll working all the time, then my computer crashed and afterwards I had this problem of 'could not load file or assembly ....dll'

Two possible solutions: when the computer crashed there may be some inconsistent files in

C:\Users\<yourUserName>\AppData\Local\Temp\Temporary ASP.NET Files

Deleting that folder, recompiling and the error was gone.

Once I had also to delete my packages folder (I had read that somewhere else). Allow Visual Studio / nuget to install missing packages (or manually reinstall) and afterwards everything was fine again.

Calling dynamic function with dynamic number of parameters

Now I'm using this:

Dialoglar.Confirm = function (_title, _question, callback_OK) {
    var confirmArguments = arguments;
    bootbox.dialog({
        title: "<b>" + _title + "</b>",
        message: _question,
        buttons: {
            success: {
                label: "OK",
                className: "btn-success",
                callback: function () {
                    if (typeof(callback_OK) == "function") {                            callback_OK.apply(this,Array.prototype.slice.call(confirmArguments, 3));
                    }
                }
            },
            danger: {
                label: "Cancel",
                className: "btn-danger",
                callback: function () {
                    $(this).hide();
                }
            }
        }
    });
};

python numpy ValueError: operands could not be broadcast together with shapes

Per numpy docs:

When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when:

  • they are equal, or
  • one of them is 1

In other words, if you are trying to multiply two matrices (in the linear algebra sense) then you want X.dot(y) but if you are trying to broadcast scalars from matrix y onto X then you need to perform X * y.T.

Example:

>>> import numpy as np
>>>
>>> X = np.arange(8).reshape(4, 2)
>>> y = np.arange(2).reshape(1, 2)  # create a 1x2 matrix
>>> X * y
array([[0,1],
       [0,3],
       [0,5],
       [0,7]])

How to set the java.library.path from Eclipse

Here is another fix:

My build system (Gradle) added a required native library (dll) to the Eclipse build path (Right Click on Project -> Properties -> Java Build Path -> Libraries). Telling the build system not to add the native dll library to the Eclipse classpath solved the problem.

Replacing backslashes with forward slashes with str_replace() in php

you have to place double-backslash

$str = str_replace('\\', '/', $str);

Remove last characters from a string in C#. An elegant way?

You can use TrimEnd. It's efficient as well and looks clean.

"Name,".TrimEnd(',');

Using a dictionary to select function to execute

class CallByName():
    
    def method1(self):
        pass

    def method2(self):
        pass

    def method3(self):
        pass

    def get_method(self, method_name):
        method = getattr(self, method_name)
        return method()


callbyname = CallByName()
method1 = callbyname.get_method(method_name)

```

Returning data from Axios API

    async handleResponse(){
      const result = await this.axiosTest();
    }

    async axiosTest () {
    return await axios.get(url)
    .then(function (response) {
            console.log(response.data);
            return response.data;})
.catch(function (error) {
    console.log(error);
});
}

You can find check https://flaviocopes.com/axios/#post-requests url and find some relevant information in the GET section of this post.

Why do people say that Ruby is slow?

People say that Ruby is slow because they compare Ruby programs to programs written in other languages. Maybe the programs you write don't need to be faster. Maybe for the programs you write Ruby isn't the bottleneck that's slowing things down.

Ruby 2.1 compared to Javascript V8

Ruby 2.1 compared to ordinary Lua

Ruby 2.1 compared to Python 3

How to get substring in C

If the task is only copying 4 characters, try for loops. If it's going to be more advanced and you're asking for a function, try strncpy. http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

strncpy(sub1, baseString, 4);
strncpy(sub1, baseString+4, 4);
strncpy(sub1, baseString+8, 4);

or

for(int i=0; i<4; i++)
    sub1[i] = baseString[i];
sub1[4] = 0;
for(int i=0; i<4; i++)
    sub2[i] = baseString[i+4];
sub2[4] = 0;
for(int i=0; i<4; i++)
    sub3[i] = baseString[i+8];
sub3[4] = 0;

Prefer strncpy if possible.

Rename Files and Directories (Add Prefix)

On my system, I don't have the rename command. Here is a simple one liner. It finds all the HTML files recursively and adds prefix_ in front of their names:

for f in $(find . -name '*.html'); do mv "$f" "$(dirname "$f")/prefix_$(basename "$f")"; done

Hiding an Excel worksheet with VBA

This can be done in a single line, as long as the worksheet is active:

ActiveSheet.Visible = xlSheetHidden

However, you may not want to do this, especially if you use any "select" operations or you use any more ActiveSheet operations.

How can I perform a short delay in C# without using sleep?

By adding using System.Timers; to your program you can use this function:

private static void delay(int Time_delay)
{
   int i=0;
  //  ameTir = new System.Timers.Timer();
    _delayTimer = new System.Timers.Timer();
    _delayTimer.Interval = Time_delay;
    _delayTimer.AutoReset = false; //so that it only calls the method once
    _delayTimer.Elapsed += (s, args) => i = 1;
    _delayTimer.Start();
    while (i == 0) { };
}

Delay is a function and can be used like:

delay(5000);

Reset par to the default values at startup

From Quick-R

par()              # view current settings
opar <- par()      # make a copy of current settings
par(col.lab="red") # red x and y labels 
hist(mtcars$mpg)   # create a plot with these new settings 
par(opar)          # restore original settings

MongoDB "root" user

Mongodb user management:

roles list:

read
readWrite
dbAdmin
userAdmin
clusterAdmin
readAnyDatabase
readWriteAnyDatabase
userAdminAnyDatabase
dbAdminAnyDatabase

create user:

db.createUser(user, writeConcern)

db.createUser({ user: "user",
  pwd: "pass",
  roles: [
    { role: "read", db: "database" } 
  ]
})

update user:

db.updateUser("user",{
  roles: [
    { role: "readWrite", db: "database" } 
  ]
})

drop user:

db.removeUser("user")

or

db.dropUser("user")

view users:

db.getUsers();

more information: https://docs.mongodb.com/manual/reference/security/#read

JsonParseException: Unrecognized token 'http': was expecting ('true', 'false' or 'null')

I faced this exception for a long time and was not able to pinpoint the problem. The exception says line 1 column 9. The mistake I did is to get the first line of the file which flume is processing.

Apache flume process the content of the file in patches. So, when flume throws this exception and says line 1, it means the first line in the current patch.

If your flume agent is configured to use batch size = 100, and (for example) the file contains 400 lines, this means the exception is thrown in one of the following lines 1, 101, 201,301.

How to discover the line which causes the problem?

You have three ways to do that.

1- pull the source code and run the agent in debug mode. If you are an average developer like me and do not know how to make this, check the other two options.

2- Try to split the file based on the batch size and run the flume agent again. If you split the file into 4 files, and the invalid json exists between lines 301 and 400, the flume agent will process the first 3 files and stop at the fourth file. Take the fourth file and again split it into more smaller files. continue the process until you reach a file with only one line and flume fails while processing it.

3- Reduce the batch size of the flume agent to only one and compare the number of processed events in the output of the sink you are using. For example, in my case I am using Solr sink. The file contains 400 lines. The flume agent is configured with batch size=100. When I run the flume agent, it fails at some point and throw that exception. At this point check how many documents are ingested in Solr. If the invalid json exists at line 346, the number of documents indexed into Solr will be 345, so the next line is the line which causes the problem.

In my case I followed the third option and fortunately I pinpoint the line which causes the problem.

This is a long answer but it actually does not solve the exception. How I overcome this exception?

I have no idea why Jackson library complain while parsing a json string contains escaped characters \n \r \t. I think (but I am not sure) the Jackson parser is by default escaping these characters which cases the json string to be split into two lines (in case of \n) and then it deals each line as a separate json string.

In my case we used a customized interceptor to remove these characters before being processed by the flume agent. This is the way we solved this problem.

Python socket receive - incoming packets always have a different size

You can alternatively use recv(x_bytes, socket.MSG_WAITALL), which seems to work only on Unix, and will return exactly x_bytes.

How to export the Html Tables data into PDF using Jspdf

There is a tablePlugin for jspdf it expects array of objects and displays that data as a table. You can style the text and headers with little changes in the code. It is open source and also has examples for you to get started with.

How do I replace part of a string in PHP?

You need first to cut the string in how many pieces you want. Then replace the part that you want:

 $text = 'this is the test for string.';
 $text = substr($text, 0, 10);
 echo $text = str_replace(" ", "_", $text);

This will output:

this_is_th

C++ equivalent of StringBuffer/StringBuilder?

std::string is the C++ equivalent: It's mutable.

printing out a 2-D array in Matrix format

public static void printMatrix(double[][] matrix) {
    for (double[] row : matrix) {
        for (double element : row) {
            System.out.printf("%5.1f", element);
        }
        System.out.println();
    }
}

Function Call

printMatrix(new double[][]{2,0,0},{0,2,0},{0,0,3}});

Output:

  2.0  0.0  0.0
  0.0  2.0  0.0
  0.0  0.0  3.0

In console:

Console Output

Launch custom android application from android browser

For example, You have next things:

A link to open your app: http://example.com

The package name of your app: com.example.mypackage

Then you need to do next:

  1. Add an intent filter to your Activity (Can be any activity you want. For more info check the documentation).

    <activity
         android:name=".MainActivity">
    
         <intent-filter android:label="@string/filter_title_view_app_from_web">
             <action android:name="android.intent.action.VIEW" />
             <category android:name="android.intent.category.DEFAULT" />
             <category android:name="android.intent.category.BROWSABLE" />
             <!-- Accepts URIs that begin with "http://example.com" -->
    
             <data
                 android:host="example.com"
                 android:scheme="http" />
         </intent-filter>
    
         <intent-filter>
             <action android:name="android.intent.action.MAIN" />
             <category android:name="android.intent.category.LAUNCHER" />
         </intent-filter>
    
     </activity> 
    
  2. Create a HTML file to test the link or use this methods.

    Open your Activity directly (just open your Activity, without a choosing dialog).

    Open this link with browser or your programm (by choosing dialog).

  3. Use Mobile Chrome to test

  4. That's it.

And its not necessary to publish app in market to test deep linking =)

Also, for more information, check documentation and useful presentation.

HTML5 Canvas background image

Canvas does not using .png file as background image. changing to other file extensions like gif or jpg works fine.

INNER JOIN in UPDATE sql for DB2

for you ask

update file1 f1
set file1.firstfield=
(
select 'BIT OF TEXT' || f2.something
from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
where exists
(
select * from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
and f1.firstfield like 'BLAH%'

if join give multiple result you can force update like this

update file1 f1
set file1.firstfield=
(
select 'BIT OF TEXT' || f2.something
from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
fetch first rows only
)
where exists
(
select * from file2 f2
where substr(f1.firstfield,10,20) = substr(f2.anotherfield,1,10)
)
and f1.firstfield like 'BLAH%' 

template methode

update table1 f1
set (f1.field1, f1.field2, f1.field3, f1.field4)=
(
select f2.field1, f2.field2, f2.field3, 'CONSTVALUE'
from table2 f2
where (f1.key1, f1.key2)=(f2.key1, f2.key2) 
)
where exists 
(
select * from table2 f2
where (f1.key1, f1.key2)=(f2.key1, f2.key2)
) 

Replacing all non-alphanumeric characters with empty strings

You could also try this simpler regex:

 str = str.replaceAll("\\P{Alnum}", "");

Run Executable from Powershell script with parameters

I was able to get this to work by using the Invoke-Expression cmdlet.

Invoke-Expression "& `"$scriptPath`" test -r $number -b $testNumber -f $FileVersion -a $ApplicationID"

Generating combinations in c++

A simple way using std::next_permutation:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
    int n, r;
    std::cin >> n;
    std::cin >> r;

    std::vector<bool> v(n);
    std::fill(v.end() - r, v.end(), true);

    do {
        for (int i = 0; i < n; ++i) {
            if (v[i]) {
                std::cout << (i + 1) << " ";
            }
        }
        std::cout << "\n";
    } while (std::next_permutation(v.begin(), v.end()));
    return 0;
}

or a slight variation that outputs the results in an easier to follow order:

#include <iostream>
#include <algorithm>
#include <vector>

int main() {
   int n, r;
   std::cin >> n;
   std::cin >> r;

   std::vector<bool> v(n);
   std::fill(v.begin(), v.begin() + r, true);

   do {
       for (int i = 0; i < n; ++i) {
           if (v[i]) {
               std::cout << (i + 1) << " ";
           }
       }
       std::cout << "\n";
   } while (std::prev_permutation(v.begin(), v.end()));
   return 0;
}

A bit of explanation:

It works by creating a "selection array" (v), where we place r selectors, then we create all permutations of these selectors, and print the corresponding set member if it is selected in in the current permutation of v.


You can implement it if you note that for each level r you select a number from 1 to n.

In C++, we need to 'manually' keep the state between calls that produces results (a combination): so, we build a class that on construction initialize the state, and has a member that on each call returns the combination while there are solutions: for instance

#include <iostream>
#include <iterator>
#include <vector>
#include <cstdlib>

using namespace std;

struct combinations
{
    typedef vector<int> combination_t;

    // initialize status
   combinations(int N, int R) :
       completed(N < 1 || R > N),
       generated(0),
       N(N), R(R)
   {
       for (int c = 1; c <= R; ++c)
           curr.push_back(c);
   }

   // true while there are more solutions
   bool completed;

   // count how many generated
   int generated;

   // get current and compute next combination
   combination_t next()
   {
       combination_t ret = curr;

       // find what to increment
       completed = true;
       for (int i = R - 1; i >= 0; --i)
           if (curr[i] < N - R + i + 1)
           {
               int j = curr[i] + 1;
               while (i <= R-1)
                   curr[i++] = j++;
               completed = false;
               ++generated;
               break;
           }

       return ret;
   }

private:

   int N, R;
   combination_t curr;
};

int main(int argc, char **argv)
{
    int N = argc >= 2 ? atoi(argv[1]) : 5;
    int R = argc >= 3 ? atoi(argv[2]) : 2;
    combinations cs(N, R);
    while (!cs.completed)
    {
        combinations::combination_t c = cs.next();
        copy(c.begin(), c.end(), ostream_iterator<int>(cout, ","));
        cout << endl;
    }
    return cs.generated;
}

test output:

1,2,
1,3,
1,4,
1,5,
2,3,
2,4,
2,5,
3,4,
3,5,
4,5,

Server cannot set status after HTTP headers have been sent IIS7.5

We were getting the same error - so this may be useful to some.

For us the cause was super simple. An interface change confused an end user and they were pressing the back button in the browser at a 'bad' time after a form submission (sure we should probably have used a PRG pattern, but we didn't).

We fixed the issue and the user is no longer pressing the back button. Problem solved.

How to display HTML tags as plain text

To display HTML tags within a browser, surround the output with < xmp> and < / xmp> tags

How to build a Debian/Ubuntu package from source?

  • put "debian" directory from original package to your source directory
  • use "dch" to update version of package
  • use "debuild" to build the package

How to obtain the chat_id of a private Telegram channel?

Open the private channel, then:


WARNING be sure to add -100 prefix when using Telegram Bot API:

  • if the channel ID is for example 1192292378
  • then you should use -1001192292378

Get Line Number of certain phrase in file Python

You can use list comprehension:

content = open("path/to/file.txt").readlines()

lookup = 'the dog barked'

lines = [line_num for line_num, line_content in enumerate(content) if lookup in line_content]

print(lines)

Streaming video from Android camera to server

Here is complete article about streaming android camera video to a webpage.

Android Streaming Live Camera Video to Web Page

  1. Used libstreaming on android app
  2. On server side Wowza Media Engine is used to decode the video stream
  3. Finally jWplayer is used to play the video on a webpage.

Radio buttons and label to display in same line

Note: Traditionally the use of the label tag is for menus. eg:

<menu>
<label>Option 1</label>
<input type="radio" id="opt1">

<label>Option 2</label>
<input type="radio" id="opt2">

<label>Option 3</label>
<input type="radio" id="opt3">  
</menu>

MySQL SELECT DISTINCT multiple columns

Both your queries are correct and should give you the right answer.

I would suggest the following query to troubleshoot your problem.

SELECT DISTINCT a,b,c,d,count(*) Count FROM my_table GROUP BY a,b,c,d
order by count(*) desc

That is add count(*) field. This will give you idea how many rows were eliminated using the group command.

How do I validate a date string format in python?

From mere curiosity, I timed the two rivalling answers posted above.
And I had the following results:

dateutil.parser (valid str): 4.6732222699938575
dateutil.parser (invalid str): 1.7270505399937974
datetime.strptime (valid): 0.7822393209935399
datetime.strptime (invalid): 0.4394566189876059

And here's the code I used (Python 3.6)


from dateutil import parser as date_parser
from datetime import datetime
from timeit import timeit


def is_date_parsing(date_str):
    try:
        return bool(date_parser.parse(date_str))
    except ValueError:
        return False


def is_date_matching(date_str):
    try:
        return bool(datetime.strptime(date_str, '%Y-%m-%d'))
    except ValueError:
        return False



if __name__ == '__main__':
    print("dateutil.parser (valid date):", end=' ')
    print(timeit("is_date_parsing('2021-01-26')",
                 setup="from __main__ import is_date_parsing",
                 number=100000))

    print("dateutil.parser (invalid date):", end=' ')
    print(timeit("is_date_parsing('meh')",
                 setup="from __main__ import is_date_parsing",
                 number=100000))

    print("datetime.strptime (valid date):", end=' ')
    print(timeit("is_date_matching('2021-01-26')",
                 setup="from __main__ import is_date_matching",
                 number=100000))

    print("datetime.strptime (invalid date):", end=' ')
    print(timeit("is_date_matching('meh')",
                 setup="from __main__ import is_date_matching",
                 number=100000))

How to disable gradle 'offline mode' in android studio?

On Windows:-

Go to File -> Settings.

And open the 'Build,Execution,Deployment'. Then open the

Build Tools -> Gradle

Then uncheck -> Offline work on the right.

Click the OK button.

Then Rebuild the Project.

On Mac OS:-

go to Android Studio -> Preferences, and the rest is the same. OR follow steps given in the image

[For Mac go 1

enter image description here

How to prevent a browser from storing passwords

Thank you for giving a reply to me. I followed the below link

Disable browser 'Save Password' functionality

I resolved the issue by just adding readonly & onfocus="this.removeAttribute('readonly');" attributes besides autocomplete="off" to the inputs as shown below.

<input type="text" name="UserName" autocomplete="off" readonly 
onfocus="this.removeAttribute('readonly');" >

<input type="password" name="Password" autocomplete="off" readonly 
onfocus="this.removeAttribute('readonly');" >

This is working fine for me.

How to get to Model or Viewbag Variables in a Script Tag

What you have should work. It depends on the type of data you are setting i.e. if it's a string value you need to make sure it's in quotes e.g.

var val = '@ViewBag.ForSection';

If it's an integer you need to parse it as one i.e.

var val = parseInt(@ViewBag.ForSection);

Read values into a shell variable from a pipe

How about this:

echo "hello world" | echo test=$(cat)

Bootstrap 4 - Responsive cards in card-columns

I have created a Cards Layout - 3 cards in a row using Bootstrap 4 / CSS3 (of course its responsive). The following example uses basic Bootstrap 4 classes such as container, row, col-x, list-group and list-group-item. Thought to share here if someone is interested in this sort of a layout.

enter image description here

HTML

<div class="container">
  <div class="row">
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">        
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
    <div class="col-sm-12 col-md-4">
      <div class="custom-column">
        <div class="custom-column-header">Header</div>
        <div class="custom-column-content">
          <ul class="list-group">
            <li class="list-group-item"><i class="fa fa-check"></i> Cras justo odio</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Dapibus ac facilisis in</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Morbi leo risus</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Porta ac consectetur ac</li>
            <li class="list-group-item"><i class="fa fa-check"></i> Vestibulum at eros</li>
          </ul>
        </div>
        <div class="custom-column-footer"><button class="btn btn-primary btn-lg">Click here</button></div>
      </div>
    </div>
  </div>
</div>

CSS / SCSS

$primary-color: #ccc;
$col-bg-color: #eee;
$col-footer-bg-color: #eee;
$col-header-bg-color: #007bff;
$col-content-bg-color: #fff;

body {
  background-color: $primary-color;
}  

.custom-column {  
  background-color: $col-bg-color;
  border: 5px solid $col-bg-color;    
  padding: 10px;
  box-sizing: border-box;  
}

.custom-column-header {
  font-size: 24px;
  background-color: #007bff;  
  color: white;
  padding: 15px;  
  text-align: center;
}

.custom-column-content {
  background-color: $col-content-bg-color;
  border: 2px solid white;  
  padding: 20px;  
}

.custom-column-footer {
  background-color: $col-footer-bg-color;   
  padding-top: 20px;
  text-align: center;
}

Link :- https://codepen.io/anjanasilva/pen/JmdOpb

Disabling and enabling a html input button

While not directly related to the question, if you hop onto this question looking to disable something other than the typical input elements button, input, textarea, the syntax won't work.

To disable a div or a span, use setAttribute

document.querySelector('#somedivorspan').setAttribute('disabled', true);

P.S: Gotcha, only call this if you intend to disable. A bug in chrome Version 83 causes this to always disable even when the second parameter is false.

How to setup virtual environment for Python in VS Code?

This is an adding to @Sam answer that though is correct is missing the fact that anytime you open a folder in visual studio code, it create a .vscode folder, but those can be multiple, created any time you eventually open a directory. The .vscode folder has JSON objects that content properties such "setting.json", in which one declare the Interpreter to use at that ".vscode" level( refer to this for more clarifications What is a 'workspace' in VS Code?).

{
   {
     "python.pythonPath": "VirtualEnPath/bin/python3.6"
   }
}

So potentially you could open VS code at another level in the virtual Env, it create another .vscode folder that assume as Python directory those of the global machine and so having such error, and has I experienced has nothing to do if the Virtual Env is activated or not.

This indeed what happened to me, I have indeed a DjangoRESTAPI_GEN folder in which I initially opened the IDE and it did recognize the Virtual Env Python path, the a few days after I opened it at the level where git is, so it did created another .vscode, that picked the global Python Interpreter, causing my lint in the Virtual Environment not been used, and the virtual env interpreter not even showed in "select python interpreter". But as wrote opening the IDE at the level where the .vscode that has the settings.json with correct path, it does.

Once you set the correct path in the setting.json and select the virtual env interpreter, then VS Code will automatically activate the VE in its terminal

enter image description here

How to export all collections in MongoDB?

I dump all collection on robo3t. I run the command below on vagrant/homestead. It's work for me

mongodump --host localhost --port 27017 --db db_name --out db_path

PHP executable not found. Install PHP 7 and add it to your PATH or set the php.executablePath setting

For those who are using xampp:

File -> Preferences -> Settings

"php.validate.executablePath": "C:\\xampp\\php\\php.exe",
"php.executablePath": "C:\\xampp\\php\\php.exe"

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

Workaround: This is a problem we have observed too, in Windows Server 2012 R2. I haven't found a reason or solution yet. Here is my work around.

During installation while error is shown, go to Services.msc. Find the service which throws the error, then re-enter the password in the service's log-in information. Then, hit "retry" in setup. It works.

The error will not be shown for same user again. But will be shown for a different user.

Use Fieldset Legend with bootstrap

That's because Bootstrap by default sets the width of the legend element to 100%. You can fix this by changing your legend.scheduler-border to also use:

legend.scheduler-border {
    width:inherit; /* Or auto */
    padding:0 10px; /* To give a bit of padding on the left and right */
    border-bottom:none;
}

JSFiddle example.

You'll also need to ensure your custom stylesheet is being added after Bootstrap to prevent Bootstrap overriding your styling - although your styles here should have higher specificity.

You may also want to add margin-bottom:0; to it as well to reduce the gap between the legend and the divider.

Changing the resolution of a VNC session in linux

As far as I know there's no way to change the client's resolution just using VNC, as it is just a "monitor mirroring" application.

TightVNC however (which is a VNC client and server application) can resize the screen on the client side, i.e. making everything a little smaller (similar to image resizing techniques in graphics programs). That should work if you don't use too small font sizes. VNC should theoretically be compatible between different VNC applications.

How to check object is nil or not in swift?

Swift 4.2

func isValid(_ object:AnyObject!) -> Bool
{
    if let _:AnyObject = object
    {
        return true
    }

    return false
}

Usage

if isValid(selectedPost)
{
    savePost()
}

How do I determine file encoding in OS X?

Which LaTeX are you using? When I was using teTeX, I had to manually download the unicode package and add this to my .tex files:

% UTF-8 stuff
\usepackage[notipa]{ucs}
\usepackage[utf8x]{inputenc}
\usepackage[T1]{fontenc}

Now, I've switched over to XeTeX from the TeXlive 2008 package (here), it is even more simple:

% UTF-8 stuff
\usepackage{fontspec}
\usepackage{xunicode}

As for detection of a file's encoding, you could play with file(1) (but it is rather limited) but like someone else said, it is difficult.

Crystal Reports for VS2012 - VS2013 - VS2015 - VS2017 - VS2019

This post is right from SAP on Sep 20, 2012.

In short, they are still working on a release of Crystal Reports that will support VS2012 (including support for Windows 8) It will come in the form of a service pack release that updates the version currently supporting VS2010. At that time they will drop 2010/2012 from the name and simply call it Crystal Reports Developer.

If you want to download that version you can find it here.

Further, service packs etc. when released can be found here.


I would also add that I am currently using Visual Studio 2012. As long as you don't edit existing reports they continue to compile and work fine. Even on Windows 8. When I need to modify a report I can still open the project with VS2010, do my work, save my changes, and then switch back to 2012. It's a little bit of a pain but the ability for VS2010 and VS2012 to co-exist is nice in this regard. I'm also using TFS2012 and so far it hasn't had a problem with me modifying files in 2010 on a "2012" solution.

When to use EntityManager.find() vs EntityManager.getReference() with JPA

This makes me wonder, when is it advisable to use the EntityManager.getReference() method instead of the EntityManager.find() method?

EntityManager.getReference() is really an error prone method and there is really very few cases where a client code needs to use it.
Personally, I never needed to use it.

EntityManager.getReference() and EntityManager.find() : no difference in terms of overhead

I disagree with the accepted answer and particularly :

If i call find method, JPA provider, behind the scenes, will call

SELECT NAME, AGE FROM PERSON WHERE PERSON_ID = ?

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

If i call getReference method, JPA provider, behind the scenes, will call

UPDATE PERSON SET AGE = ? WHERE PERSON_ID = ?

It is not the behavior that I get with Hibernate 5 and the javadoc of getReference() doesn't say such a thing :

Get an instance, whose state may be lazily fetched. If the requested instance does not exist in the database, the EntityNotFoundException is thrown when the instance state is first accessed. (The persistence provider runtime is permitted to throw the EntityNotFoundException when getReference is called.) The application should not expect that the instance state will be available upon detachment, unless it was accessed by the application while the entity manager was open.

EntityManager.getReference() spares a query to retrieve the entity in two cases :

1) if the entity is stored in the Persistence context, that is the first level cache.
And this behavior is not specific to EntityManager.getReference(), EntityManager.find() will also spare a query to retrieve the entity if the entity is stored in the Persistence context.

You can check the first point with any example.
You can also rely on the actual Hibernate implementation.
Indeed, EntityManager.getReference() relies on the createProxyIfNecessary() method of the org.hibernate.event.internal.DefaultLoadEventListener class to load the entity.
Here is its implementation :

private Object createProxyIfNecessary(
        final LoadEvent event,
        final EntityPersister persister,
        final EntityKey keyToLoad,
        final LoadEventListener.LoadType options,
        final PersistenceContext persistenceContext) {
    Object existing = persistenceContext.getEntity( keyToLoad );
    if ( existing != null ) {
        // return existing object or initialized proxy (unless deleted)
        if ( traceEnabled ) {
            LOG.trace( "Entity found in session cache" );
        }
        if ( options.isCheckDeleted() ) {
            EntityEntry entry = persistenceContext.getEntry( existing );
            Status status = entry.getStatus();
            if ( status == Status.DELETED || status == Status.GONE ) {
                return null;
            }
        }
        return existing;
    }
    if ( traceEnabled ) {
        LOG.trace( "Creating new proxy for entity" );
    }
    // return new uninitialized proxy
    Object proxy = persister.createProxy( event.getEntityId(), event.getSession() );
    persistenceContext.getBatchFetchQueue().addBatchLoadableEntityKey( keyToLoad );
    persistenceContext.addProxy( keyToLoad, proxy );
    return proxy;
}

The interesting part is :

Object existing = persistenceContext.getEntity( keyToLoad );

2) If we don't effectively manipulate the entity, echoing to the lazily fetched of the javadoc.
Indeed, to ensure the effective loading of the entity, invoking a method on it is required.
So the gain would be related to a scenario where we want to load a entity without having the need to use it ? In the frame of applications, this need is really uncommon and in addition the getReference() behavior is also very misleading if you read the next part.

Why favor EntityManager.find() over EntityManager.getReference()

In terms of overhead, getReference() is not better than find() as discussed in the previous point.
So why use the one or the other ?

Invoking getReference() may return a lazily fetched entity.
Here, the lazy fetching doesn't refer to relationships of the entity but the entity itself.
It means that if we invoke getReference() and then the Persistence context is closed, the entity may be never loaded and so the result is really unpredictable. For example if the proxy object is serialized, you could get a null reference as serialized result or if a method is invoked on the proxy object, an exception such as LazyInitializationException is thrown.

It means that the throw of EntityNotFoundException that is the main reason to use getReference() to handle an instance that does not exist in the database as an error situation may be never performed while the entity is not existing.

EntityManager.find() doesn't have the ambition of throwing EntityNotFoundException if the entity is not found. Its behavior is both simple and clear. You will never have surprise as it returns always a loaded entity or null (if the entity is not found) but never an entity under the shape of a proxy that may not be effectively loaded.
So EntityManager.find() should be favored in the very most of cases.

Flutter does not find android sdk

SdkManager removes the API28 version and re-downloads the API28 version, setting the Flutter and Dart paths in AndroidStudio, and now it works fine. image

What is the difference between "#!/usr/bin/env bash" and "#!/usr/bin/bash"?

Running a command through /usr/bin/env has the benefit of looking for whatever the default version of the program is in your current environment.

This way, you don't have to look for it in a specific place on the system, as those paths may be in different locations on different systems. As long as it's in your path, it will find it.

One downside is that you will be unable to pass more than one argument (e.g. you will be unable to write /usr/bin/env awk -f) if you wish to support Linux, as POSIX is vague on how the line is to be interpreted, and Linux interprets everything after the first space to denote a single argument. You can use /usr/bin/env -S on some versions of env to get around this, but then the script will become even less portable and break on fairly recent systems (e.g. even Ubuntu 16.04 if not later).

Another downside is that since you aren't calling an explicit executable, it's got the potential for mistakes, and on multiuser systems security problems (if someone managed to get their executable called bash in your path, for example).

#!/usr/bin/env bash #lends you some flexibility on different systems
#!/usr/bin/bash     #gives you explicit control on a given system of what executable is called

In some situations, the first may be preferred (like running python scripts with multiple versions of python, without having to rework the executable line). But in situations where security is the focus, the latter would be preferred, as it limits code injection possibilities.

Java 8 stream map on entry set

Here is a shorter solution by AbacusUtil

Stream.of(input).toMap(e -> e.getKey().substring(subLength), 
                       e -> AttributeType.GetByName(e.getValue()));

How to set default value for form field in Symfony2?

As Brian asked:

empty_data appears to only set the field to 1 when it is submitted with no value. What about when you want the form to default to displaying 1 in the input when no value is present?

you can set the default value with empty_value

$builder->add('myField', 'number', ['empty_value' => 'Default value'])

Auto insert date and time in form input field?

It sounds like you are going to be storing the value that input field contains after the form is submitted, which means you are using a scripting language. I would use it instead of JavaScript as most scripting languages have better time/date formatting options. In PHP you could do something like this:

<input id="date" name="date" value="<?php echo date("M j, Y - g:i"); ?>"/>

Which would fill the field with "Jun 16, 2009 - 8:58"

How to invoke a Linux shell command from Java

Building on @Tim's example to make a self-contained method:

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Shell {

    /** Returns null if it failed for some reason.
     */
    public static ArrayList<String> command(final String cmdline,
    final String directory) {
        try {
            Process process = 
                new ProcessBuilder(new String[] {"bash", "-c", cmdline})
                    .redirectErrorStream(true)
                    .directory(new File(directory))
                    .start();

            ArrayList<String> output = new ArrayList<String>();
            BufferedReader br = new BufferedReader(
                new InputStreamReader(process.getInputStream()));
            String line = null;
            while ( (line = br.readLine()) != null )
                output.add(line);

            //There should really be a timeout here.
            if (0 != process.waitFor())
                return null;

            return output;

        } catch (Exception e) {
            //Warning: doing this is no good in high quality applications.
            //Instead, present appropriate error messages to the user.
            //But it's perfectly fine for prototyping.

            return null;
        }
    }

    public static void main(String[] args) {
        test("which bash");

        test("find . -type f -printf '%T@\\\\t%p\\\\n' "
            + "| sort -n | cut -f 2- | "
            + "sed -e 's/ /\\\\\\\\ /g' | xargs ls -halt");

    }

    static void test(String cmdline) {
        ArrayList<String> output = command(cmdline, ".");
        if (null == output)
            System.out.println("\n\n\t\tCOMMAND FAILED: " + cmdline);
        else
            for (String line : output)
                System.out.println(line);

    }
}

(The test example is a command that lists all files in a directory and its subdirectories, recursively, in chronological order.)

By the way, if somebody can tell me why I need four and eight backslashes there, instead of two and four, I can learn something. There is one more level of unescaping happening than what I am counting.

Edit: Just tried this same code on Linux, and there it turns out that I need half as many backslashes in the test command! (That is: the expected number of two and four.) Now it's no longer just weird, it's a portability problem.

In Tensorflow, get the names of all the Tensors in a graph

The accepted answer only gives you a list of strings with the names. I prefer a different approach, which gives you (almost) direct access to the tensors:

graph = tf.get_default_graph()
list_of_tuples = [op.values() for op in graph.get_operations()]

list_of_tuples now contains every tensor, each within a tuple. You could also adapt it to get the tensors directly:

graph = tf.get_default_graph()
list_of_tuples = [op.values()[0] for op in graph.get_operations()]

Remove an item from array using UnderscoreJS

You can use Underscore .filter

    var arr = [{
      id: 1,
      name: 'a'
    }, {
      id: 2,
      name: 'b'
    }, {
      id: 3,
      name: 'c'
    }];

    var filtered = _(arr).filter(function(item) {
         return item.id !== 3
    });

Can also be written as:

var filtered = arr.filter(function(item) {
    return item.id !== 3
});

var filtered = _.filter(arr, function(item) {
    return item.id !== 3
});

Check Fiddle

You can also use .reject

Can Mysql Split a column?

Here is another variant I posted on related question. The REGEX check to see if you are out of bounds is useful, so for a table column you would put it in the where clause.

SET @Array = 'one,two,three,four';
SET @ArrayIndex = 2;
SELECT CASE 
    WHEN @Array REGEXP CONCAT('((,).*){',@ArrayIndex,'}') 
    THEN SUBSTRING_INDEX(SUBSTRING_INDEX(@Array,',',@ArrayIndex+1),',',-1) 
    ELSE NULL
END AS Result;
  • SUBSTRING_INDEX(string, delim, n) returns the first n
  • SUBSTRING_INDEX(string, delim, -1) returns the last only
  • REGEXP '((delim).*){n}' checks if there are n delimiters (i.e. you are in bounds)

Angular 2 http post params and body

Let said our backend looks like this:

public async Task<IActionResult> Post([FromBody] IList<UserRol> roles, string notes) {
}

We have a HttpService like this:

    post<T>(url: string, body: any, headers?: HttpHeaders, params?: HttpParams): Observable<T> {
        return this.http.post<T>(url, body, { headers: headers, params});
    }

Following is how we can pass the body and the notes as parameter: // how to call it

const headers: HttpHeaders = new HttpHeaders({
    'Authorization': `Bearer XXXXXXXXXXXXXXXXXXXXXXXXXXX`
});

const bodyData = this.getBodyData(); // get whatever we want to send as body

let params: HttpParams = new HttpParams();
params = params.set('notes', 'Some notes to send');

this.httpService.post<any>(url, bodyData, headers, params);

It worked for me (using angular 7^), I hope is useful for somebody.

Why does the 'int' object is not callable error occur when using the sum() function?

This means that somewhere else in your code, you have something like:

sum = 0

Which shadows the builtin sum (which is callable) with an int (which isn't).

How can I make my own event in C#?

You can declare an event with the following code:

public event EventHandler MyOwnEvent;

A custom delegate type instead of EventHandler can be used if needed.

You can find detailed information/tutorials on the use of events in .NET in the article Events Tutorial (MSDN).

manage.py runserver

Just in case any Windows users are having trouble, I thought I'd add my own experience. When running python manage.py runserver 0.0.0.0:8000, I could view urls using localhost:8000, but not my ip address 192.168.1.3:8000.

I ended up disabling ipv6 on my wireless adapter, and running ipconfig /renew. After this everything worked as expected.

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

A single listening port can accept more than one connection simultaneously.

There is a '64K' limit that is often cited, but that is per client per server port, and needs clarifying.

Each TCP/IP packet has basically four fields for addressing. These are:

source_ip source_port destination_ip destination_port
<----- client ------> <--------- server ------------>

Inside the TCP stack, these four fields are used as a compound key to match up packets to connections (e.g. file descriptors).

If a client has many connections to the same port on the same destination, then three of those fields will be the same - only source_port varies to differentiate the different connections. Ports are 16-bit numbers, therefore the maximum number of connections any given client can have to any given host port is 64K.

However, multiple clients can each have up to 64K connections to some server's port, and if the server has multiple ports or either is multi-homed then you can multiply that further.

So the real limit is file descriptors. Each individual socket connection is given a file descriptor, so the limit is really the number of file descriptors that the system has been configured to allow and resources to handle. The maximum limit is typically up over 300K, but is configurable e.g. with sysctl.

The realistic limits being boasted about for normal boxes are around 80K for example single threaded Jabber messaging servers.

Image convert to Base64

Exactly what you need:) You can choose callback version or Promise version. Note that promises will work in IE only with Promise polyfill lib.You can put this code once on a page, and this function will appear in all your files.

The loadend event is fired when progress has stopped on the loading of a resource (e.g. after "error", "abort", or "load" have been dispatched)

Callback version

        File.prototype.convertToBase64 = function(callback){
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    callback(e.target.result, e.target.error);
                };   
                reader.readAsDataURL(this);
        };

        $("#asd").on('change',function(){
          var selectedFile = this.files[0];
          selectedFile.convertToBase64(function(base64){
               alert(base64);
          }) 
        });

Promise version

    File.prototype.convertToBase64 = function(){
         return new Promise(function(resolve, reject) {
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    resolve({
                      fileName: this.name,
                      result: e.target.result, 
                      error: e.target.error
                    });
                };   
                reader.readAsDataURL(this);
        }.bind(this)); 
    };

    FileList.prototype.convertAllToBase64 = function(regexp){
      // empty regexp if not set
      regexp = regexp || /.*/;
      //making array from FileList
      var filesArray = Array.prototype.slice.call(this);
      var base64PromisesArray = filesArray.
           filter(function(file){
             return (regexp).test(file.name)
           }).map(function(file){
             return file.convertToBase64();
           });
      return Promise.all(base64PromisesArray);
    };

    $("#asd").on('change',function(){
      //for one file
      var selectedFile = this.files[0];
      selectedFile.convertToBase64().
          then(function(obj){
            alert(obj.result);
          });
      });
      //for all files that have file extention png, jpeg, jpg, gif
      this.files.convertAllToBase64(/\.(png|jpeg|jpg|gif)$/i).then(function(objArray){
            objArray.forEach(function(obj, i){
                  console.log("result[" + obj.fileName + "][" + i + "] = " + obj.result);
            });
      });
    })

html

<input type="file" id="asd" multiple/>

How to compare two Dates without the time portion?

My proposition:

    Calendar cal = Calendar.getInstance();
    cal.set(1999,10,01);   // nov 1st, 1999
    cal.set(Calendar.AM_PM,Calendar.AM);
    cal.set(Calendar.HOUR,0);
    cal.set(Calendar.MINUTE,0);
    cal.set(Calendar.SECOND,0);
    cal.set(Calendar.MILLISECOND,0);

    // date column in the Thought table is of type sql date
    Thought thought = thoughtDao.getThought(date, language);

    Assert.assertEquals(cal.getTime(), thought.getDate());

What's the difference between "static" and "static inline" function?

From my experience with GCC I know that static and static inline differs in a way how compiler issue warnings about unused functions. More precisely when you declare static function and it isn't used in current translation unit then compiler produce warning about unused function, but you can inhibit that warning with changing it to static inline.

Thus I tend to think that static should be used in translation units and benefit from extra check compiler does to find unused functions. And static inline should be used in header files to provide functions that can be in-lined (due to absence of external linkage) without issuing warnings.

Unfortunately I cannot find any evidence for that logic. Even from GCC documentation I wasn't able to conclude that inline inhibits unused function warnings. I'd appreciate if someone will share links to description of that.

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

For the difference between A1 and Today's date you could enter: =ABS(TODAY()-A1)

which returns the (fractional) number of days between the dates.

You're likely getting a #VALUE! error in your formula because Excel treats dates as numbers.

how to return index of a sorted list?

you can use numpy.argsort

or you can do:

test =  [2,3,1,4,5]
idxs = list(zip(*sorted([(val, i) for i, val in enumerate(test)])))[1]

zip will rearange the list so that the first element is test and the second is the idxs.

Spring expected at least 1 bean which qualifies as autowire candidate for this dependency

If there is an interface anywhere in the ThreadProvider hierarchy try putting the name of the Interface as the type of your service provider, eg. if you have say this structure:

public class ThreadProvider implements CustomInterface{
...
}

Then in your controller try this:

@Controller
public class ChiusuraController {

    @Autowired
    private CustomInterface chiusuraProvider;
}

The reason why this is happening is, in your first case when you DID NOT have ChiusuraProvider extend ThreadProvider Spring probably was underlying creating a CGLIB based proxy for you(to handle the @Transaction).

When you DID extend from ThreadProvider assuming that ThreadProvider extends some interface, Spring in that case creates a Java Dynamic Proxy based Proxy, which would appear to be an implementation of that interface instead of being of ChisuraProvider type.

If you absolutely need to use ChisuraProvider you can try AspectJ as an alternative or force CGLIB based proxy in the case with ThreadProvider also this way:

<aop:aspectj-autoproxy proxy-target-class="true"/>

Here is some more reference on this from the Spring Reference site: http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/classic-aop-spring.html#classic-aop-pfb

What is size_t in C?

size_t or any unsigned type might be seen used as loop variable as loop variables are typically greater than or equal to 0.

When we use a size_t object, we have to make sure that in all the contexts it is used, including arithmetic, we want only non-negative values. For instance, following program would definitely give the unexpected result:

// C program to demonstrate that size_t or
// any unsigned int type should be used 
// carefully when used in a loop

#include<stdio.h>
int main()
{
const size_t N = 10;
int a[N];

// This is fine
for (size_t n = 0; n < N; ++n)
a[n] = n;

// But reverse cycles are tricky for unsigned 
// types as can lead to infinite loop
for (size_t n = N-1; n >= 0; --n)
printf("%d ", a[n]);
}

Output
Infinite loop and then segmentation fault

CSS rule to apply only if element has BOTH classes

If you need a progmatic solution this should work in jQuery:

$(".abc.xyz").css("width", 200);

How can I use "." as the delimiter with String.split() in java

If performance is an issue, you should consider using StringTokenizer instead of split. StringTokenizer is much much faster than split, even though it is a "legacy" class (but not deprecated).

error: command 'gcc' failed with exit status 1 on CentOS

I bet you have to install libxml2-devel or libxml++-devel or even python-devel. But it is only a wild guess, not seeing the actual error from the log file. But it seems gcc is missing either a header file or a library file.

Differences between Emacs and Vim

I'm a full-blown Emacs fan-boy, but I knew VI long before I knew Emacs. That said, I make all of my people learn VI because it's always available, everywhere. Can't go wrong with either one of them.

What's the difference between using CGFloat and float?

just mention that - Jan, 2020 Xcode 11.3/iOS13

Swift 5

From the CoreGraphics source code

public struct CGFloat {
    /// The native type used to store the CGFloat, which is Float on
    /// 32-bit architectures and Double on 64-bit architectures.
    public typealias NativeType = Double

How to get HTTP Response Code using Selenium WebDriver

I was also having same issue and stuck for some days, but after some research i figured out that we can actually use chrome's "--remote-debugging-port" to intercept requests in conjunction with selenium web driver. Use following Pseudocode as a reference:-

create instance of chrome driver with remote debugging

int freePort = findFreePort();

chromeOptions.addArguments("--remote-debugging-port=" + freePort);

ChromeDriver driver = new ChromeDriver(chromeOptions);`

make a get call to http://127.0.0.1:freePort

String response = makeGetCall( "http://127.0.0.1" + freePort  + "/json" );

Extract chrome's webSocket Url to listen, you can see response and figure out how to extract

String webSocketUrl = response.substring(response.indexOf("ws://127.0.0.1"), response.length() - 4);

Connect to this socket, u can use asyncHttp

socket = maketSocketConnection( webSocketUrl );

Enable network capture

socket.send( { "id" : 1, "method" : "Network.enable" } );

Now chrome will send all network related events and captures them as follows

socket.onMessageReceived( String message ){

    Json responseJson = toJson(message);
    if( responseJson.method == "Network.responseReceived" ){
       //extract status code
    }
}

driver.get("http://stackoverflow.com");

you can do everything mentioned in dev tools site. see https://chromedevtools.github.io/devtools-protocol/ Note:- use chromedriver 2.39 or above.

I hope it helps someone.

reference : Using Google Chrome remote debugging protocol

Android Layout Weight

Think it that way, will be simpler

If you have 3 buttons and their weights are 1,3,1 accordingly, it will work like table in HTML

Provide 5 portions for that line: 1 portion for button 1, 3 portion for button 2 and 1 portion for button 1

Why do this() and super() have to be the first statement in a constructor?

The main goal of adding the super() in the sub-class constructors is that the main job of the compiler is to make a direct or indirect connection of all the classes with the Object class that's why the compiler checks if we have provided the super(parameterized) then compiler doesn't take any responsibility. so that all the instance member gets initialized from Object to the sub - classes.

How to make/get a multi size .ico file?

'@icon sushi' is a portable utility that can create multiple icon ico file for free.

Drag & drop the different icon sizes, select them all and choose file -> create multiple icon.

You can download if from http://www.towofu.net/soft/e-aicon.php

Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name string
    Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

How to select the last column of dataframe

This is another way to do it. I think maybe a little more general:

df.ix[:,-1]

How to use an arraylist as a prepared statement parameter

You may want to use setArray method as mentioned in the javadoc below:

http://docs.oracle.com/javase/6/docs/api/java/sql/PreparedStatement.html#setArray(int, java.sql.Array)

Sample Code:

PreparedStatement pstmt = 
                conn.prepareStatement("select * from employee where id in (?)");
Array array = conn.createArrayOf("VARCHAR", new Object[]{"1", "2","3"});
pstmt.setArray(1, array);
ResultSet rs = pstmt.executeQuery();

How do I SET the GOPATH environment variable on Ubuntu? What file must I edit?

export GOROOT=/usr/lib/go
export GOPATH=$HOME/go
export PATH=$PATH:$GOROOT/bin

And you may want to check by $ go env

Using true and false in C

1 is most readable not compatible with all compilers.

No ISO C compiler has a built in type called bool. ISO C99 compilers have a type _Bool, and a header which typedef's bool. So compatability is simply a case of providing your own header if the compiler is not C99 compliant (VC++ for example).

Of course a simpler approach is to compile your C code as C++.

Junit - run set up method once

Try this solution: https://stackoverflow.com/a/46274919/907576 :

with @BeforeAllMethods/@AfterAllMethods annotation you could execute any method in Test class in an instance context, where all injected values are available.

Best way to remove duplicate entries from a data table

Do dtEmp on your current working DataTable:

DataTable distinctTable = dtEmp.DefaultView.ToTable( /*distinct*/ true);

It's nice.

How can I roll back my last delete command in MySQL?

If you haven't made a backup, you are pretty much fudged.

Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

I solved this another way. First of all I installed cuda 10.1 toolkit from this link

Where i selected installer type(exe(local)) and installed 10.1 in custom mode means (without visual studio integration, NVIDIA PhysX because previously I installed CUDA 10.2 so required dependencies were installed automatically)

After installation, From the Following Path (C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin) , in my case, I copied 'cudart64_101.dll' file and pasted in (C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.2\bin).

Then importing Tensorflow worked smoothly.

N.B. Sorry for Bad English

Find files in a folder using Java

For list out Json files from your given directory.

import java.io.File;
    import java.io.FilenameFilter;

    public class ListOutFilesInDir {
        public static void main(String[] args) throws Exception {

            File[] fileList = getFileList("directory path");

            for(File file : fileList) {
                System.out.println(file.getName());
            }
        }

        private static File[] getFileList(String dirPath) {
            File dir = new File(dirPath);   

            File[] fileList = dir.listFiles(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return name.endsWith(".json");
                }
            });
            return fileList;
        }
    }

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

Calculate percentage saved between two numbers?

The formula would be (original - discounted)/original. i.e. (365-165)/365 = 0.5479...

Load vs. Stress testing

Load testing = putting a specified amount of load on the server for certain amount of time. 100 simultaneous users for 10 minutes. Ensure stability of software. Stress testing = increasing the amount of load steadily until the software crashes. 10 simultaneous users increasing every 2 minutes until the server crashes.

To make a comparison to weight lifting: You "max" your weight to see what you can do for 1 rep (stress testing) and then on regular workouts you do 85% of your max value for 3 sets of 10 reps (load testing)

How to detect if multiple keys are pressed at once using JavaScript?

If one of keys pressed is Alt / Crtl / Shift you can use this method:

document.body.addEventListener('keydown', keysDown(actions) );

function actions() {
   // do stuff here
}

// simultaneous pressing Alt + R
function keysDown (cb) {
  return function (zEvent) {
    if (zEvent.altKey &&  zEvent.code === "KeyR" ) {
      return cb()
    }
  }
}

Get the cartesian product of a series of lists?

For Python 2.5 and older:

>>> [(a, b, c) for a in [1,2,3] for b in ['a','b'] for c in [4,5]]
[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), 
 (2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5), 
 (3, 'b', 4), (3, 'b', 5)]

Here's a recursive version of product() (just an illustration):

def product(*args):
    if not args:
        return iter(((),)) # yield tuple()
    return (items + (item,) 
            for items in product(*args[:-1]) for item in args[-1])

Example:

>>> list(product([1,2,3], ['a','b'], [4,5])) 
[(1, 'a', 4), (1, 'a', 5), (1, 'b', 4), (1, 'b', 5), (2, 'a', 4), 
 (2, 'a', 5), (2, 'b', 4), (2, 'b', 5), (3, 'a', 4), (3, 'a', 5), 
 (3, 'b', 4), (3, 'b', 5)]
>>> list(product([1,2,3]))
[(1,), (2,), (3,)]
>>> list(product([]))
[]
>>> list(product())
[()]

Checking letter case (Upper/Lower) within a string in Java

Although this code is likely beyond the understanding of a novice, it can be done in one line using a regex with positive and negative look-aheads:

boolean ok = 
    password.matches("^(?=.*[A-Z])(?=.*[!@#$%^&*])(?=.*\\d)(?!.*(AND|NOT)).*[a-z].*");

OrderBy pipe issue

I've created an OrderBy pipe that does just what you need. It supports being able to sort on multiple columns of an enumerable of objects as well.

<li *ngFor="#todo in todos | orderBy : ['completed']">{{todo.name}} {{todo.completed}}</li>

This pipe does allow for adding more items to the array after rendering the page, and will sort the array with the updates dynamically.

I have a write up on the process here.

And here's a working demo: http://fuelinteractive.github.io/fuel-ui/#/pipe/orderby and https://plnkr.co/edit/DHLVc0?p=info

Angular 2 Hover event

Simply do (mouseenter) attribute in Angular2+...

In your HTML do:

<div (mouseenter)="mouseHover($event)">Hover!</div> 

and in your component do:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'component',
  templateUrl: './component.html',
  styleUrls: ['./component.scss']
})

export class MyComponent implements OnInit {

  mouseHover(e) {
    console.log('hovered', e);
  }
} 

Error Handler - Exit Sub vs. End Sub

Typically if you have database connections or other objects declared that, whether used safely or created prior to your exception, will need to be cleaned up (disposed of), then returning your error handling code back to the ProcExit entry point will allow you to do your garbage collection in both cases.

If you drop out of your procedure by falling to Exit Sub, you may risk having a yucky build-up of instantiated objects that are just sitting around in your program's memory.

if statements matching multiple values

How about:

if (new[] {1, 2}.Contains(value))

It's a hack though :)

Or if you don't mind creating your own extension method, you can create the following:

public static bool In<T>(this T obj, params T[] args)
{
    return args.Contains(obj);
}

And you can use it like this:

if (1.In(1, 2))

:)

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-jar-plugin:2.3.2 or one of its dependencies could not be resolved

There could be multiple reasons, i fixed with following steps:

  1. delete .m2 folder and re launch eclipse. (Find m2 folder in windows: c:\Users\Your_User_Name\ .m2 or to search in Mac : ~/.m2
  2. make sure settings.xml is configured as #JustinBieber mentioned.
  3. provide settings.xml path in eclipse (windows->preferences->maven->user settings) User Settings must locate settings.xml file.

save changes and relaunch the eclipse..!! it should work.

Getting the WordPress Post ID of current post

You can get id through below Code...Its Simple and Fast

 <?php $post_id = get_the_ID();
   echo $post_id;
   ?>

Calculating a directory's size using Python?

monknut answer is good but it fails on broken symlink, so you also have to check if this path really exists

if os.path.exists(fp):
    total_size += os.stat(fp).st_size

Does calling clone() on an array also clone its contents?

1D array of primitives does copy elements when it is cloned. This tempts us to clone 2D array(Array of Arrays).

Remember that 2D array clone doesn't work due to shallow copy implementation of clone().

public static void main(String[] args) {
    int row1[] = {0,1,2,3};
    int row2[] =  row1.clone();
    row2[0] = 10;
    System.out.println(row1[0] == row2[0]); // prints false

    int table1[][]={{0,1,2,3},{11,12,13,14}};
    int table2[][] = table1.clone();
    table2[0][0] = 100;
    System.out.println(table1[0][0] == table2[0][0]); //prints true
}

Python PDF library

Reportlab. There is an open source version, and a paid version which adds the Report Markup Language (an alternative method of defining your document).

Reading/parsing Excel (xls) files with Python

Using pandas:

import pandas as pd

xls = pd.ExcelFile(r"yourfilename.xls") #use r before absolute file path 

sheetX = xls.parse(2) #2 is the sheet number+1 thus if the file has only 1 sheet write 0 in paranthesis

var1 = sheetX['ColumnName']

print(var1[1]) #1 is the row number...

Printf width specifier to maintain precision of floating-point value

The short answer to print floating point numbers losslessly (such that they can be read back in to exactly the same number, except NaN and Infinity):

  • If your type is float: use printf("%.9g", number).
  • If your type is double: use printf("%.17g", number).

Do NOT use %f, since that only specifies how many significant digits after the decimal and will truncate small numbers. For reference, the magic numbers 9 and 17 can be found in float.h which defines FLT_DECIMAL_DIG and DBL_DECIMAL_DIG.

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

"Get" request with appending headers transform to "Options" request. So Cors policy problems occur. You have to implement "Options" request to your server.

Convert String XML fragment to Document Node in Java

/**
*
* Convert a string to a Document Object
*
* @param xml The xml to convert
* @return A document Object
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static Document string2Document(String xml) throws IOException, SAXException, ParserConfigurationException {

    if (xml == null)
    return null;

    return inputStream2Document(new ByteArrayInputStream(xml.getBytes()));

}


/**
* Convert an inputStream to a Document Object
* @param inputStream The inputstream to convert
* @return a Document Object
* @throws IOException
* @throws SAXException
* @throws ParserConfigurationException
*/
public static Document inputStream2Document(InputStream inputStream) throws IOException, SAXException, ParserConfigurationException {
    DocumentBuilderFactory newInstance = DocumentBuilderFactory.newInstance();
    newInstance.setNamespaceAware(true);
    Document parse = newInstance.newDocumentBuilder().parse(inputStream);
    return parse;
}

Xcode Objective-C | iOS: delay function / NSTimer help?

Less code is better code.

[NSThread sleepForTimeInterval:0.06];

Swift:

Thread.sleep(forTimeInterval: 0.06)

Keep values selected after form submission

Since WordPress already uses jQuery you can try something like this:

var POST=<?php echo json_encode($_POST); ?>;
for(k in POST){
  $("#"+k).val(POST[k]);
}

how to update the multiple rows at a time using linq to sql?

Do not use the ToList() method as in the accepted answer !

Running SQL profiler, I verified and found that ToList() function gets all the records from the database. It is really bad performance !!

I would have run this query by pure sql command as follows:

string query = "Update YourTable Set ... Where ...";    
context.Database.ExecuteSqlCommandAsync(query, new SqlParameter("@ColumnY", value1), new SqlParameter("@ColumnZ", value2));

This would operate the update in one-shot without selecting even one row.

Bash script error [: !=: unary operator expected

Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.

In the case the first arg is '-v', then do your conditional ps -ef, else in all other cases throw the usage.

#!/bin/sh
case $1 in
  '-v') if [ "$1" = -v ]; then
         echo "`ps -ef | grep -v '\['`"
        else
         echo "`ps -ef | grep '\[' | grep root`"
        fi;;
     *) echo "usage: $0 [-v]"
        exit 1;; #It is good practice to throw a code, hence allowing $? check
esac

If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.

#!/bin/sh

usage ()
 {
  echo "usage: $0 [-v]"
  exit 1
 }

unset arg_match

for arg in $*
 do
  case $arg in
    '-v') if [ "$arg" = -v ]; then
           echo "`ps -ef | grep -v '\['`"
          else
           echo "`ps -ef | grep '\[' | grep root`"
          fi
          arg_match=1;; # this is set, but could increment.
       *) ;;
  esac
done

if [ ! $arg_match ]
 then
  usage
fi

But, allow multiple occurrences of an argument is convenient to use in situations such as:

$ adduser -u:sam -s -f -u:bob -trace -verbose

We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:

$ adduser -u sam -s -f -u bob -trace -verbose

How to encode a string in JavaScript for displaying in HTML?

If you want to use a library rather than doing it yourself:

The most commonly used way is using jQuery for this purpose:

var safestring = $('<div>').text(unsafestring).html();

If you want to to encode all the HTML entities you will have to use a library or write it yourself.

You can use a more compact library than jQuery, like HTML Encoder and Decode

What's the difference between identifying and non-identifying relationships?

An Identifying relationship specifies that a child object cannot exist without the parent object

Non-identifying relationships specifies a regular association between objects, 1:1 or 1:n cardinality.

Non-identifying relationships can be specified as optional where a parent is not required or mandatory where a parent is required by setting the parent table cardinality...

Angular 2 Scroll to bottom (Chat style)

In case anyone has this problem with Angular 9, this is how I manage to fix it.

I started with the solution with #scrollMe [scrollTop]="scrollMe.scrollHeight" and I got the ExpressionChangedAfterItHasBeenCheckedError error as people mentioned.

In order to fix this one I just add in my ts component:

@Component({
    changeDetection: ChangeDetectionStrategy.OnPush,
...})

 constructor(private cdref: ChangeDetectorRef) {}

 ngAfterContentChecked() {
        this.cdref.detectChanges();
    }

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was checked. Previous value: 'undefined'

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

Easiest way is to throw a ResponseStatusException

    @RequestMapping(value = "/matches/{matchId}", produces = "application/json")
    @ResponseBody
    public String match(@PathVariable String matchId, @RequestBody String body) {
        String json = matchService.getMatchJson(matchId);
        if (json == null) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND);
        }
        return json;
    }

Conditional step/stage in Jenkins pipeline

Just use if and env.BRANCH_NAME, example:

    if (env.BRANCH_NAME == "deployment") {                                          
        ... do some build ...
    } else {                                   
        ... do something else ...
    }                                                                       

JQuery - Call the jquery button click event based on name property

You can use the name property for that particular element. For example to set a border of 2px around an input element with name xyz, you can use;

$(function() {
    $("input[name = 'xyz']").css("border","2px solid red");
})

DEMO

javascript get x and y coordinates on mouse click

It sounds like your printMousePos function should:

  1. Get the X and Y coordinates of the mouse
  2. Add those values to the HTML

Currently, it does this:

  1. Creates (undefined) variables for the X and Y coordinates of the mouse
  2. Attaches a function to the "mousemove" event (which will set those variables to the mouse coordinates when triggered by a mouse move)
  3. Adds the current values of your variables to the HTML

See the problem? Your variables are never getting set, because as soon as you add your function to the "mousemove" event you print them.

It seems like you probably don't need that mousemove event at all; I would try something like this:

function printMousePos(e) {
    var cursorX = e.pageX;
    var cursorY = e.pageY;
    document.getElementById('test').innerHTML = "x: " + cursorX + ", y: " + cursorY;
}

How to show x and y axes in a MATLAB graph?

Easiest solution:

plot([0,0],[0.0], xData, yData);

This creates an invisible line between the points [0,0] to [0,0] and since Matlab wants to include these points it will shows the axis.

Is there a simple way to delete a list element by value?

Finding a value in a list and then deleting that index (if it exists) is easier done by just using list's remove method:

>>> a = [1, 2, 3, 4]
>>> try:
...   a.remove(6)
... except ValueError:
...   pass
... 
>>> print a
[1, 2, 3, 4]
>>> try:
...   a.remove(3)
... except ValueError:
...   pass
... 
>>> print a
[1, 2, 4]

If you do this often, you can wrap it up in a function:

def remove_if_exists(L, value):
  try:
    L.remove(value)
  except ValueError:
    pass

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

If WorkSheet("wsName") Exists

There's no built-in function for this.

Function SheetExists(SheetName As String, Optional wb As Excel.Workbook)
   Dim s As Excel.Worksheet
   If wb Is Nothing Then Set wb = ThisWorkbook
   On Error Resume Next
   Set s = wb.Sheets(SheetName)
   On Error GoTo 0
   SheetExists = Not s Is Nothing
End Function

System.Data.OracleClient requires Oracle client software version 8.1.7

Update 1: It is possible for different users to have different path. But its not the likely problem here. There is more chance that the user that the iwam user doesn't have permission to the oracle client directory.

Update 0: Its suppose to work. Check for environment variable ( That are needed to find the oracle client and tnsnames.ora ). Also, Maybe you have a 32/64 bit issues. Also, consider using the Oracle Data Provider for .NET ( search for odp.net)

How to remove entry from $PATH on mac

when you login, or start a bash shell, environment variables are loaded/configured according to .bashrc, or .bash_profile. Whatever export you are doing, it's valid only for current session. so export PATH=/Applications/SenchaSDKTools-2.0.0-beta3:$PATH this command is getting executed each time you are opening a shell, you can override it, but again that's for the current session only. edit the .bashrc file to suite your need. If it's saying permission denied, perhaps the file is write-protected, a link to some other file (many organisations keep a master .bashrc file and gives each user a link of it to their home dir, you can copy the file instead of link and the start adding content to it)

How do you add a scroll bar to a div?

<head>
<style>
div.scroll
{
background-color:#00FFFF;
width:40%;
height:200PX;
FLOAT: left;
margin-left: 5%;
padding: 1%;
overflow:scroll;
}


</style>
</head>

<body>



<div class="scroll">You can use the overflow property when you want to have better       control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better control of the layout. The default value is visible.better </div>


</body>
</html>

Difference between Static and final?

Static is something that any object in a class can call, that inherently belongs to an object type.

A variable can be final for an entire class, and that simply means it cannot be changed anymore. It can only be set once, and trying to set it again will result in an error being thrown. It is useful for a number of reasons, perhaps you want to declare a constant, that can't be changed.

Some example code:

class someClass
{
   public static int count=0;
   public final String mName;

   someClass(String name)
   {
     mname=name;
     count=count+1;
   }

  public static void main(String args[])
  {
    someClass obj1=new someClass("obj1");
    System.out.println("count="+count+" name="+obj1.mName);
    someClass obj2=new someClass("obj2");
    System.out.println("count="+count+" name="+obj2.mName);
  }
}

Wikipedia contains the complete list of java keywords.

Difference between margin and padding?

Padding

Padding is a CSS property that defines the space between an element content and its border (if it has a border). If an element has a border around it, padding will give space from that border to the element content which appears in that border. If an element does not have a border around it, then adding padding has no effect at all on that element, because there is no border to give space from.

Margin

Margin is a CSS property that defines the space of outside of an element to its next outside element.

Margin affects elements that both have or do not have borders. If an element has a border, margin defines the space from this border to the next outer element. If an element does not have a border, then margin defines the space from the element content to the next outer element.

Difference Between Padding and Margin

So the difference between margin and padding is that while padding deals with the inner space, margin deals with the outer space to the next outer element.

Iterate through object properties

Your for loop is iterating over all of the properties of the object obj. propt is defined in the first line of your for loop. It is a string that is a name of a property of the obj object. In the first iteration of the loop, propt would be "name".

PHP Curl And Cookies

You can define different cookies for every user with CURLOPT_COOKIEFILE and CURLOPT_COOKIEJAR. Make different file for every user so each one would have it's own cookie-based session on remote server.

How to add style from code behind?

Try this:

Html Markup

<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="#">HyperLink</asp:HyperLink>

Code

using System.Drawing;
using System.Web.UI;
using System.Web.UI.WebControls;

protected void Page_Load(object sender, EventArgs e)
{
    Style style = new Style();
    style.ForeColor = Color.Green;
    this.Page.Header.StyleSheet.CreateStyleRule(style, this, "#" + HyperLink1.ClientID + ":hover");
}

Add jars to a Spark Job - spark-submit

There is restriction on using --jars: if you want to specify a directory for location of jar/xml file, it doesn't allow directory expansions. This means if you need to specify absolute path for each jar.

If you specify --driver-class-path and you are executing in yarn cluster mode, then driver class doesn't get updated. We can verify if class path is updated or not under spark ui or spark history server under tab environment.

Option which worked for me to pass jars which contain directory expansions and which worked in yarn cluster mode was --conf option. It's better to pass driver and executor class paths as --conf, which adds them to spark session object itself and those paths are reflected on Spark Configuration. But Please make sure to put jars on the same path across the cluster.

spark-submit \
  --master yarn \
  --queue spark_queue \
  --deploy-mode cluster    \
  --num-executors 12 \
  --executor-memory 4g \
  --driver-memory 8g \
  --executor-cores 4 \
  --conf spark.ui.enabled=False \
  --conf spark.driver.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapred.output.dir=/tmp \
  --conf spark.executor.extraClassPath=/usr/hdp/current/hbase-master/lib/hbase-server.jar:/usr/hdp/current/hbase-master/lib/hbase-common.jar:/usr/hdp/current/hbase-master/lib/hbase-client.jar:/usr/hdp/current/hbase-master/lib/zookeeper.jar:/usr/hdp/current/hbase-master/lib/hbase-protocol.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/scopt_2.11-3.3.0.jar:/usr/hdp/current/spark2-thriftserver/examples/jars/spark-examples_2.10-1.1.0.jar:/etc/hbase/conf \
  --conf spark.hadoop.mapreduce.output.fileoutputformat.outputdir=/tmp

AngularJS: How can I pass variables between controllers?

--- I know this answer is not for this question, but I want people who reads this question and want to handle Services such as Factories to avoid trouble doing this ----

For this you will need to use a Service or a Factory.

The services are the BEST PRACTICE to share data between not nested controllers.

A very very good annotation on this topic about data sharing is how to declare objects. I was unlucky because I fell in a AngularJS trap before I read about it, and I was very frustrated. So let me help you avoid this trouble.

I read from the "ng-book: The complete book on AngularJS" that AngularJS ng-models that are created in controllers as bare-data are WRONG!

A $scope element should be created like this:

angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
  // best practice, always use a model
  $scope.someModel = {
    someValue: 'hello computer'
  });

And not like this:

angular.module('myApp', [])
.controller('SomeCtrl', function($scope) {
  // anti-pattern, bare value
  $scope.someBareValue = 'hello computer';
  };
});

This is because it is recomended(BEST PRACTICE) for the DOM(html document) to contain the calls as

<div ng-model="someModel.someValue"></div>  //NOTICE THE DOT.

This is very helpful for nested controllers if you want your child controller to be able to change an object from the parent controller....

But in your case you don't want nested scopes, but there is a similar aspect to get objects from services to the controllers.

Lets say you have your service 'Factory' and in the return space there is an objectA that contains objectB that contains objectC.

If from your controller you want to GET the objectC into your scope, is a mistake to say:

$scope.neededObjectInController = Factory.objectA.objectB.objectC;

That wont work... Instead use only one dot.

$scope.neededObjectInController = Factory.ObjectA;

Then, in the DOM you can call objectC from objectA. This is a best practice related to factories, and most important, it will help to avoid unexpected and non-catchable errors.

How to install XCODE in windows 7 platform?

X-code is primarily made for OS-X or iPhone development on Mac systems. Versions for Windows are not available. However this might help!

There is no way to get Xcode on Windows; however you can use a different SDK like Corona instead although it will not use Objective-C (I believe it uses Lua). I have however heard that it is horrible to use.

Source: classroomm.com

What is pipe() function in Angular

Don't get confused with the concepts of Angular and RxJS

We have pipes concept in Angular and pipe() function in RxJS.

1) Pipes in Angular: A pipe takes in data as input and transforms it to the desired output
https://angular.io/guide/pipes

2) pipe() function in RxJS: You can use pipes to link operators together. Pipes let you combine multiple functions into a single function.

The pipe() function takes as its arguments the functions you want to combine, and returns a new function that, when executed, runs the composed functions in sequence.
https://angular.io/guide/rx-library (search for pipes in this URL, you can find the same)

So according to your question, you are referring pipe() function in RxJS

How do I use the Tensorboard callback of Keras?

If you are working with Keras library and want to use tensorboard to print your graphs of accuracy and other variables, Then below are the steps to follow.

step 1: Initialize the keras callback library to import tensorboard by using below command

from keras.callbacks import TensorBoard

step 2: Include the below command in your program just before "model.fit()" command.

tensor_board = TensorBoard(log_dir='./Graph', histogram_freq=0, write_graph=True, write_images=True)

Note: Use "./graph". It will generate the graph folder in your current working directory, avoid using "/graph".

step 3: Include Tensorboard callback in "model.fit()".The sample is given below.

model.fit(X_train,y_train, batch_size=batch_size, epochs=nb_epoch, verbose=1, validation_split=0.2,callbacks=[tensor_board])

step 4 : Run your code and check whether your graph folder is there in your working directory. if the above codes work correctly you will have "Graph" folder in your working directory.

step 5 : Open Terminal in your working directory and type the command below.

tensorboard --logdir ./Graph

step 6: Now open your web browser and enter the address below.

http://localhost:6006

After entering, the Tensorbaord page will open where you can see your graphs of different variables.

Bootstrap 3 truncate long text inside rows of a table in a responsive way

This is what I achieved, but had to set width, and it cannot be percentual.

_x000D_
_x000D_
.trunc{_x000D_
  width:250px; _x000D_
  white-space: nowrap; _x000D_
  overflow: hidden; _x000D_
  text-overflow: ellipsis;_x000D_
}_x000D_
table tr td {_x000D_
padding: 5px_x000D_
}_x000D_
table tr td {_x000D_
background: salmon_x000D_
}_x000D_
table tr td:first-child {_x000D_
background: lightsalmon_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<table>_x000D_
      _x000D_
      <tr>_x000D_
        <td>Quisque dignissim ante in tincidunt gravida. Maecenas lectus turpis</td>_x000D_
      <td>_x000D_
         <div class="trunc">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum._x000D_
         </div>_x000D_
    </td>_x000D_
        </tr>_x000D_
      </table>
_x000D_
_x000D_
_x000D_

or this: http://collaboradev.com/2015/03/28/responsive-css-truncate-and-ellipsis/

Disabling Minimize & Maximize On WinForm?

How to make form minimize when closing was already answered, but how to remove the minimize and maximize buttons wasn't.
FormBorderStyle: FixedDialog
MinimizeBox: false
MaximizeBox: false

Can not change UILabel text color

// This is wrong 
categoryTitle.textColor = [UIColor colorWithRed:188 green:149 blue:88 alpha:1.0];

// This should be  
categoryTitle.textColor = [UIColor colorWithRed:188/255 green:149/255 blue:88/255 alpha:1.0];

// In the documentation, the limit of the parameters are mentioned.

colorWithRed:green:blue:alpha: documentation link

How to send/receive SOAP request and response using C#?

The urls are different.

  • http://localhost/AccountSvc/DataInquiry.asmx

vs.

  • /acctinqsvc/portfolioinquiry.asmx

Resolve this issue first, as if the web server cannot resolve the URL you are attempting to POST to, you won't even begin to process the actions described by your request.

You should only need to create the WebRequest to the ASMX root URL, ie: http://localhost/AccountSvc/DataInquiry.asmx, and specify the desired method/operation in the SOAPAction header.

The SOAPAction header values are different.

  • http://localhost/AccountSvc/DataInquiry.asmx/ + methodName

vs.

  • http://tempuri.org/GetMyName

You should be able to determine the correct SOAPAction by going to the correct ASMX URL and appending ?wsdl

There should be a <soap:operation> tag underneath the <wsdl:operation> tag that matches the operation you are attempting to execute, which appears to be GetMyName.

There is no XML declaration in the request body that includes your SOAP XML.

You specify text/xml in the ContentType of your HttpRequest and no charset. Perhaps these default to us-ascii, but there's no telling if you aren't specifying them!

The SoapUI created XML includes an XML declaration that specifies an encoding of utf-8, which also matches the Content-Type provided to the HTTP request which is: text/xml; charset=utf-8

Hope that helps!

How to prove that a problem is NP complete?

First, you show that it lies in NP at all.

Then you find another problem that you already know is NP complete and show how you polynomially reduce NP Hard problem to your problem.

Why can't I push to this bare repository?

If you:

 git push origin master

it will push to the bare repo.

It sounds like your alice repo isn't tracking correctly.

cat .git/config

This will show the default remote and branch.

If you

 git push -u origin master

You should start tracking that remote and branch. I'm not sure if that option has always been in git.

Difference between objectForKey and valueForKey?

When you do valueForKey: you need to give it an NSString, whereas objectForKey: can take any NSObject subclass as a key. This is because for Key-Value Coding, the keys are always strings.

In fact, the documentation states that even when you give valueForKey: an NSString, it will invoke objectForKey: anyway unless the string starts with an @, in which case it invokes [super valueForKey:], which may call valueForUndefinedKey: which may raise an exception.

Get ID of element that called a function

Pass a reference to the element into the function when it is called:

<area id="nose" onmouseover="zoom(this);" />

<script>
  function zoom(ele) {
    var id = ele.id;

    console.log('area element id = ' + id);
  }
</script>

Init function in javascript and how it works

The way I usually explain this to people is to show how it's similar to other JavaScript patterns.

First, you should know that there are two ways to declare a function (actually, there's at least five, but these are the two main culprits):

function foo() {/*code*/}

and

var foo = function() {/*code*/};

Even if this construction looks strange, you probably use it all the time when attaching events:

window.onload=function(){/*code*/};

You should notice that the second form is not much different from a regular variable declaration:

var bar = 5;
var baz = 'some string';
var foo = function() {/*code*/};

But in JavaScript, you always have the choice between using a value directly or through a variable. If bar is 5, then the next two statements are equivalent:

var myVal = bar * 100; // use 'bar'
var myVal = 5 * 100;   // don't use 'bar'

Well, if you can use 5 on its own, why can't you use function() {\*code*\} on its own too? In fact, you can. And that's called an anonymous function. So these two examples are equivalent as well:

var foo = function() {/*code*/}; // use 'foo'
foo();                           

(function(){/*code*/})();        // don't use 'foo' 

The only difference you should see is in the extra brackets. That's simply because if you start a line with the keyword function, the parser will think you are declaring a function using the very first pattern at the top of this answer and throw a syntax error exception. So wrap your entire anonymous function inside a pair of braces and the problem goes away.

In other words, the following three statements are valid:

5;                        // pointless and stupid
'some string';            // pointless and stupid
(function(){/*code*/})(); // wonderfully powerful

[EDIT in 2020]

The previous version of my answer recommended Douglas Crockford's form of parens-wrapping for these "immediately invoked anonymous functions". User @RayLoveless recommended in 2012 to use the version shown now. Back then, before ES6 and arrow functions, there was no obvious idiomatic difference; you simply had to prevent the statement starting with the function keyword. In fact, there were lots of ways to do that. But using parens, these two statements were syntactically and idiomatically equivalent:

( function() { /* code */}() );
( function() { /* code */} )();

But user @zentechinc's comment below reminds me that arrow functions change all this. So now only one of these statements is correct.

( () => { /* code */ }() ); // Syntax error
( () => { /* code */ } )();

Why on earth does this matter? Actually, it's pretty easy to demonstrate. Remember an arrow function can come in two basic forms:

() => { return 5; };       // With a function body
() => { console.log(5); };

() => 5;                   // Or with a single expression
() => console.log(5);

Without parens wrapping this second type of arrow function, you end up with an idiomatic mess:

() => 5();              // How do you invoke a 5?
() => console.log(5)(); // console.log does not return a function!

Check which element has been clicked with jQuery

The basis of jQuery is the ability to find items in the DOM through selectors, and then checking properties on those selectors. Read up on Selectors here:

http://api.jquery.com/category/selectors/

However, it would make more sense to create event handlers for the click events for the different functionality that should occur based on what is clicked.

Read int values from a text file in C

A simple solution using fscanf:

void read_ints (const char* file_name)
{
  FILE* file = fopen (file_name, "r");
  int i = 0;

  fscanf (file, "%d", &i);    
  while (!feof (file))
    {  
      printf ("%d ", i);
      fscanf (file, "%d", &i);      
    }
  fclose (file);        
}

Uncaught SyntaxError: Invalid or unexpected token

The accepted answer work when you have a single line string(the email) but if you have a

multiline string, the error will remain.

Please look into this matter:

<!-- start: definition-->
@{
    dynamic item = new System.Dynamic.ExpandoObject();
    item.MultiLineString = @"a multi-line
                             string";
    item.SingleLineString = "a single-line string";
}
<!-- end: definition-->
<a href="#" onclick="Getinfo('@item.MultiLineString')">6/16/2016 2:02:29 AM</a>
<script>
    function Getinfo(text) {
        alert(text);
    }
</script>

Change the single-quote(') to backtick(`) in Getinfo as bellow and error will be fixed:

<a href="#" onclick="Getinfo(`@item.MultiLineString`)">6/16/2016 2:02:29 AM</a>

Why does "npm install" rewrite package-lock.json?

Probably you should use something like this

npm ci

Instead of using npm install if you don't want to change the version of your package.

According to the official documentation, both npm install and npm ci install the dependencies which are needed for the project.

The main difference is, npm install does install the packages taking packge.json as a reference. Where in the case of npm ci, it does install the packages taking package-lock.json as a reference, making sure every time the exact package is installed.

Get URL of ASP.Net Page in code-behind

Do you want the server name? Or the host name?

Request.Url.Host ala Stephen

Dns.GetHostName - Server name

Request.Url will have access to most everything you'll need to know about the page being requested.

Catch KeyError in Python

If it's raising a KeyError with no message, then it won't print anything. If you do...

try:
    connection = manager.connect("I2Cx")
except Exception as e:
    print repr(e)

...you'll at least get the exception class name.

A better alternative is to use multiple except blocks, and only 'catch' the exceptions you intend to handle...

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print 'I got a KeyError - reason "%s"' % str(e)
except IndexError as e:
    print 'I got an IndexError - reason "%s"' % str(e)

There are valid reasons to catch all exceptions, but you should almost always re-raise them if you do...

try:
    connection = manager.connect("I2Cx")
except KeyError as e:
    print 'I got a KeyError - reason "%s"' % str(e)
except:
    print 'I got another exception, but I should re-raise'
    raise

...because you probably don't want to handle KeyboardInterrupt if the user presses CTRL-C, nor SystemExit if the try-block calls sys.exit().

What's the valid way to include an image with no src?

Simply, Like this:

<img id="give_me_src"/>

nodemon command is not recognized in terminal for node js server

First, write npm install --save nodemon then in package.json write the followings

"scripts": {
    "server": "nodemon server.js"
  },

then write

npm run server

Can I run javascript before the whole page is loaded?

You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.

So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded event or functions like $.ready in jQuery.

Base64 Encoding Image

My synopsis of rfc2397 is:

Once you've got your base64 encoded image data put it inside the <Image></Image> tags prefixed with "data:{mimetype};base64," this is similar to the prefixing done in the parenthesis of url() definition in CSS or in the quoted value of the src attribute of the img tag in [X]HTML. You can test the data url in firefox by putting the data:image/... line into the URL field and pressing enter, it should show your image.

For actually encoding I think we need to go over all your options, not just PHP, because there's so many ways to base64 encode something.

  1. Use the base64 command line tool. It's part of the GNU coreutils (v6+) and pretty much default in any Cygwin, Linux, GnuWin32 install, but not the BSDs I tried. Issue: $ base64 imagefile.ico > imagefile.base64.txt
  2. Use a tool that features the option to convert to base64, like Notepad++ which has the feature under plugins->MIME tools->base64 Encode
  3. Email yourself the file and view the raw email contents, copy and paste.
  4. Use a web form.

A note on mime-types: I would prefer you use one of image/png image/jpeg or image/gif as I can't find the popular image/x-icon. Should that be image/vnd.microsoft.icon? Also the other formats are much shorter.

compare 265 bytes vs 1150 bytes:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAVFBMVEWcZjTcViTMuqT8/vzcYjTkhhTkljT87tz03sRkZmS8mnT03tT89vTsvoTk1sz86uTkekzkjmzkwpT01rTsmnzsplTUwqz89uy0jmzsrmTknkT0zqT3X4fRAAAAbklEQVR4XnXOVw6FIBBAUafQsZfX9r/PB8JoTPT+QE4o01AtMoS8HkALcH8BGmGIAvaXLw0wCqxKz0Q9w1LBfFSiJBzljVerlbYhlBO4dZHM/F3llybncbIC6N+70Q7OlUm7DdO+gKs9gyRwdgd/LOcGXHzLN5gAAAAASUVORK5CYII=

data:image/x-icon;base64,AAABAAEAEBAAAAEAIABoBAAAFgAAACgAAAAQAAAAIAAAAAEAIAAAAAAAAAQAAAAAAAAAAAAAAAAAAAAAAAD/////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv///////////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb///////////9mZmb/ZmZm//////////////////////////////////////////////////////9mZmb/ZmZm////////////ZmZm/2ZmZv//////ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv//////ZmZm/2ZmZv///////////2ZmZv9mZmb//////2ZmZv9mZmb/ZmZm/2ZmZv9mZmb/ZmZm/2ZmZv9mZmb//////2ZmZv9mZmb///////////9mZmb/ZmZm////////////////////////////8fX4/8nW5P+twtb/oLjP//////9mZmb/ZmZm////////////////////////////oLjP/3eZu/9pj7T/M2aZ/zNmmf8zZpn/M2aZ/zNmmf///////////////////////////////////////////zNmmf8zZpn/M2aZ/zNmmf8zZpn/d5m7/6C4z/+WwuH/wN/3//////////////////////////////////////+guM//rcLW/8nW5P/x9fj//////9/v+/+w1/X/QZ7m/1Cm6P//////////////////////////////////////////////////////7/f9/4C+7v8xluT/EYbg/zGW5P/A3/f/0933/9Pd9//////////////////////////////////f7/v/YK7q/xGG4P8RhuD/MZbk/7DX9f//////4uj6/zJh2/8yYdv/8PT8////////////////////////////UKbo/xGG4P8xluT/sNf1////////////4uj6/zJh2/8jVtj/e5ro/////////////////////////////////8Df9/+gz/P/////////////////8PT8/0944P8jVtj/bI7l/////////////////////////////////////////////////////////////////2yO5f8jVtj/T3jg//D0/P///////////////////////////////////////////////////////////3ua6P8jVtj/MmHb/+Lo+v////////////////////////////////////////////////////////////D0/P8yYdv/I1bY/9Pd9///////////////////////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA==

How to push object into an array using AngularJS

Please check this - http://plnkr.co/edit/5Sx4k8tbWaO1qsdMEWYI?p=preview

Controller-

var app= angular.module('app', []);

app.controller('TestController', function($scope) {
    this.arrayText = [{text:'Hello',},{text: 'world'}];

    this.addText = function(text) {

      if(text) {
        var obj = {
          text: text
        };
          this.arrayText.push(obj);
          this.myText = '';
          console.log(this.arrayText);
        }
      } 
 });

HTML

<form ng-controller="TestController as testCtrl" ng-submit="testCtrl.addText(testCtrl.myText)">
        <input type="text" ng-model="testCtrl.myText" value="Lets go">
        <button type="submit">Add</button>
        <div ng-repeat="item in testCtrl.arrayText">
            <span>{{item}}</span>
        </div>
</form>

POST request with JSON body

I think cURL would be a good solution. This is not tested, but you can try something like this:

$body = '{
  "kind": "blogger#post",
  "blog": {
    "id": "8070105920543249955"
  },
  "title": "A new post",
  "content": "With <b>exciting</b> content..."
}';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://www.googleapis.com/blogger/v3/blogs/8070105920543249955/posts/");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type: application/json","Authorization: OAuth 2.0 token here"));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $body);
$result = curl_exec($ch);

mongodb service is not starting up

This can also happen if the disk is full at your logpath path (e.g. if you have a dedicated /log/ directory/drive and it is full).

This had me panicking for a good 15 minutes because it also prevents you from reading the mongod.log when starting the process, so difficult to troubleshoot.

Difference between del, remove, and pop on lists

Remove basically works on the value . Delete and pop work on the index

Remove basically removes the first matching value. Delete deletes the item from a specific index Pop basically takes an index and returns the value at that index. Next time you print the list the value doesnt appear.

Example:

How to sort pandas data frame using values from several columns?

If you are writing this code as a script file then you will have to write it like this:

df = df.sort(['c1','c2'], ascending=[False,True])

Read a Csv file with powershell and capture corresponding data

Old topic, but never clearly answered. I've been working on similar as well, and found the solution:

The pipe (|) in this code sample from Austin isn't the delimiter, but to pipe the ForEach-Object, so if you want to use it as delimiter, you need to do this:

Import-Csv H:\Programs\scripts\SomeText.csv -delimiter "|" |`
ForEach-Object {
    $Name += $_.Name
    $Phone += $_."Phone Number"
}

Spent a good 15 minutes on this myself before I understood what was going on. Hope the answer helps the next person reading this avoid the wasted minutes! (Sorry for expanding on your comment Austin)

How to convert interface{} to string?

You don't need to use a type assertion, instead just use the %v format specifier with Sprintf:

hostAndPort := fmt.Sprintf("%v:%v", arguments["<host>"], arguments["<port>"])

Notification Icon with the new Firebase Cloud Messaging system

Unfortunately this was a limitation of Firebase Notifications in SDK 9.0.0-9.6.1. When the app is in the background the launcher icon is use from the manifest (with the requisite Android tinting) for messages sent from the console.

With SDK 9.8.0 however, you can override the default! In your AndroidManifest.xml you can set the following fields to customise the icon and color:

<meta-data
        android:name="com.google.firebase.messaging.default_notification_icon"
        android:resource="@drawable/notification_icon" />
<meta-data android:name="com.google.firebase.messaging.default_notification_color"
        android:resource="@color/google_blue" />

Note that if the app is in the foreground (or a data message is sent) you can completely use your own logic to customise the display. You can also always customise the icon if sending the message from the HTTP/XMPP APIs.

How to open the second form?

//To open the form

Form2 form2 = new Form2();

form2.Show();
// And to close
form2.Close();

Hope this helps

adb command not found

I solved this issue by install adb package. I'm using Ubuntu.

sudo apt install adb

I think this will help to you.

VirtualBox: mount.vboxsf: mounting failed with the error: No such device

I am running VirtualBox 5.1.20, and had a similar issue. Here is a url to where I found the fix, and the fix I implemented:

# https://dsin.wordpress.com/2016/08/17/ubuntu-wrong-fs-type-bad-option-bad-superblock/
if [ "5.1.20" == "${VBOXVER}" ]; then
  rm /sbin/mount.vboxsf
  ln -s /usr/lib/VBoxGuestAdditions/mount.vboxsf /sbin/mount.vboxsf
fi

The link had something similar to /usr/lib/VBoxGuestAdditions/other/mount.vboxsf, rather than what I have in the script excerpt.

For a build script I use in vagrant for the additions:

https://github.com/rburkholder/vagrant/blob/master/scripts/additions.sh

Seems to be a fix at https://www.virtualbox.org/ticket/16670

subsampling every nth entry in a numpy array

You can use numpy's slicing, simply start:stop:step.

>>> xs
array([1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4])
>>> xs[1::4]
array([2, 2, 2])

This creates a view of the the original data, so it's constant time. It'll also reflect changes to the original array and keep the whole original array in memory:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2]         # O(1), constant time
>>> b[:] = 0           # modifying the view changes original array
>>> a                  # original array is modified
array([0, 2, 0, 4, 0])

so if either of the above things are a problem, you can make a copy explicitly:

>>> a
array([1, 2, 3, 4, 5])
>>> b = a[::2].copy()  # explicit copy, O(n)
>>> b[:] = 0           # modifying the copy
>>> a                  # original is intact
array([1, 2, 3, 4, 5])

This isn't constant time, but the result isn't tied to the original array. The copy also contiguous in memory, which can make some operations on it faster.