Programs & Examples On #Deep web

Re-assign host access permission to MySQL user

Similar issue where I was getting permissions failed. On my setup, I SSH in only. So What I did to correct the issue was

sudo MySQL
SELECT User, Host FROM mysql.user WHERE Host <> '%';
MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User  | Host        |
+-------+-------------+
| root  | 169.254.0.% |
| foo   | 192.168.0.% |
| bar   | 192.168.0.% |
+-------+-------------+
4 rows in set (0.00 sec)

I need these users moved to 'localhost'. So I issued the following:

UPDATE mysql.user SET host = 'localhost' WHERE user = 'foo';
UPDATE mysql.user SET host = 'localhost' WHERE user = 'bar';

Run SELECT User, Host FROM mysql.user WHERE Host <> '%'; again and we see:

MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User  | Host        |
+-------+-------------+
| root  | 169.254.0.% |
| foo   | localhost   |
| bar   | localhost   |
+-------+-------------+
4 rows in set (0.00 sec)

And then I was able to work normally again. Hope that helps someone.

$ mysql -u foo -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 74
Server version: 10.1.23-MariaDB-9+deb9u1 Raspbian 9.0

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

Java ByteBuffer to String

the root of this question is how to decode bytes to string?

this can be done with the JAVA NIO CharSet:

public final CharBuffer decode(ByteBuffer bb)

FileChannel channel = FileChannel.open(
  Paths.get("files/text-latin1.txt", StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);

CharSet latin1 = StandardCharsets.ISO_8859_1;
CharBuffer latin1Buffer = latin1.decode(buffer);

String result = new String(latin1Buffer.array());
  • First we create a channel and read it in a buffer
  • Then decode method decodes a Latin1 buffer to a char buffer
  • We can then put the result, for instance, in a String

Clip/Crop background-image with CSS

may be you can write like this:

#graphic { 
 background-image: url(image.jpg); 
 background-position: 0 -50px; 
 width: 200px; 
 height: 100px;
}

How to write lists inside a markdown table?

An alternative approach, which I've recently implemented, is to use the div-table plugin with panflute.

This creates a table from a set of fenced divs (standard in the pandoc implementation of markdown), in a similar layout to html:

---
panflute-filters: [div-table]
panflute-path: 'panflute/docs/source'
---

::::: {.divtable}
:::: {.tcaption}
a caption here (optional), only the first paragraph is used.
::::
:::: {.thead}
[Header 1]{width=0.4 align=center}
[Header 2]{width=0.6 align=default}
::::
:::: {.trow}
::: {.tcell}

1. any
2. normal markdown
3. can go in a cell

:::
::: {.tcell}
![](https://pixabay.com/get/e832b60e2cf7043ed1584d05fb0938c9bd22ffd41cb2144894f9c57aae/bird-1771435_1280.png?attachment){width=50%}

some text
:::
::::
:::: {.trow bypara=true}
If bypara=true

Then each paragraph will be treated as a separate column
::::
any text outside a div will be ignored
:::::

Looks like:

enter image description here

Error: Unable to run mksdcard SDK tool

Just to say 16.04, I'm running

sudo apt-get install lib32z1 lib32ncurses5 libbz2-1.0:i386 lib32stdc++6

seems to work on a vanilla install after installing oracle-jdk-8

Secure Web Services: REST over HTTPS vs SOAP + WS-Security. Which is better?

See the wiki article:

In point-to-point situations confidentiality and data integrity can also be enforced on Web services through the use of Transport Layer Security (TLS), for example, by sending messages over https.

WS-Security however addresses the wider problem of maintaining integrity and confidentiality of messages until after a message was sent from the originating node, providing so called end to end security.

That is:

  • HTTPS is a transport layer (point-to-point) security mechanism
  • WS-Security is an application layer (end-to-end) security mechanism.

python mpl_toolkits installation issue

I can't comment due to the lack of reputation, but if you are on arch linux, you should be able to find the corresponding libraries on the arch repositories directly. For example for mpl_toolkits.basemap:

pacman -S python-basemap

How to change an application icon programmatically in Android?

To get the solution by Markus working I needed the first Intent so be:

Intent myLauncherIntent = new Intent(Intent.ACTION_MAIN);
            myLauncherIntent.setClassName(this,  this.getClass().getName());
            myLauncherIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

How to use vertical align in bootstrap

Prinsen's answer is the best choice. But, to fix the issue where the columns don't collapse his code needs to be surrounded by a media check statement. This way these styles are only applied when the larger columns are active. Here is the updated complete answer.

HTML:

<div class="row display-table">
    <div class="col-xs-12 col-sm-4 display-cell">
        img
    </div>
    <div class="col-xs-12 col-sm-8 display-cell">
        text
    </div>
</div>

CSS:

@media (min-width: 768px){
   .display-table{
       display: table;
       table-layout: fixed;
   }

   .display-cell{
       display: table-cell;
       vertical-align: middle;
       float: none;
   }
}

if A vs if A is not None:

It depends on the context.

I use if A: when I'm expecting A to be some sort of collection, and I only want to execute the block if the collection isn't empty. This allows the caller to pass any well-behaved collection, empty or not, and have it do what I expect. It also allows None and False to suppress execution of the block, which is occasionally convenient to calling code.

OTOH, if I expect A to be some completely arbitrary object but it could have been defaulted to None, then I always use if A is not None, as calling code could have deliberately passed a reference to an empty collection, empty string, or a 0-valued numeric type, or boolean False, or some class instance that happens to be false in boolean context.

And on the other other hand, if I expect A to be some more-specific thing (e.g. instance of a class I'm going to call methods of), but it could have been defaulted to None, and I consider default boolean conversion to be a property of the class I don't mind enforcing on all subclasses, then I'll just use if A: to save my fingers the terrible burden of typing an extra 12 characters.

Java socket API: How to tell if a connection has been closed?

I see the other answer just posted, but I think you are interactive with clients playing your game, so I may pose another approach (while BufferedReader is definitely valid in some cases).

If you wanted to... you could delegate the "registration" responsibility to the client. I.e. you would have a collection of connected users with a timestamp on the last message received from each... if a client times out, you would force a re-registration of the client, but that leads to the quote and idea below.

I have read that to actually determine whether or not a socket has been closed data must be written to the output stream and an exception must be caught. This seems like a really unclean way to handle this situation.

If your Java code did not close/disconnect the Socket, then how else would you be notified that the remote host closed your connection? Ultimately, your try/catch is doing roughly the same thing that a poller listening for events on the ACTUAL socket would be doing. Consider the following:

  • your local system could close your socket without notifying you... that is just the implementation of Socket (i.e. it doesn't poll the hardware/driver/firmware/whatever for state change).
  • new Socket(Proxy p)... there are multiple parties (6 endpoints really) that could be closing the connection on you...

I think one of the features of the abstracted languages is that you are abstracted from the minutia. Think of the using keyword in C# (try/finally) for SqlConnection s or whatever... it's just the cost of doing business... I think that try/catch/finally is the accepted and necesary pattern for Socket use.

How to revert initial git commit?

You can't. So:

rm -rf .git/
git init
git add -A
git commit -m 'Your new commit message'

Restore LogCat window within Android Studio

Choose "floating mode" then "Docker mode". It's worked for me!

How to install Android app on LG smart TV?

LG, VIZIO, SAMSUNG and PANASONIC TVs are not android based, and you cannot run APKs off of them... You should just buy a fire stick and call it a day. The only TVs that are android-based, and you can install APKs are: SONY, PHILIPS and SHARP.
#FACTS.

Unable to run Java GUI programs with Ubuntu

Check what your environment variable DISPLAY's value is. Try running a simple X application from the command line. If it works, check DISPLAY's value for the right value.

You can experiment with different values of and environment variable on a per invocation basis by doing the following on the command line:

DISPLAY=:0.0 <your-java-executable-here>

How are you calling your program?

How to delete all files and folders in a directory?

Here is the tool I ended with after reading all posts. It does

  • Deletes all that can be deleted
  • Returns false if some files remain in folder

It deals with

  • Readonly files
  • Deletion delay
  • Locked files

It doesn't use Directory.Delete because the process is aborted on exception.

    /// <summary>
    /// Attempt to empty the folder. Return false if it fails (locked files...).
    /// </summary>
    /// <param name="pathName"></param>
    /// <returns>true on success</returns>
    public static bool EmptyFolder(string pathName)
    {
        bool errors = false;
        DirectoryInfo dir = new DirectoryInfo(pathName);

        foreach (FileInfo fi in dir.EnumerateFiles())
        {
            try
            {
                fi.IsReadOnly = false;
                fi.Delete();

                //Wait for the item to disapear (avoid 'dir not empty' error).
                while (fi.Exists)
                {
                    System.Threading.Thread.Sleep(10);
                    fi.Refresh();
                }
            }
            catch (IOException e)
            {
                Debug.WriteLine(e.Message);
                errors = true;
            }
        }

        foreach (DirectoryInfo di in dir.EnumerateDirectories())
        {
            try
            {
                EmptyFolder(di.FullName);
                di.Delete();

                //Wait for the item to disapear (avoid 'dir not empty' error).
                while (di.Exists)
                {
                    System.Threading.Thread.Sleep(10);
                    di.Refresh();
                }
            }
            catch (IOException e)
            {
                Debug.WriteLine(e.Message);
                errors = true;
            }
        }

        return !errors;
    }

Add a column in a table in HIVE QL

You cannot add a column with a default value in Hive. You have the right syntax for adding the column ALTER TABLE test1 ADD COLUMNS (access_count1 int);, you just need to get rid of default sum(max_count). No changes to that files backing your table will happen as a result of adding the column. Hive handles the "missing" data by interpreting NULL as the value for every cell in that column.

So now your have the problem of needing to populate the column. Unfortunately in Hive you essentially need to rewrite the whole table, this time with the column populated. It may be easier to rerun your original query with the new column. Or you could add the column to the table you have now, then select all of its columns plus value for the new column.

You also have the option to always COALESCE the column to your desired default and leave it NULL for now. This option fails when you want NULL to have a meaning distinct from your desired default. It also requires you to depend on always remembering to COALESCE.

If you are very confident in your abilities to deal with the files backing Hive, you could also directly alter them to add your default. In general I would recommend against this because most of the time it will be slower and more dangerous. There might be some case where it makes sense though, so I've included this option for completeness.

How to pass a user / password in ansible command

you can use --extra-vars like this:

$ ansible all --inventory=10.0.1.2, -m ping \
    --extra-vars "ansible_user=root ansible_password=yourpassword"

If you're authenticating to a Linux host that's joined to a Microsoft Active Directory domain, this command line works.

ansible --module-name ping --extra-vars 'ansible_user=domain\user ansible_password=PASSWORD' --inventory 10.10.6.184, all

Multiple Python versions on the same machine?

How to install different Python versions is indeed OS dependent.

However, if you're on linux, you can use a tool like pythonbrew or pythonz to help you easily manage and switch between different versions.

Select all where [first letter starts with B]

SELECT author FROM lyrics WHERE author LIKE 'B%';

Make sure you have an index on author, though!

How do I download a file from the internet to my linux server with Bash

You can use the command wget to download from command line. Specifically, you could use

wget http://download.oracle.com/otn-pub/java/jdk/7u10-b18/jdk-7u10-linux-x64.tar.gz

However because Oracle requires you to accept a license agreement this may not work (and I am currently unable to test it).

Python time measure function

My way of doing it:

from time import time

def printTime(start):
    end = time()
    duration = end - start
    if duration < 60:
        return "used: " + str(round(duration, 2)) + "s."
    else:
        mins = int(duration / 60)
        secs = round(duration % 60, 2)
        if mins < 60:
            return "used: " + str(mins) + "m " + str(secs) + "s."
        else:
            hours = int(duration / 3600)
            mins = mins % 60
            return "used: " + str(hours) + "h " + str(mins) + "m " + str(secs) + "s."

Set a variable as start = time() before execute the function/loops, and printTime(start) right after the block.

and you got the answer.

What is the difference between Left, Right, Outer and Inner Joins?

At first you have to understand what does join do? We connect multiple table and get specific result from the joined tables. The simplest way to do this is cross join.

Lets say tableA has two column A and B. And tableB has three column C and D. If we apply cross join it will produce lot of meaningless row. Then we have to match using primary key to get actual data.

Left: it will return all records from left table and matched record from right table.

Right: it will return opposite to Left join. It will return all records from right table and matched records from left table.

Inner: This is like intersection. It will return only matched records from both table.

Outer: And this is like union. It will return all available record from both table.

Some times we don't need all of the data, and also we should need only common data or records. we can easily get it using these join methods. Remember left and right join also are outer join.

You can get all records just using cross join. But it could be expensive when it comes to millions of records. So make it simple by using left, right, inner or outer join.

thanks

Getting error "No such module" using Xcode, but the framework is there

I was getting the same error as i added couple of frameworks using Cocoapods. If we are using Pods in our project, we should use xcodeworkspace instead of xcodeproject. To run the project through xcodebuild, i added -workspace <workspacename> parameter in xcodebuild command and it worked perfectly.

How to check Spark Version

Addition to @Binary Nerd

If you are using Spark, use the following to get the Spark version:

spark-submit --version

or

Login to the Cloudera Manager and goto Hosts page then run inspect hosts in cluster

Spring-Security-Oauth2: Full authentication is required to access this resource

The client_id and client_secret, by default, should go in the Authorization header, not the form-urlencoded body.

  1. Concatenate your client_id and client_secret, with a colon between them: [email protected]:12345678.
  2. Base 64 encode the result: YWJjQGdtYWlsLmNvbToxMjM0NTY3OA==
  3. Set the Authorization header: Authorization: Basic YWJjQGdtYWlsLmNvbToxMjM0NTY3OA==

java.lang.ClassNotFoundException on working app

Something like this happened when I changed the build target to 3.2. After digging around I found that a had named the jar lib folder "lib" instead of "libs". I just renamed it to libs and updated the references on the Java build path and everything was working again. Maybe this will help someone...

How to draw circle in html page?

As of 2015, you can make it and center the text with as few as 15 lines of CSS (Fiddle):

_x000D_
_x000D_
body {_x000D_
  background-color: #fff;_x000D_
}_x000D_
#circle {_x000D_
  position: relative;_x000D_
  background-color: #09f;_x000D_
  margin: 20px auto;_x000D_
  width: 400px;_x000D_
  height: 400px;_x000D_
  border-radius: 200px;_x000D_
}_x000D_
#text {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  color: #fff;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="UTF-8">_x000D_
  <title>circle with text</title>_x000D_
_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div id="circle">_x000D_
    <div id="text">Text in the circle</div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Without any -webkit-s, this works on IE11, Firefox, Chrome and Opera, and it is valid HTML5 (experimental) and CSS3.

Same on MS Edge (2020).

string decode utf-8

the core functions are getBytes(String charset) and new String(byte[] data). you can use these functions to do UTF-8 decoding.

UTF-8 decoding actually is a string to string conversion, the intermediate buffer is a byte array. since the target is an UTF-8 string, so the only parameter for new String() is the byte array, which calling is equal to new String(bytes, "UTF-8")

Then the key is the parameter for input encoded string to get internal byte array, which you should know beforehand. If you don't, guess the most possible one, "ISO-8859-1" is a good guess for English user.

The decoding sentence should be

String decoded = new String(encoded.getBytes("ISO-8859-1"));

Is there any way to do HTTP PUT in python

import urllib2
opener = urllib2.build_opener(urllib2.HTTPHandler)
request = urllib2.Request('http://example.org', data='your_put_data')
request.add_header('Content-Type', 'your/contenttype')
request.get_method = lambda: 'PUT'
url = opener.open(request)

Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432?

I often encounter this problem on windows,the way I solved the problem is Service - Click PostgreSQL Database Server 8.3 - Click the second tab "log in" - choose the first line "the local system account".

Recursion in Python? RuntimeError: maximum recursion depth exceeded while calling a Python object

I've changed the recursion to iteration.

def MovingTheBall(listOfBalls,position,numCell):
while 1:
    stop=1
    positionTmp = (position[0]+choice([-1,0,1]),position[1]+choice([-1,0,1]),0)
    for i in range(0,len(listOfBalls)):
        if positionTmp==listOfBalls[i].pos:
            stop=0
    if stop==1:
        if (positionTmp[0]==0 or positionTmp[0]>=numCell or positionTmp[0]<=-numCell or positionTmp[1]>=numCell or positionTmp[1]<=-numCell):
            stop=0
        else:
            return positionTmp

Works good :D

What exactly is LLVM?

LLVM is a library that is used to construct, optimize and produce intermediate and/or binary machine code.

LLVM can be used as a compiler framework, where you provide the "front end" (parser and lexer) and the "back end" (code that converts LLVM's representation to actual machine code).

LLVM can also act as a JIT compiler - it has support for x86/x86_64 and PPC/PPC64 assembly generation with fast code optimizations aimed for compilation speed.

Unfortunately disabled since 2013, there was the ability to play with LLVM's machine code generated from C or C++ code at the demo page.

Number of elements in a javascript object

function count(){
    var c= 0;
    for(var p in this) if(this.hasOwnProperty(p))++c;
    return c;
}

var O={a: 1, b: 2, c: 3};

count.call(O);

Change the "From:" address in Unix "mail"

I derived this from all the above answers. Nothing worked for me when I tried each one of them. I did lot of trail and error by combining all the above answers and concluded on this. I am not sure if this works for you but it worked for me on Ununtu 12.04 and RHEL 5.4.

echo "This is the body of the mail" | mail -s 'This is the subject' '<[email protected]>,<[email protected]>' -- -F '<SenderName>' -f '<[email protected]>'

One can send the mail to any number of people by adding any number of receiver id's and the mail is sent by SenderName from [email protected]

Hope this helps.

Python: Converting from ISO-8859-1/latin1 to UTF-8

concept = concept.encode('ascii', 'ignore') 
concept = MySQLdb.escape_string(concept.decode('latin1').encode('utf8').rstrip())

I do this, I am not sure if that is a good approach but it works everytime !!

Prevent text selection after double click

or, on mozilla:

document.body.onselectstart = function() { return false; } // Or any html object

On IE,

document.body.onmousedown = function() { return false; } // valid for any html object as well

Git for beginners: The definitive practical guide

I got started with the official Git tutorial. I think it's practical enough for beginners (I was, and still am, a beginner, by your definition! I barely grasp makefiles, I've only played a bit with Apache Subversion, etc.).

How to add images in select list?

You already have several answers that suggest using JavaScript/jQuery. I am going to add an alternative that only uses HTML and CSS without any JS.

The basic idea is to use a set of radio buttons and labels (that will activate/deactivate the radio buttons), and with CSS control that only the label associated to the selected radio button will be displayed. If you want to allow selecting multiple values, you could achieve it by using checkboxes instead of radio buttons.

Here is an example. The code may be a bit messier (specially compared to the other solutions):

_x000D_
_x000D_
.select-sim {_x000D_
  width:200px;_x000D_
  height:22px;_x000D_
  line-height:22px;_x000D_
  vertical-align:middle;_x000D_
  position:relative;_x000D_
  background:white;_x000D_
  border:1px solid #ccc;_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
.select-sim::after {_x000D_
  content:"?";_x000D_
  font-size:0.5em;_x000D_
  font-family:arial;_x000D_
  position:absolute;_x000D_
  top:50%;_x000D_
  right:5px;_x000D_
  transform:translate(0, -50%);_x000D_
}_x000D_
_x000D_
.select-sim:hover::after {_x000D_
  content:"";_x000D_
}_x000D_
_x000D_
.select-sim:hover {_x000D_
  overflow:visible;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options .option label {_x000D_
  display:inline-block;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options {_x000D_
  background:white;_x000D_
  border:1px solid #ccc;_x000D_
  position:absolute;_x000D_
  top:-1px;_x000D_
  left:-1px;_x000D_
  width:100%;_x000D_
  height:88px;_x000D_
  overflow-y:scroll;_x000D_
}_x000D_
_x000D_
.select-sim .options .option {_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options .option {_x000D_
  height:22px;_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
.select-sim .options .option img {_x000D_
  vertical-align:middle;_x000D_
}_x000D_
_x000D_
.select-sim .options .option label {_x000D_
  display:none;_x000D_
}_x000D_
_x000D_
.select-sim .options .option input {_x000D_
  width:0;_x000D_
  height:0;_x000D_
  overflow:hidden;_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
  float:left;_x000D_
  display:inline-block;_x000D_
  /* fix specific for Firefox */_x000D_
  position: absolute;_x000D_
  left: -10000px;_x000D_
}_x000D_
_x000D_
.select-sim .options .option input:checked + label {_x000D_
  display:block;_x000D_
  width:100%;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options .option input + label {_x000D_
  display:block;_x000D_
}_x000D_
_x000D_
.select-sim:hover .options .option input:checked + label {_x000D_
  background:#fffff0;_x000D_
}
_x000D_
<div class="select-sim" id="select-color">_x000D_
  <div class="options">_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="" id="color-" checked />_x000D_
      <label for="color-">_x000D_
        <img src="http://placehold.it/22/ffffff/ffffff" alt="" /> Select an option_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="red" id="color-red" />_x000D_
      <label for="color-red">_x000D_
        <img src="http://placehold.it/22/ff0000/ffffff" alt="" /> Red_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="green" id="color-green" />_x000D_
      <label for="color-green">_x000D_
        <img src="http://placehold.it/22/00ff00/ffffff" alt="" /> Green_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="blue" id="color-blue" />_x000D_
      <label for="color-blue">_x000D_
        <img src="http://placehold.it/22/0000ff/ffffff" alt="" /> Blue_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="yellow" id="color-yellow" />_x000D_
      <label for="color-yellow">_x000D_
        <img src="http://placehold.it/22/ffff00/ffffff" alt="" /> Yellow_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="pink" id="color-pink" />_x000D_
      <label for="color-pink">_x000D_
        <img src="http://placehold.it/22/ff00ff/ffffff" alt="" /> Pink_x000D_
      </label>_x000D_
    </div>_x000D_
    <div class="option">_x000D_
      <input type="radio" name="color" value="turquoise" id="color-turquoise" />_x000D_
      <label for="color-turquoise">_x000D_
        <img src="http://placehold.it/22/00ffff/ffffff" alt="" /> Turquoise_x000D_
      </label>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Concatenating variables and strings in React

exampleData=

        const json1 = [
            {id: 1, test: 1},
            {id: 2, test: 2},
            {id: 3, test: 3},
            {id: 4, test: 4},
            {id: 5, test: 5}
        ];

        const json2 = [
            {id: 3, test: 6},
            {id: 4, test: 7},
            {id: 5, test: 8},
            {id: 6, test: 9},
            {id: 7, test: 10}
        ];

example1=


        const finalData1 = json1.concat(json2).reduce(function (index, obj) {
            index[obj.id] = Object.assign({}, obj, index[obj.id]);
            return index;
        }, []).filter(function (res, obj) {
            return obj;
        });

example2=

        let hashData = new Map();

        json1.concat(json2).forEach(function (obj) {
            hashData.set(obj.id, Object.assign(hashData.get(obj.id) || {}, obj))
        });

        const finalData2 = Array.from(hashData.values());

I recommend second example , it is faster.

Download File Using jQuery

I suggest you use the mousedown event, which is called BEFORE the click event. That way, the browser handles the click event naturally, which avoids any code weirdness:

(function ($) {


    // with this solution, the browser handles the download link naturally (tested in chrome and firefox)
    $(document).ready(function () {

        var url = '/private/downloads/myfile123.pdf';
        $("a").on('mousedown', function () {
            $(this).attr("href", url);
        });

    });
})(jQuery);

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

Easiest way is use this way

my_var=`echo 2` echo $my_var output : 2

note that is not simple single quote is back quote ( ` ).

PHP max_input_vars

Just to complement. On a shared server using mod_suphp I was having the same issue.

Declaring 4 max_input_vars (suhosin included), didn't solved it, it just kept truncating on 1000 vars (default), and declaring "php_value max_input_vars 6000" on .htaccess threw error 500.

What solved it was to add the following on .htaccess, which applies the php.ini file recursively to that path

suPHP_ConfigPath /home/myuser/public_html

Check if a variable is null in plsql

if var is NULL then
  var :=5;
end if;

How to redirect a URL path in IIS?

Format the redirect URL in the following way:

stuff.mysite.org.uk$S$Q

The $S will say that any path must be applied to the new URL. $Q says that any parameter variables must be passed to the new URL.

In IIS 7.0, you must enable the option Redirect to exact destination. I believe there must be an option like this in IIS 6.0 too.

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

Maybe useful for anyone else running into this issue: When setting the port on the properties:

props.put("mail.smtp.port", smtpPort);

..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.

JWT (JSON Web Token) library for Java

By referring to https://jwt.io/ you can find jwt implementations in many languages including java. Also the site provide some comparison between these implementation (the algorithms they support and ....).

For java these are mentioned libraries:

How to make the 'cut' command treat same sequental delimiters as one?

shortest/friendliest solution

After becoming frustrated with the too many limitations of cut, I wrote my own replacement, which I called cuts for "cut on steroids".

cuts provides what is likely the most minimalist solution to this and many other related cut/paste problems.

One example, out of many, addressing this particular question:

$ cat text.txt
0   1        2 3
0 1          2   3 4

$ cuts 2 text.txt
2
2

cuts supports:

  • auto-detection of most common field-delimiters in files (+ ability to override defaults)
  • multi-char, mixed-char, and regex matched delimiters
  • extracting columns from multiple files with mixed delimiters
  • offsets from end of line (using negative numbers) in addition to start of line
  • automatic side-by-side pasting of columns (no need to invoke paste separately)
  • support for field reordering
  • a config file where users can change their personal preferences
  • great emphasis on user friendliness & minimalist required typing

and much more. None of which is provided by standard cut.

See also: https://stackoverflow.com/a/24543231/1296044

Source and documentation (free software): http://arielf.github.io/cuts/

How can I deserialize JSON to a simple Dictionary<string,string> in ASP.NET?

For anyone who is trying to convert JSON to dictionary just for retrieving some value out of it. There is a simple way using Newtonsoft.JSON

using Newtonsoft.Json.Linq
...

JObject o = JObject.Parse(@"{
  'CPU': 'Intel',
  'Drives': [
    'DVD read/writer',
    '500 gigabyte hard drive'
  ]
}");

string cpu = (string)o["CPU"];
// Intel

string firstDrive = (string)o["Drives"][0];
// DVD read/writer

IList<string> allDrives = o["Drives"].Select(t => (string)t).ToList();
// DVD read/writer
// 500 gigabyte hard drive

python how to pad numpy array with zeros

I know I'm a bit late to this, but in case you wanted to perform relative padding (aka edge padding), here's how you can implement it. Note that the very first instance of assignment results in zero-padding, so you can use this for both zero-padding and relative padding (this is where you copy the edge values of the original array into the padded array).

def replicate_padding(arr):
    """Perform replicate padding on a numpy array."""
    new_pad_shape = tuple(np.array(arr.shape) + 2) # 2 indicates the width + height to change, a (512, 512) image --> (514, 514) padded image.
    padded_array = np.zeros(new_pad_shape) #create an array of zeros with new dimensions
    
    # perform replication
    padded_array[1:-1,1:-1] = arr        # result will be zero-pad
    padded_array[0,1:-1] = arr[0]        # perform edge pad for top row
    padded_array[-1, 1:-1] = arr[-1]     # edge pad for bottom row
    padded_array.T[0, 1:-1] = arr.T[0]   # edge pad for first column
    padded_array.T[-1, 1:-1] = arr.T[-1] # edge pad for last column
    
    #at this point, all values except for the 4 corners should have been replicated
    padded_array[0][0] = arr[0][0]     # top left corner
    padded_array[-1][0] = arr[-1][0]   # bottom left corner
    padded_array[0][-1] = arr[0][-1]   # top right corner 
    padded_array[-1][-1] = arr[-1][-1] # bottom right corner

    return padded_array

Complexity Analysis:

The optimal solution for this is numpy's pad method. After averaging for 5 runs, np.pad with relative padding is only 8% better than the function defined above. This shows that this is fairly an optimal method for relative and zero-padding padding.


#My method, replicate_padding
start = time.time()
padded = replicate_padding(input_image)
end = time.time()
delta0 = end - start

#np.pad with edge padding
start = time.time()
padded = np.pad(input_image, 1, mode='edge')
end = time.time()
delta = end - start


print(delta0) # np Output: 0.0008790493011474609 
print(delta)  # My Output: 0.0008130073547363281
print(100*((delta0-delta)/delta)) # Percent difference: 8.12316715542522%

UICollectionView - dynamic cell height?

TL;DR: Scan down to image, and then check out working project here.

Updating my answer for a simpler solution that I found..

In my case, I wanted to fix the width, and have variable height cells. I wanted a drop in, reusable solution that handled rotation and didn't require a lot of intervention.

What I arrived at, was override (just) systemLayoutFitting(...) in the collection cell (in this case a base class for me), and first defeat UICollectionView's effort to set the wrong dimension on contentView by adding a constraint for the known dimension, in this case, the width.

class EstimatedWidthCell: UICollectionViewCell {
    override init(frame: CGRect) {
        super.init(frame: frame)
        contentView.translatesAutoresizingMaskIntoConstraints = false
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        contentView.translatesAutoresizingMaskIntoConstraints = false
    }

    override func systemLayoutSizeFitting(
        _ targetSize: CGSize, withHorizontalFittingPriority
        horizontalFittingPriority: UILayoutPriority,
        verticalFittingPriority: UILayoutPriority) -> CGSize {

        width.constant = targetSize.width

and then return the final size for the cell - used for (and this feels like a bug) the dimension of the cell itself, but not contentView - which is otherwise constrained to a conflicting size (hence the constraint above). To calculate the correct cell size, I use a lower priority for the dimension that I wanted to float, and I get back the height required to fit the content within the width to which I want to fix:

        let size = contentView.systemLayoutSizeFitting(
            CGSize(width: targetSize.width, height: 1),
            withHorizontalFittingPriority: .required,
            verticalFittingPriority: verticalFittingPriority)

        print("\(#function) \(#line) \(targetSize) -> \(size)")
        return size
    }

    lazy var width: NSLayoutConstraint = {
        return contentView.widthAnchor
            .constraint(equalToConstant: bounds.size.width)
            .isActive(true)
    }()
}

But where does this width come from? It is configured via the estimatedItemSize on the collection view's flow layout:

lazy var collectionView: UICollectionView = {
    let view = UICollectionView(frame: CGRect(), collectionViewLayout: layout)
    view.backgroundColor = .cyan
    view.translatesAutoresizingMaskIntoConstraints = false
    return view
}()

lazy var layout: UICollectionViewFlowLayout = {
    let layout = UICollectionViewFlowLayout()
    let width = view.bounds.size.width // should adjust for inset
    layout.estimatedItemSize = CGSize(width: width, height: 10)
    layout.scrollDirection = .vertical
    return layout
}()

Finally, to handle rotation, I implement trailCollectionDidChange to invalidate the layout:

override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
    layout.estimatedItemSize = CGSize(width: view.bounds.size.width, height: 10)
    layout.invalidateLayout()
    super.traitCollectionDidChange(previousTraitCollection)
}

The final result looks like this:

enter image description here

And I have published a working sample here.

How to convert int to date in SQL Server 2008

You most likely want to examine the documentation for T-SQL's CAST and CONVERT functions, located in the documentation here: http://msdn.microsoft.com/en-US/library/ms187928(v=SQL.90).aspx

You will then use one of those functions in your T-SQL query to convert the [idate] column from the database into the datetime format of your liking in the output.

PHP Include for HTML?

I have a similar issue. It appears that PHP does not like php code inside included file. In your case solution is quite simple. Remove php code from navbar.php, simply leave plain HTML in it and it will work.

How do you switch pages in Xamarin.Forms?

Call:

((App)App.Current).ChangeScreen(new Map());

Create this method inside App.xaml.cs:

public void ChangeScreen(Page page)
{
     MainPage = page;
}

What is DOM Event delegation?

Delegation is a technique where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object. This sounds at first very similar to the proxy pattern, but it serves a much different purpose. Delegation is an abstraction mechanism which centralizes object (method) behavior.

Generally spoken: use delegation as alternative to inheritance. Inheritance is a good strategy, when a close relationship exist in between parent and child object, however, inheritance couples objects very closely. Often, delegation is the more flexible way to express a relationship between classes.

This pattern is also known as "proxy chains". Several other design patterns use delegation - the State, Strategy and Visitor Patterns depend on it.

Find non-ASCII characters in varchar columns using SQL Server

Here is a solution for the single column search using PATINDEX.
It also displays the StartPosition, InvalidCharacter and ASCII code.

select line,
  patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line) as [Position],
  substring(line,patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line),1) as [InvalidCharacter],
  ascii(substring(line,patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line),1)) as [ASCIICode]
from  staging.APARMRE1
where patindex('%[^ !-~]%' COLLATE Latin1_General_BIN,Line) >0

Can the Unix list command 'ls' output numerical chmod permissions?

You don't use ls to get a file's permission information. You use the stat command. It will give you the numerical values you want. The "Unix Way" says that you should invent your own script using ls (or 'echo *') and stat and whatever else you like to give the information in the format you desire.

java.io.FileNotFoundException: (Access is denied)

Here's a gotcha that I just discovered - perhaps it might help someone else. If using windows the classes folder must not have encryption enabled! Tomcat doesn't seem to like that. Right click on the classes folder, select "Properties" and then click the "Advanced..." button. Make sure the "Encrypt contents to secure data" checkbox is cleared. Restart Tomcat.

It worked for me so here's hoping it helps someone else, too.

Invisible characters - ASCII

There is actually a truly invisible character: U+FEFF. This character is called the Byte Order Mark and is related to the Unicode 8 system. It is a really confusing concept that can be explained HERE The Byte Order Mark or BOM for short is an invisible character that doesn't take up any space. You can copy the character bellow between the > and <.

Here is the character:

> <

How to catch this character in action:

  • Copy the character between the > and <,
  • Write a line of text, then randomly put your caret in the line of text
  • Paste the character in the line.
  • Go to the beginning of the line and press and hold the right arrow key.

You will notice that when your caret gets to the place you pasted the character, it will briefly stop for around half a second. This is becuase the caret is passing over the invisible character. Even though you can't see it doesn't mean it isn't there. The caret still sees that there is a character in that area that you pasted the BOM and will pass through it. Since the BOM is invisble, the caret will look like it has paused for a brief moment. You can past the BOM multiple times in an area and redo the steps above to really show the affect. Good luck!

EDIT: Sadly, Stackoverflow doesn't like the character. Here is an example from w3.org: https://www.w3.org/International/questions/examples/phpbomtest.php

mysql: SOURCE error 2?

It's probably the file path to your file. If you don't know the exact location of the file you want to use, try to find your file in Finder, then drag the file into Terminal window

mysql> SOURCE dragfilePathHere 

SQL: How to get the count of each distinct value in a column?

SELECT
  category,
  COUNT(*) AS `num`
FROM
  posts
GROUP BY
  category

How do I set the colour of a label (coloured text) in Java?

You can set the color of a JLabel by altering the foreground category:

JLabel title = new JLabel("I love stackoverflow!", JLabel.CENTER);

title.setForeground(Color.white);

As far as I know, the simplest way to create the two-color label you want is to simply make two labels, and make sure they get placed next to each other in the proper order.

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

I have just cooked up another solution for this, where it's not longer necessary to use a -much to high- max-height value. It needs a few lines of javascript code to calculate the inner height of the collapsed DIV but after that, it's all CSS.

1) Fetching and setting height

Fetch the inner height of the collapsed element (using scrollHeight). My element has a class .section__accordeon__content and I actually run this in a forEach() loop to set the height for all panels, but you get the idea.

document.querySelectorAll( '.section__accordeon__content' ).style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";

2) Use the CSS variable to expand the active item

Next, use the CSS variable to set the max-height value when the item has an .active class.

.section__accordeon__content.active {
  max-height: var(--accordeon-height);
}

Final example

So the full example goes like this: first loop through all accordeon panels and store their scrollHeight values as CSS variables. Next use the CSS variable as the max-height value on the active/expanded/open state of the element.

Javascript:

document.querySelectorAll( '.section__accordeon__content' ).forEach(
  function( accordeonPanel ) {
    accordeonPanel.style.cssText = "--accordeon-height: " + accordeonPanel.scrollHeight + "px";
  }
);

CSS:

.section__accordeon__content {
  max-height: 0px;
  overflow: hidden;
  transition: all 425ms cubic-bezier(0.465, 0.183, 0.153, 0.946);
}

.section__accordeon__content.active {
  max-height: var(--accordeon-height);
}

And there you have it. A adaptive max-height animation using only CSS and a few lines of JavaScript code (no jQuery required).

Hope this helps someone in the future (or my future self for reference).

Difference between F5, Ctrl + F5 and click on refresh button?

F5 and the refresh button will look at your browser cache before asking the server for content.

Ctrl + F5 forces a load from the server.

You can set content expiration headers and/or meta tags to ensure the browser doesn't cache anything (perhaps something you can do only for the development environment).

How do you completely remove Ionic and Cordova installation from mac?

1) first remove cordova cmd

npm uninstall -g cordova

2) After that remove ionic

npm uninstall -g ionic

using stored procedure in entity framework

You can call a stored procedure using SqlQuery (See here)

// Prepare the query
var query = context.Functions.SqlQuery(
    "EXEC [dbo].[GetFunctionByID] @p1", 
    new SqlParameter("p1", 200));

// add NoTracking() if required

// Fetch the results
var result = query.ToList();

Creating a new user and password with Ansible

How to create encrypted password for passing to password var to Ansible user task (from @Brendan Wood's comment):

openssl passwd -salt 'some_plain_salt' -1 'some_plain_pass'

The result will look like:

$1$some_pla$lmVKJwdV3Baf.o.F0OOy71

Example of user task:

- name: Create user
  user: name="my_user" password="$1$some_pla$lmVKJwdV3Baf.o.F0OOy71"

UPD: crypt using SHA-512 see here and here:

Python

$ python -c "import crypt, getpass, pwd; print crypt.crypt('password', '\$6\$saltsalt\$')"

$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/

Perl

$ perl -e 'print crypt("password","\$6\$saltsalt\$") . "\n"'

$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/

Ruby

$ ruby -e 'puts "password".crypt("$6$saltsalt$")'

$6$saltsalt$qFmFH.bQmmtXzyBY0s9v7Oicd2z4XSIecDzlB5KiA2/jctKu9YterLp8wwnSq.qc.eoxqOmSuNp2xS0ktL3nh/

In Java, how do I get the difference in seconds between 2 dates?

I should like to provide the modern answer. The other answers were fine when this question was asked, but time moves on. Today I recommend you use java.time, the modern Java date and time API.

    ZonedDateTime aDateTime = ZonedDateTime.of(2017, 12, 8, 19, 25, 48, 991000000, ZoneId.of("Europe/Sarajevo"));
    ZonedDateTime otherDateTime = ZonedDateTime.of(2017, 12, 8, 20, 10, 38, 238000000, ZoneId.of("Europe/Sarajevo"));

    long diff = ChronoUnit.SECONDS.between(aDateTime, otherDateTime);
    System.out.println("Difference: " + diff + " seconds");

This prints:

Difference: 2689 seconds

ChronoUnit.SECONDS.between() works with two ZonedDateTime objects or two OffsetDateTimes, two LocalDateTimes, etc.

If you need anything else than just the seconds, you should consider using the Duration class:

    Duration dur = Duration.between(aDateTime, otherDateTime);
    System.out.println("Duration: " + dur);
    System.out.println("Difference: " + dur.getSeconds() + " seconds");

This prints:

Duration: PT44M49.247S
Difference: 2689 seconds

The former of the two lines prints the duration in ISO 8601 format, the output means a duration of 44 minutes and 49.247 seconds.

Why java.time?

The Date class used in several of the other answers is now long outdated. Joda-Time also used in a couple (and possibly in the question) is now in maintenance mode, no major enhancements are planned, and the developers officially recommend migrating to java.time, also known as JSR-310.

Question: Can I use the modern API with my Java version?

If using at least Java 6, you can.

PHP: Calling another class' method

//file1.php
<?php

class ClassA
{
   private $name = 'John';

   function getName()
   {
     return $this->name;
   }   
}
?>

//file2.php
<?php
   include ("file1.php");

   class ClassB
   {

     function __construct()
     {
     }

     function callA()
     {
       $classA = new ClassA();
       $name = $classA->getName();
       echo $name;    //Prints John
     }
   }

   $classb = new ClassB();
   $classb->callA();
?>

How can I get an int from stdio in C?

The typical way is with scanf:

int input_value;

scanf("%d", &input_value);

In most cases, however, you want to check whether your attempt at reading input succeeded. scanf returns the number of items it successfully converted, so you typically want to compare the return value against the number of items you expected to read. In this case you're expecting to read one item, so:

if (scanf("%d", &input_value) == 1)
    // it succeeded
else
    // it failed

Of course, the same is true of all the scanf family (sscanf, fscanf and so on).

Add jars to a Spark Job - spark-submit

ClassPath:

ClassPath is affected depending on what you provide. There are a couple of ways to set something on the classpath:

  • spark.driver.extraClassPath or it's alias --driver-class-path to set extra classpaths on the node running the driver.
  • spark.executor.extraClassPath to set extra class path on the Worker nodes.

If you want a certain JAR to be effected on both the Master and the Worker, you have to specify these separately in BOTH flags.

Separation character:

Following the same rules as the JVM:

  • Linux: A colon :
    • e.g: --conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar:/opt/prog/aws-java-sdk-1.10.50.jar"
  • Windows: A semicolon ;
    • e.g: --conf "spark.driver.extraClassPath=/opt/prog/hadoop-aws-2.7.1.jar;/opt/prog/aws-java-sdk-1.10.50.jar"

File distribution:

This depends on the mode which you're running your job under:

  1. Client mode - Spark fires up a Netty HTTP server which distributes the files on start up for each of the worker nodes. You can see that when you start your Spark job:

    16/05/08 17:29:12 INFO HttpFileServer: HTTP File server directory is /tmp/spark-48911afa-db63-4ffc-a298-015e8b96bc55/httpd-84ae312b-5863-4f4c-a1ea-537bfca2bc2b
    16/05/08 17:29:12 INFO HttpServer: Starting HTTP Server
    16/05/08 17:29:12 INFO Utils: Successfully started service 'HTTP file server' on port 58922.
    16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/foo.jar at http://***:58922/jars/com.mycode.jar with timestamp 1462728552732
    16/05/08 17:29:12 INFO SparkContext: Added JAR /opt/aws-java-sdk-1.10.50.jar at http://***:58922/jars/aws-java-sdk-1.10.50.jar with timestamp 1462728552767
    
  2. Cluster mode - In cluster mode spark selected a leader Worker node to execute the Driver process on. This means the job isn't running directly from the Master node. Here, Spark will not set an HTTP server. You have to manually make your JARS available to all the worker node via HDFS/S3/Other sources which are available to all nodes.

Accepted URI's for files

In "Submitting Applications", the Spark documentation does a good job of explaining the accepted prefixes for files:

When using spark-submit, the application jar along with any jars included with the --jars option will be automatically transferred to the cluster. Spark uses the following URL scheme to allow different strategies for disseminating jars:

  • file: - Absolute paths and file:/ URIs are served by the driver’s HTTP file server, and every executor pulls the file from the driver HTTP server.
  • hdfs:, http:, https:, ftp: - these pull down files and JARs from the URI as expected
  • local: - a URI starting with local:/ is expected to exist as a local file on each worker node. This means that no network IO will be incurred, and works well for large files/JARs that are pushed to each worker, or shared via NFS, GlusterFS, etc.

Note that JARs and files are copied to the working directory for each SparkContext on the executor nodes.

As noted, JARs are copied to the working directory for each Worker node. Where exactly is that? It is usually under /var/run/spark/work, you'll see them like this:

drwxr-xr-x    3 spark spark   4096 May 15 06:16 app-20160515061614-0027
drwxr-xr-x    3 spark spark   4096 May 15 07:04 app-20160515070442-0028
drwxr-xr-x    3 spark spark   4096 May 15 07:18 app-20160515071819-0029
drwxr-xr-x    3 spark spark   4096 May 15 07:38 app-20160515073852-0030
drwxr-xr-x    3 spark spark   4096 May 15 08:13 app-20160515081350-0031
drwxr-xr-x    3 spark spark   4096 May 18 17:20 app-20160518172020-0032
drwxr-xr-x    3 spark spark   4096 May 18 17:20 app-20160518172045-0033

And when you look inside, you'll see all the JARs you deployed along:

[*@*]$ cd /var/run/spark/work/app-20160508173423-0014/1/
[*@*]$ ll
total 89988
-rwxr-xr-x 1 spark spark   801117 May  8 17:34 awscala_2.10-0.5.5.jar
-rwxr-xr-x 1 spark spark 29558264 May  8 17:34 aws-java-sdk-1.10.50.jar
-rwxr-xr-x 1 spark spark 59466931 May  8 17:34 com.mycode.code.jar
-rwxr-xr-x 1 spark spark  2308517 May  8 17:34 guava-19.0.jar
-rw-r--r-- 1 spark spark      457 May  8 17:34 stderr
-rw-r--r-- 1 spark spark        0 May  8 17:34 stdout

Affected options:

The most important thing to understand is priority. If you pass any property via code, it will take precedence over any option you specify via spark-submit. This is mentioned in the Spark documentation:

Any values specified as flags or in the properties file will be passed on to the application and merged with those specified through SparkConf. Properties set directly on the SparkConf take highest precedence, then flags passed to spark-submit or spark-shell, then options in the spark-defaults.conf file

So make sure you set those values in the proper places, so you won't be surprised when one takes priority over the other.

Lets analyze each option in question:

  • --jars vs SparkContext.addJar: These are identical, only one is set through spark submit and one via code. Choose the one which suites you better. One important thing to note is that using either of these options does not add the JAR to your driver/executor classpath, you'll need to explicitly add them using the extraClassPath config on both.
  • SparkContext.addJar vs SparkContext.addFile: Use the former when you have a dependency that needs to be used with your code. Use the latter when you simply want to pass an arbitrary file around to your worker nodes, which isn't a run-time dependency in your code.
  • --conf spark.driver.extraClassPath=... or --driver-class-path: These are aliases, doesn't matter which one you choose
  • --conf spark.driver.extraLibraryPath=..., or --driver-library-path ... Same as above, aliases.
  • --conf spark.executor.extraClassPath=...: Use this when you have a dependency which can't be included in an uber JAR (for example, because there are compile time conflicts between library versions) and which you need to load at runtime.
  • --conf spark.executor.extraLibraryPath=... This is passed as the java.library.path option for the JVM. Use this when you need a library path visible to the JVM.

Would it be safe to assume that for simplicity, I can add additional application jar files using the 3 main options at the same time:

You can safely assume this only for Client mode, not Cluster mode. As I've previously said. Also, the example you gave has some redundant arguments. For example, passing JARs to --driver-library-path is useless, you need to pass them to extraClassPath if you want them to be on your classpath. Ultimately, what you want to do when you deploy external JARs on both the driver and the worker is:

spark-submit --jars additional1.jar,additional2.jar \
  --driver-class-path additional1.jar:additional2.jar \
  --conf spark.executor.extraClassPath=additional1.jar:additional2.jar \
  --class MyClass main-application.jar

ArrayList or List declaration in Java

Possibly you can refer to this link http://docs.oracle.com/javase/6/docs/api/java/util/List.html

List is an interface.ArrayList,LinkedList etc are classes which implement list.Whenyou are using List Interface,you have to itearte elements using ListIterator and can move forward and backward,in the List where as in ArrayList Iterate using Iterator and its elements can be accessed unidirectional way.

Apache and Node.js on the Same Server

I am assuming that you are making a web app because you refer to Apache and Node. Quick answer - Is it possible - YES. Is it recommended - NO. Node bundles it's own webserver and most websites run on port 80. I am also assuming that there is currently no Apache plugin which is supported by Nodejs and I am not sure if creating a virtual host is the best way to implement this. These are the questions that should be answered by developers who maintain Nodejs like the good folks at Joyent.

Instead of ports, it would be better to evaluate Node's tech stack which is completely different from most others and which is why I love it but it also involves a few compromises that you should be aware of in advance.

Your example looks similar to a CMS or a sharing web app and there are hundreds of out of the box apps available that will run just fine on Apache. Even if you do not like any readymade solution, you could write a webapp in PHP / Java / Python or mix n match it with a couple of ready made apps and they are all designed and supported to run behind a single instance of Apache.

It's time to pause and think about what I just said.

Now you are ready to decide on which techstack you are going to use. If your website will never use any out of the thousands of ready made apps that require Apache, then go for Node otherwise you must first eliminate the assumptions that I have stated earlier.

In the end, your choice of techstack is way more important than any individual component.

I completely agree with @Straseus that it is relatively trivial to use node.js file system api for handling uploads and downloads but think more about what you want from your website in the long run and then choose your techstack.

Learning Node's framework is easier than learning other frameworks but it is not a panacea. With a slightly more effort (which may be a worthwhile endeavor in itself), you can learn any other framework too. We all learn from each other and you will be more productive if you are working as a small team than if you are working alone and your backend technical skills will also develop faster. Therefore, do not discount the skills of other members of your team so cheaply.

This post is about a year old and chances are that you have already decided but I hope that my rant will help the next person who is going through a similar decision.

Thanks for reading.

Python : How to parse the Body from a raw email , given that raw email does not have a "Body" tag or anything

If emails is the pandas dataframe and emails.message the column for email text

## Helper functions
def get_text_from_email(msg):
    '''To get the content from email objects'''
    parts = []
    for part in msg.walk():
        if part.get_content_type() == 'text/plain':
            parts.append( part.get_payload() )
    return ''.join(parts)

def split_email_addresses(line):
    '''To separate multiple email addresses'''
    if line:
        addrs = line.split(',')
        addrs = frozenset(map(lambda x: x.strip(), addrs))
    else:
        addrs = None
    return addrs 

import email
# Parse the emails into a list email objects
messages = list(map(email.message_from_string, emails['message']))
emails.drop('message', axis=1, inplace=True)
# Get fields from parsed email objects
keys = messages[0].keys()
for key in keys:
    emails[key] = [doc[key] for doc in messages]
# Parse content from emails
emails['content'] = list(map(get_text_from_email, messages))
# Split multiple email addresses
emails['From'] = emails['From'].map(split_email_addresses)
emails['To'] = emails['To'].map(split_email_addresses)

# Extract the root of 'file' as 'user'
emails['user'] = emails['file'].map(lambda x:x.split('/')[0])
del messages

emails.head()

What is the difference between private and protected members of C++ classes?

private is preferred for member data. Members in C++ classes are private by default.

public is preferred for member functions, though it is a matter of opinion. At least some methods must be accessible. public is accessible to all. It is the most flexible option and least safe. Anybody can use them, and anybody can misuse them.

private is not accessible at all. Nobody can use them outside the class, and nobody can misuse them. Not even in derived classes.

protected is a compromise because it can be used in derived classes. When you derive from a class, you have a good understanding of the base class, and you are careful not to misuse these members.

MFC is a C++ wrapper for Windows API, it prefers public and protected. Classes generated by Visual Studio wizard have an ugly mix of protected, public, and private members. But there is some logic to MFC classes themselves.

Members such as SetWindowText are public because you often need to access these members.

Members such as OnLButtonDown, handle notifications received by the window. They should not be accessed, therefore they are protected. You can still access them in the derived class to override these functions.

Some members have to do threads and message loops, they should not be accessed or override, so they are declared as private

In C++ structures, members are public by default. Structures are usually used for data only, not methods, therefore public declaration is considered safe.

How to write a basic swap function in Java

Java is pass by value. So the swap in the sense you mean is not possible. But you can swap contents of two objects or you do it inline.

Xcode Project vs. Xcode Workspace - Differences

In brief

  • Xcode 3 introduced subproject, which is parent-child relationship, meaning that parent can reference its child target, but no vice versa
  • Xcode 4 introduced workspace, which is sibling relationship, meaning that any project can reference projects in the same workspace

httpd Server not started: (13)Permission denied: make_sock: could not bind to address [::]:88

With my centos 6.7 installation, not only did I have the problem starting httpd with root but also with xauth (getting /usr/bin/xauth: timeout in locking authority file /.Xauthority with underlying permission denied errors)

# setenforce 0

Fixed both issues.

Reset/remove CSS styles for element only

BETTER SOLUTION

Download "copy/paste" stylesheet? to reset css properties to default (UA style):
https://github.com/monmomo04/resetCss.git

Thanks@Milche Patern!
I was really looking for reset/default style properties value. My first try was to copy the computed value from the browser Dev tool of the root(html) element. But as it computed, it would have looked/worked different on every system.
For those who encounter a browser crash when trying to use the asterisk * to reset the style of the children elements, and as I knew it didn't work for you, I have replaced the asterisk "*" with all the HTML tags name instead. The browser didn't crash; I am on Chrome Version 46.0.2490.71 m.
At last, it's good to mention that those properties will reset the style to the default style of topest root element but not to the initial value for each HTML element. ?So to correct this, I have taken the "user-agent" styles of webkit based browser and implemented it under the "reset-this" class.

Useful link:


Download "copy/paste" stylesheet? to reset css properties to default (UA style):
https://github.com/monmomo04/resetCss.git

User-agent style:
Browsers' default CSS for HTML elements
http://trac.webkit.org/browser/trunk/Source/WebCore/css/html.css

Css specifity (pay attention to specifity) :
https://css-tricks.com/specifics-on-css-specificity/

https://github.com/monmomo04/resetCss.git

SQL query, store result of SELECT in local variable

You can create table variables:

DECLARE @result1 TABLE (a INT, b INT, c INT)

INSERT INTO @result1
SELECT a, b, c
FROM table1

SELECT a AS val FROM @result1
UNION
SELECT b AS val FROM @result1
UNION
SELECT c AS val FROM @result1

This should be fine for what you need.

How to query values from xml nodes?

if you have only one xml in your table, you can convert it in 2 steps:

CREATE TABLE Batches( 
   BatchID int,
   RawXml xml 
)

declare @xml xml=(select top 1 RawXml from @Batches)

SELECT  --b.BatchID,
        x.XmlCol.value('(ReportHeader/OrganizationReportReferenceIdentifier)[1]','VARCHAR(100)') AS OrganizationReportReferenceIdentifier,
        x.XmlCol.value('(ReportHeader/OrganizationNumber)[1]','VARCHAR(100)') AS OrganizationNumber
FROM    @xml.nodes('/CasinoDisbursementReportXmlFile/CasinoDisbursementReport') x(XmlCol)

Function to convert column number to letter?

LATEST UPDATE: Please ignore the function below, @SurasinTancharoen managed to alert me that it is broken at n = 53.
For those who are interested, here are other broken values just below n = 200:

Certain values of

Please use @brettdj function for all your needs. It even works for Microsoft Excel latest maximum number of columns limit: 16384 should gives XFD

enter image description here

END OF UPDATE


The function below is provided by Microsoft:

Function ConvertToLetter(iCol As Integer) As String
   Dim iAlpha As Integer
   Dim iRemainder As Integer
   iAlpha = Int(iCol / 27)
   iRemainder = iCol - (iAlpha * 26)
   If iAlpha > 0 Then
      ConvertToLetter = Chr(iAlpha + 64)
   End If
   If iRemainder > 0 Then
      ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64)
   End If
End Function

Source: How to convert Excel column numbers into alphabetical characters

APPLIES TO

  • Microsoft Office Excel 2007
  • Microsoft Excel 2002 Standard Edition
  • Microsoft Excel 2000 Standard Edition
  • Microsoft Excel 97 Standard Edition

How to remove numbers from a string?

This can be done without regex which is more efficient:

var questionText = "1 ding ?"
var index = 0;
var num = "";
do
{
    num += questionText[index];
} while (questionText[++index] >= "0" && questionText[index] <= "9");
questionText = questionText.substring(num.length);

And as a bonus, it also stores the number, which may be useful to some people.

With CSS, how do I make an image span the full width of the page as a background image?

You set the CSS to :

#elementID {
    background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) center no-repeat;
    height: 200px;
}

It centers the image, but does not scale it.

FIDDLE

In newer browsers you can use the background-size property and do:

#elementID {
    height: 200px; 
    width: 100%;
    background: black url(http://www.electrictoolbox.com/images/rangitoto-3072x200.jpg) no-repeat;
    background-size: 100% 100%;
}

FIDDLE

Other than that, a regular image is one way to do it, but then it's not really a background image.

?

Validation error: "No validator could be found for type: java.lang.Integer"

As the question is asked simply use @Min(1) instead of @size on integer fields and it will work.

Sqlite convert string to date

As Sqlite doesn't have a date type you will need to do string comparison to achieve this. For that to work you need to reverse the order - eg from dd/MM/yyyy to yyyyMMdd, using something like

where substr(column,7)||substr(column,4,2)||substr(column,1,2) 
      between '20101101' and '20101130'

Android Material: Status bar color won't change

Status bar coloring is not supported in AppCompat v7:21.0.0.

From the Android developers blog post

On older platforms, AppCompat emulates the color theming where possible. At the moment this is limited to coloring the action bar and some widgets.

This means the AppCompat lib will only color status bars on Lollipop and above.

How to make a function wait until a callback has been called using node.js

Using async and await it is lot more easy.

router.post('/login',async (req, res, next) => {
i = await queries.checkUser(req.body);
console.log('i: '+JSON.stringify(i));
});

//User Available Check
async function checkUser(request) {
try {
    let response = await sql.query('select * from login where email = ?', 
    [request.email]);
    return response[0];

    } catch (err) {
    console.log(err);

  }

}

phpMyAdmin is throwing a #2002 cannot log in to the mysql server phpmyadmin

This can also be caused if you forget (as I did) to move config.inc.php into its proper place after completing the setup script.

After making the config folder and doing chmod o+rw config and going to localhost/phpmyadmin/setup and following those steps, you need to go back to the command line and finish things off:

mv config/config.inc.php .         # move file to current directory
chmod o-rw config.inc.php          # remove world read and write permissions
rm -rf config                      # remove not needed directory

See full instructions at https://phpmyadmin.readthedocs.org/en/latest/setup.html

SQL sum with condition

With condition HAVING you will eliminate data with cash not ultrapass 0 if you want, generating more efficiency in your query.

SELECT SUM(cash) AS money FROM Table t1, Table2 t2 WHERE t1.branch = t2.branch 
AND t1.transID = t2.transID
AND ValueDate > @startMonthDate HAVING money > 0;

Insert new column into table in sqlite?

You have two options. First, you could simply add a new column with the following:

ALTER TABLE {tableName} ADD COLUMN COLNew {type};

Second, and more complicatedly, but would actually put the column where you want it, would be to rename the table:

ALTER TABLE {tableName} RENAME TO TempOldTable;

Then create the new table with the missing column:

CREATE TABLE {tableName} (name TEXT, COLNew {type} DEFAULT {defaultValue}, qty INTEGER, rate REAL);

And populate it with the old data:

INSERT INTO {tableName} (name, qty, rate) SELECT name, qty, rate FROM TempOldTable;

Then delete the old table:

DROP TABLE TempOldTable;

I'd much prefer the second option, as it will allow you to completely rename everything if need be.

Control the size of points in an R scatterplot?

As rcs stated, cex will do the job in base graphics package. I reckon that you're not willing to do your graph in ggplot2 but if you do, there's a size aesthetic attribute, that you can easily control (ggplot2 has user-friendly function arguments: instead of typing cex (character expansion), in ggplot2 you can type e.g. size = 2 and you'll get 2mm point).

Here's the example:

### base graphics ###
plot(mpg ~ hp, data = mtcars, pch = 16, cex = .9)

### ggplot2 ###
# with qplot()
qplot(mpg, hp, data = mtcars, size = I(2))
# or with ggplot() + geom_point()
ggplot(mtcars, aes(mpg, hp), size = 2) + geom_point()
# or another solution:
ggplot(mtcars, aes(mpg, hp)) + geom_point(size = 2)

Best way to find the intersection of multiple sets?

From Python version 2.6 on you can use multiple arguments to set.intersection(), like

u = set.intersection(s1, s2, s3)

If the sets are in a list, this translates to:

u = set.intersection(*setlist)

where *a_list is list expansion

Note that set.intersection is not a static method, but this uses the functional notation to apply intersection of the first set with the rest of the list. So if the argument list is empty this will fail.

How to download videos from youtube on java?

Regarding the format (mp4 or flv) decide which URL you want to use. Then use this tutorial to download the video and save it into a local directory.

Kotlin Ternary Conditional Operator

You could define your own Boolean extension function that returns null when the Boolean is false to provide a structure similar to the ternary operator:

infix fun <T> Boolean.then(param: T): T? = if (this) param else null

This would make an a ? b : c expression translate to a then b ?: c, like so:

println(condition then "yes" ?: "no")

Update: But to do some more Java-like conditional switch you will need something like that

infix fun <T> Boolean.then(param: () -> T): T? = if (this) param() else null

println(condition then { "yes" } ?: "no") pay attention on the lambda. its content calculation should be postponed until we make sure condition is true

This one looks clumsy, that is why there is high demanded request exist to port Java ternary operator into Kotlin

git-upload-pack: command not found, when cloning remote Git repo

Make sure git-upload-pack is on the path from a non-login shell. (On my machine it's in /usr/bin).

To see what your path looks like on the remote machine from a non-login shell, try this:

ssh you@remotemachine echo \$PATH

(That works in Bash, Zsh, and tcsh, and probably other shells too.)

If the path it gives back doesn't include the directory that has git-upload-pack, you need to fix it by setting it in .bashrc (for Bash), .zshenv (for Zsh), .cshrc (for tcsh) or equivalent for your shell.

You will need to make this change on the remote machine.

If you're not sure which path you need to add to your remote PATH, you can find it with this command (you need to run this on the remote machine):

which git-upload-pack

On my machine that prints /usr/bin/git-upload-pack. So in this case, /usr/bin is the path you need to make sure is in your remote non-login shell PATH.

Cannot ignore .idea/workspace.xml - keeps popping up

In the same dir where you see the file appear do:

  • rm .idea/workspace.xml
  • git rm -f .idea/workspace.xml (as suggested by chris vdp)
  • vi .gitignore
  • i (to edit), add .idea/workspace.xml in one of the lines, Esc, :wq

You should be good now

Check which element has been clicked with jQuery

Hope this useful for you.

$(document).click(function(e){
    if ($('#news_gallery').on('clicked')) {
        var article = $('#news-article .news-article');
    }  
});

Given an RGB value, how do I create a tint (or shade)?

I'm currently experimenting with canvas and pixels... I'm finding this logic works out for me better.

  1. Use this to calculate the grey-ness ( luma ? )
  2. but with both the existing value and the new 'tint' value
  3. calculate the difference ( I found I did not need to multiply )
  4. add to offset the 'tint' value

    var grey =  (r + g + b) / 3;    
    var grey2 = (new_r + new_g + new_b) / 3;
    
    var dr =  grey - grey2 * 1;    
    var dg =  grey - grey2 * 1    
    var db =  grey - grey2 * 1;  
    
    tint_r = new_r + dr;    
    tint_g = new_g + dg;   
    tint_b = new_b _ db;
    

or something like that...

PHP prepend leading zero before single digit number, on-the-fly

You can use str_pad for adding 0's

str_pad($month, 2, '0', STR_PAD_LEFT); 

string str_pad ( string $input , int $pad_length [, string $pad_string = " " [, int $pad_type = STR_PAD_RIGHT ]] )

How to check Django version

If you want to make Django version comparison, you could use django-nine (pip install django-nine). For example, if Django version installed in your environment is 1.7.4, then the following would be true.

from nine import versions

versions.DJANGO_1_7 # True
versions.DJANGO_LTE_1_7 # True
versions.DJANGO_GTE_1_7 # True
versions.DJANGO_GTE_1_8 # False
versions.DJANGO_GTE_1_4 # True
versions.DJANGO_LTE_1_6 # False

JavaScript: What are .extend and .prototype used for?

Javascript's inheritance is prototype based, so you extend the prototypes of objects such as Date, Math, and even your own custom ones.

Date.prototype.lol = function() {
 alert('hi');
};

( new Date ).lol() // alert message

In the snippet above, I define a method for all Date objects ( already existing ones and all new ones ).

extend is usually a high level function that copies the prototype of a new subclass that you want to extend from the base class.

So you can do something like:

extend( Fighter, Human )

And the Fighter constructor/object will inherit the prototype of Human, so if you define methods such as live and die on Human then Fighter will also inherit those.

Updated Clarification:

"high level function" meaning .extend isn't built-in but often provided by a library such as jQuery or Prototype.

Creation timestamp and last update timestamp with Hibernate and MySQL

  1. What database column types you should use

Your first question was:

What data types would you use in the database (assuming MySQL, possibly in a different timezone that the JVM)? Will the data types be timezone-aware?

In MySQL, the TIMESTAMP column type does a shifting from the JDBC driver local time zone to the database timezone, but it can only store timestamps up to 2038-01-19 03:14:07.999999, so it's not the best choice for the future.

So, better to use DATETIME instead, which doesn't have this upper boundary limitation. However, DATETIME is not timezone aware. So, for this reason, it's best to use UTC on the database side and use the hibernate.jdbc.time_zone Hibernate property.

  1. What entity property type you should use

Your second question was:

What data types would you use in Java (Date, Calendar, long, ...)?

On the Java side, you can use the Java 8 LocalDateTime. You can also use the legacy Date, but the Java 8 Date/Time types are better since they are immutable, and don't do a timezone shifting to local timezone when logging them.

Now, we can also answer this question:

What annotations would you use for the mapping (e.g. @Temporal)?

If you are using the LocalDateTime or java.sql.Timestamp to map a timestamp entity property, then you don't need to use @Temporal since HIbernate already knows that this property is to be saved as a JDBC Timestamp.

Only if you are using java.util.Date, you need to specify the @Temporal annotation, like this:

@Temporal(TemporalType.TIMESTAMP)
@Column(name = "created_on")
private Date createdOn;

But, it's much better if you map it like this:

@Column(name = "created_on")
private LocalDateTime createdOn;

How to generate the audit column values

Your third question was:

Whom would you make responsible for setting the timestamps—the database, the ORM framework (Hibernate), or the application programmer?

What annotations would you use for the mapping (e.g. @Temporal)?

There are many ways you can achieve this goal. You can allow the database to do that..

For the create_on column, you could use a DEFAULT DDL constraint, like :

ALTER TABLE post 
ADD CONSTRAINT created_on_default 
DEFAULT CURRENT_TIMESTAMP() FOR created_on;

For the updated_on column, you could use a DB trigger to set the column value with CURRENT_TIMESTAMP() every time a given row is modified.

Or, use JPA or Hibernate to set those.

Let's assume you have the following database tables:

Database tables with audit columns

And, each table has columns like:

  • created_by
  • created_on
  • updated_by
  • updated_on

Using Hibernate @CreationTimestamp and @UpdateTimestamp annotations

Hibernate offers the @CreationTimestamp and @UpdateTimestamp annotations that can be used to map the created_on and updated_on columns.

You can use @MappedSuperclass to define a base class that will be extended by all entities:

@MappedSuperclass
public class BaseEntity {
 
    @Id
    @GeneratedValue
    private Long id;
 
    @Column(name = "created_on")
    @CreationTimestamp
    private LocalDateTime createdOn;
 
    @Column(name = "created_by")
    private String createdBy;
 
    @Column(name = "updated_on")
    @UpdateTimestamp
    private LocalDateTime updatedOn;
 
    @Column(name = "updated_by")
    private String updatedBy;
 
    //Getters and setters omitted for brevity
}

And, all entities will extend the BaseEntity, like this:

@Entity(name = "Post")
@Table(name = "post")
public class Post extend BaseEntity {
 
    private String title;
 
    @OneToMany(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();
 
    @OneToOne(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true,
        fetch = FetchType.LAZY
    )
    private PostDetails details;
 
    @ManyToMany
    @JoinTable(
        name = "post_tag",
        joinColumns = @JoinColumn(
            name = "post_id"
        ),
        inverseJoinColumns = @JoinColumn(
            name = "tag_id"
        )
    )
    private List<Tag> tags = new ArrayList<>();
 
    //Getters and setters omitted for brevity
}

However, even if the createdOn and updateOn properties are set by the Hibernate-specific @CreationTimestamp and @UpdateTimestamp annotations, the createdBy and updatedBy require registering an application callback, as illustrated by the following JPA solution.

Using JPA @EntityListeners

You can encapsulate the audit properties in an Embeddable:

@Embeddable
public class Audit {
 
    @Column(name = "created_on")
    private LocalDateTime createdOn;
 
    @Column(name = "created_by")
    private String createdBy;
 
    @Column(name = "updated_on")
    private LocalDateTime updatedOn;
 
    @Column(name = "updated_by")
    private String updatedBy;
 
    //Getters and setters omitted for brevity
}

And, create an AuditListener to set the audit properties:

public class AuditListener {
 
    @PrePersist
    public void setCreatedOn(Auditable auditable) {
        Audit audit = auditable.getAudit();
 
        if(audit == null) {
            audit = new Audit();
            auditable.setAudit(audit);
        }
 
        audit.setCreatedOn(LocalDateTime.now());
        audit.setCreatedBy(LoggedUser.get());
    }
 
    @PreUpdate
    public void setUpdatedOn(Auditable auditable) {
        Audit audit = auditable.getAudit();
 
        audit.setUpdatedOn(LocalDateTime.now());
        audit.setUpdatedBy(LoggedUser.get());
    }
}

To register the AuditListener, you can use the @EntityListeners JPA annotation:

@Entity(name = "Post")
@Table(name = "post")
@EntityListeners(AuditListener.class)
public class Post implements Auditable {
 
    @Id
    private Long id;
 
    @Embedded
    private Audit audit;
 
    private String title;
 
    @OneToMany(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();
 
    @OneToOne(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true,
        fetch = FetchType.LAZY
    )
    private PostDetails details;
 
    @ManyToMany
    @JoinTable(
        name = "post_tag",
        joinColumns = @JoinColumn(
            name = "post_id"
        ),
        inverseJoinColumns = @JoinColumn(
            name = "tag_id"
        )
    )
    private List<Tag> tags = new ArrayList<>();
 
    //Getters and setters omitted for brevity
}

SSRS Expression for IF, THEN ELSE

You should be able to use

IIF(Fields!ExitReason.Value = 7, 1, 0)

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

Convert unix time stamp to date in java

Java 8 introduces the Instant.ofEpochSecond utility method for creating an Instant from a Unix timestamp, this can then be converted into a ZonedDateTime and finally formatted, e.g.:

final DateTimeFormatter formatter = 
    DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

final long unixTime = 1372339860;
final String formattedDtm = Instant.ofEpochSecond(unixTime)
        .atZone(ZoneId.of("GMT-4"))
        .format(formatter);

System.out.println(formattedDtm);   // => '2013-06-27 09:31:00'

I thought this might be useful for people who are using Java 8.

Expression must have class type

It's a pointer, so instead try:

a->f();

Basically the operator . (used to access an object's fields and methods) is used on objects and references, so:

A a;
a.f();
A& ref = a;
ref.f();

If you have a pointer type, you have to dereference it first to obtain a reference:

A* ptr = new A();
(*ptr).f();
ptr->f();

The a->b notation is usually just a shorthand for (*a).b.

A note on smart pointers

The operator-> can be overloaded, which is notably used by smart pointers. When you're using smart pointers, then you also use -> to refer to the pointed object:

auto ptr = make_unique<A>();
ptr->f();

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

when reimporting your keys from the old keyring, you need to specify the command:

gpg --allow-secret-key-import --import <keyring>

otherwise it will only import the public keys, not the private keys.

Android: remove notification from notification bar

simply set setAutoCancel(True) like the following code:

Intent resultIntent = new Intent(GameLevelsActivity.this, NotificationReceiverActivityAdv.class);

PendingIntent resultPendingIntent =
        PendingIntent.getActivity(
                GameLevelsActivity.this,
                0,
                resultIntent,
                PendingIntent.FLAG_UPDATE_CURRENT
                );

NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
        getApplicationContext()).setSmallIcon(R.drawable.icon)
        .setContentTitle(adv_title)
        .setContentText(adv_desc)
        .setContentIntent(resultPendingIntent)
         //HERE IS WHAT YOY NEED:
        .setAutoCancel(true);

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(547, mBuilder.build());`

Which exception should I raise on bad/illegal argument combinations in Python?

I think the best way to handle this is the way python itself handles it. Python raises a TypeError. For example:

$ python -c 'print(sum())'
Traceback (most recent call last):
File "<string>", line 1, in <module>
TypeError: sum expected at least 1 arguments, got 0

Our junior dev just found this page in a google search for "python exception wrong arguments" and I'm surprised that the obvious (to me) answer wasn't ever suggested in the decade since this question was asked.

Replace non ASCII character from string

FailedDev's answer is good, but can be improved. If you want to preserve the ascii equivalents, you need to normalize first:

String subjectString = "öäü";
subjectString = Normalizer.normalize(subjectString, Normalizer.Form.NFD);
String resultString = subjectString.replaceAll("[^\\x00-\\x7F]", "");

=> will produce "oau"

That way, characters like "öäü" will be mapped to "oau", which at least preserves some information. Without normalization, the resulting String will be blank.

Make a div into a link

Just have the link in the block and enhance it with jquery. It degrades 100% gracefully for anyone without javascript. Doing this with html isn't really the best solution imho. For example:

<div id="div_link">
<h2><a href="mylink.htm">The Link and Headline</a></h2>
<p>Some more stuff and maybe another <a href="mylink.htm">link</a>.</p>
</div>

Then use jquery to make the block clickable (via web designer wall):

$(document).ready(function(){

    $("#div_link").click(function(){
      window.location=$(this).find("a").attr("href"); return false;
    });

});

Then all you have to do is add cursor styles to the div

    #div_link:hover {cursor: pointer;}

For bonus points only apply these styles if javascript is enabled by adding a 'js_enabled' class to the div, or the body, or whatever.

Entity Framework vs LINQ to SQL

Neither yet supports the unique SQL 2008 datatypes. The difference from my perspective is that Entity still has a chance to construct a model around my geographic datatype in some future release, and Linq to SQL, being abandoned, never will.

Wonder what's up with nHibernate, or OpenAccess...

How to git-svn clone the last n revisions from a Subversion repository?

I find myself using the following often to get a limited number of revisions out of our huge subversion tree (we're soon reaching svn revision 35000).

# checkout a specific revision
git svn clone -r N svn://some/repo/branch/some-branch
# enter it and get all commits since revision 'N'
cd some-branch
git svn rebase

And a good way to find out where a branch started is to do a svn log it and find the first one on the branch (the last one listed when doing):

svn log --stop-on-copy svn://some/repo/branch/some-branch

So far I have not really found the hassle worth it in tracking all branches. It takes too much time to clone and svn and git don't work together as good as I would like. I tend to create patch files and apply them on the git clone of another svn branch.

What Scala web-frameworks are available?

There's also Pinky, which used to be on bitbucket but got transfered to github.

By the way, github is a great place to search for Scala projects, as there's a lot being put there.

Find all CSV files in a directory using Python

I had to get csv files that were in subdirectories, therefore, using the response from tchlpr I modified it to work best for my use case:

import os
import glob

os.chdir( '/path/to/main/dir' )
result = glob.glob( '*/**.csv' )
print( result )

check if file exists on remote host with ssh

Can't get much simpler than this :)

ssh host "test -e /path/to/file"
if [ $? -eq 0 ]; then
    # your file exists
fi

As suggested by dimo414, this can be collapsed to:

if ssh host "test -e /path/to/file"; then
    # your file exists
fi

How do I print output in new line in PL/SQL?

dbms_output.put_line('Hi,');
dbms_output.put_line('good');
dbms_output.put_line('morning');
dbms_output.put_line('friends');

or

DBMS_OUTPUT.PUT_LINE('Hi, ' || CHR(13) || CHR(10) || 
                     'good' || CHR(13) || CHR(10) ||
                     'morning' || CHR(13) || CHR(10) ||
                     'friends' || CHR(13) || CHR(10) ||);

try it.

How do I clear inner HTML

const destroy = container => {
  document.getElementById(container).innerHTML = '';
};

Faster previous

const destroyFast = container => {
  const el = document.getElementById(container);
  while (el.firstChild) el.removeChild(el.firstChild);
};

Sort a Custom Class List<T>

First things first, if the date property is storing a date, store it using a DateTime. If you parse the date through the sort you have to parse it for each item being compared, that's not very efficient...

You can then make an IComparer:

public class TagComparer : IComparer<cTag>
{
    public int Compare(cTag first, cTag second)
    {
        if (first != null && second != null)
        {
            // We can compare both properties.
            return first.date.CompareTo(second.date);
        }

        if (first == null && second == null)
        {
            // We can't compare any properties, so they are essentially equal.
            return 0;
        }

        if (first != null)
        {
            // Only the first instance is not null, so prefer that.
            return -1;
        }

        // Only the second instance is not null, so prefer that.
        return 1;
    }
}

var list = new List<cTag>();
// populate list.

list.Sort(new TagComparer());

You can even do it as a delegate:

list.Sort((first, second) =>
          {
              if (first != null && second != null)
                  return first.date.CompareTo(second.date);

              if (first == null && second == null)
                  return 0;

              if (first != null)
                  return -1;

              return 1;
          });

Split string based on regex

You could use a lookahead:

re.split(r'[ ](?=[A-Z]+\b)', input)

This will split at every space that is followed by a string of upper-case letters which end in a word-boundary.

Note that the square brackets are only for readability and could as well be omitted.

If it is enough that the first letter of a word is upper case (so if you would want to split in front of Hello as well) it gets even easier:

re.split(r'[ ](?=[A-Z])', input)

Now this splits at every space followed by any upper-case letter.

How to configure Spring Security to allow Swagger URL to be accessed without authentication

Here's a complete solution for Swagger with Spring Security. We probably want to only enable Swagger in our development and QA environment and disable it in the production environment. So, I am using a property (prop.swagger.enabled) as a flag to bypass spring security authentication for swagger-ui only in development/qa environment.

@Configuration
@EnableSwagger2
public class SwaggerConfiguration extends WebSecurityConfigurerAdapter implements WebMvcConfigurer {

@Value("${prop.swagger.enabled:false}")
private boolean enableSwagger;

@Bean
public Docket SwaggerConfig() {
    return new Docket(DocumentationType.SWAGGER_2)
            .enable(enableSwagger)
            .select()
            .apis(RequestHandlerSelectors.basePackage("com.your.controller"))
            .paths(PathSelectors.any())
            .build();
}

@Override
public void configure(WebSecurity web) throws Exception {
    if (enableSwagger)  
        web.ignoring().antMatchers("/v2/api-docs",
                               "/configuration/ui",
                               "/swagger-resources/**",
                               "/configuration/security",
                               "/swagger-ui.html",
                               "/webjars/**");
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    if (enableSwagger) {
        registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
        registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
    }
  }
}

Cannot find name 'require' after upgrading to Angular4

The problem (as outlined in typescript getting error TS2304: cannot find name ' require') is that the type definitions for node are not installed.

With a projected genned with @angular/cli 1.x, the specific steps should be:

Step 1:

Install @types/node with either of the following:

- npm install --save @types/node
- yarn add @types/node -D

Step 2: Edit your src/tsconfig.app.json file and add the following in place of the empty "types": [], which should already be there:

...
"types": [ "node" ],
"typeRoots": [ "../node_modules/@types" ]
...

If I've missed anything, jot a comment and I'll edit my answer.

Java : How to determine the correct charset encoding of a stream

For ISO8859_1 files, there is not an easy way to distinguish them from ASCII. For Unicode files however one can generally detect this based on the first few bytes of the file.

UTF-8 and UTF-16 files include a Byte Order Mark (BOM) at the very beginning of the file. The BOM is a zero-width non-breaking space.

Unfortunately, for historical reasons, Java does not detect this automatically. Programs like Notepad will check the BOM and use the appropriate encoding. Using unix or Cygwin, you can check the BOM with the file command. For example:

$ file sample2.sql 
sample2.sql: Unicode text, UTF-16, big-endian

For Java, I suggest you check out this code, which will detect the common file formats and select the correct encoding: How to read a file and automatically specify the correct encoding

How to write macro for Notepad++?

Macros in Notepad++ are just a bunch of encoded operations: you start recording, operate on the buffer, perhaps activating menus, stop recording then play the macro.
After investigation, I found out they are saved in the file shortcuts.xml in the Macros section. For example, I have there:

<Macro name="Trim Trailing and save" Ctrl="no" Alt="yes" Shift="yes" Key="83">
    <Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
    <Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
    <Action type="1" message="2170" wParam="0" lParam="0" sParam=" " />
    <Action type="0" message="2327" wParam="0" lParam="0" sParam="" />
    <Action type="0" message="2327" wParam="0" lParam="0" sParam="" />
    <Action type="2" message="0" wParam="42024" lParam="0" sParam="" />
    <Action type="2" message="0" wParam="41006" lParam="0" sParam="" />
</Macro>

I haven't looked at the source, but from the look, I would say we have messages sent to Scintilla (the editing component, perhaps type 0 and 1), and to Notepad++ itself (probably activating menu items).
I don't think it will record actions in dialogs (like search/replace).

Looking at Scintilla.iface file, we can see that 2170 is the code of ReplaceSel (ie. insert string is nothing is selected), 2327 is Tab command, and Resource Hacker (just have it handy...) shows that 42024 is "Trim Trailing Space" menu item and 41006 is "Save".
I guess action type 0 is for Scintilla commands with numerical params, type 1 is for commands with string parameter, 2 is for Notepad++ commands.

Problem: Scintilla doesn't have a "Replace all" command: it is the task of the client to do the iteration, with or without confirmation, etc.
Another problem: it seems type 1 action is limited to 1 char (I edited manually, when exiting N++ it was truncated).
I tried some tricks, but I fear such task is beyond the macro capabilities.

Maybe that's where SciTE with its Lua scripting ability (or Programmer's Notepad which seems to be scriptable with Python) has an edge... :-)

[EDIT] Looks like I got the above macro from this thread or a similar place... :-) I guess the first lines are unnecessary (side effect or recording) but they were good examples of macro code anyway.

python 3.2 UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 9629: character maps to <undefined>

While Python 3 deals in Unicode, the Windows console or POSIX tty that you're running inside does not. So, whenever you print, or otherwise send Unicode strings to stdout, and it's attached to a console/tty, Python has to encode it.

The error message indirectly tells you what character set Python was trying to use:

  File "C:\Python32\lib\encodings\cp850.py", line 19, in encode

This means the charset is cp850.

You can test or yourself that this charset doesn't have the appropriate character just by doing '\u2013'.encode('cp850'). Or you can look up cp850 online (e.g., at Wikipedia).

It's possible that Python is guessing wrong, and your console is really set for, say UTF-8. (In that case, just manually set sys.stdout.encoding='utf-8'.) It's also possible that you intended your console to be set for UTF-8 but did something wrong. (In that case, you probably want to follow up at superuser.com.)

But if nothing is wrong, you just can't print that character. You will have to manually encode it with one of the non-strict error-handlers. For example:

>>> '\u2013'.encode('cp850')
UnicodeEncodeError: 'charmap' codec can't encode character '\u2013' in position 0: character maps to <undefined>
>>> '\u2013'.encode('cp850', errors='replace')
b'?'

So, how do you print a string that won't print on your console?

You can replace every print function with something like this:

>>> print(r['body'].encode('cp850', errors='replace').decode('cp850'))
?

… but that's going to get pretty tedious pretty fast.

The simple thing to do is to just set the error handler on sys.stdout:

>>> sys.stdout.errors = 'replace'
>>> print(r['body'])
?

For printing to a file, things are pretty much the same, except that you don't have to set f.errors after the fact, you can set it at construction time. Instead of this:

with open('path', 'w', encoding='cp850') as f:

Do this:

with open('path', 'w', encoding='cp850', errors='replace') as f:

… Or, of course, if you can use UTF-8 files, just do that, as Mark Ransom's answer shows:

with open('path', 'w', encoding='utf-8') as f:

grant remote access of MySQL database from any IP address

To remotely access database Mysql server 8:

CREATE USER 'root'@'%' IDENTIFIED BY 'Pswword@123';

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' WITH GRANT OPTION;

FLUSH PRIVILEGES;

MySQL limit from descending order

yes, you can swap these 2 queries

select * from table limit 5, 5

select * from table limit 0, 5

Getting the class of the element that fired an event using JQuery

Try:

$(document).ready(function() {
    $("a").click(function(event) {
       alert(event.target.id+" and "+$(event.target).attr('class'));
    });
});

Can not find the tag library descriptor of springframework

Removing the space between @ and taglib did the trick for me: <%@ taglib prefix="spring" uri="http://www.springframework.org/tags" %>

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

Following worked for me.

  1. Open another instance of Application Loader. ( Select "Application Loader" under the "Xcode -> Open Developer Tool" menu)

  2. "Agree" to the terms.

  3. After completing Step 2. First instance of Application Loader proceeded to the next step and build got submitted.

jQuery not working with IE 11

As Arnaud suggested in a comment to the original post, you should put this in your html header:

<meta http-equiv="X-UA-Compatible" content="IE=edge">

I don't want any cred for this. I just want to make it more visible for anyone else that come here.

Android LinearLayout Gradient Background

I would check your alpha channel on your gradient colors. For me, when I was testing my code out I had the alpha channel set wrong on the colors and it did not work for me. Once I got the alpha channel set it all worked!

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

I think you can simplify this by just adding the necessary CSS properties to your special scrollable menu class..

CSS:

.scrollable-menu {
    height: auto;
    max-height: 200px;
    overflow-x: hidden;
}

HTML

       <ul class="dropdown-menu scrollable-menu" role="menu">
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
          <li><a href="#">Something else here</a></li>
          <li><a href="#">Action</a></li>
            ..
          <li><a href="#">Action</a></li>
          <li><a href="#">Another action</a></li>
       </ul>

Working example: https://www.bootply.com/86116

Bootstrap 4

Another example for Bootstrap 4 using flexbox

How to get duration, as int milli's and float seconds from <chrono>?

In AAA style using the explicitly typed initializer idiom:

#include <chrono>
#include <iostream>

int main(){
  auto start = std::chrono::high_resolution_clock::now();
  // Code to time here...
  auto end = std::chrono::high_resolution_clock::now();

  auto dur = end - start;
  auto i_millis = std::chrono::duration_cast<std::chrono::milliseconds>(dur);
  auto f_secs = std::chrono::duration_cast<std::chrono::duration<float>>(dur);
  std::cout << i_millis.count() << '\n';
  std::cout << f_secs.count() << '\n';
}

How to toggle a boolean?

bool = !bool;

This holds true in most languages.

How to convert string representation of list to a list?

>>> import ast
>>> x = '[ "A","B","C" , " D"]'
>>> x = ast.literal_eval(x)
>>> x
['A', 'B', 'C', ' D']
>>> x = [n.strip() for n in x]
>>> x
['A', 'B', 'C', 'D']

ast.literal_eval:

With ast.literal_eval you can safely evaluate an expression node or a string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, bytes, numbers, tuples, lists, dicts, booleans, and None.

ASP.NET Core Web API exception handling

If you want set custom exception handling behavior for a specific controller, you can do so by overriding the controllers OnActionExecuted method.

Remember to set the ExceptionHandled property to true to disable default exception handling behavior.

Here is a sample from an api I'm writing, where I want to catch specific types of exceptions and return a json formatted result:

    private static readonly Type[] API_CATCH_EXCEPTIONS = new Type[]
    {
        typeof(InvalidOperationException),
        typeof(ValidationException)           
    };

    public override void OnActionExecuted(ActionExecutedContext context)
    {
        base.OnActionExecuted(context);

        if (context.Exception != null)
        {
            var exType = context.Exception.GetType();
            if (API_CATCH_EXCEPTIONS.Any(type => exType == type || exType.IsSubclassOf(type)))
            {
                context.Result = Problem(detail: context.Exception.Message);
                context.ExceptionHandled = true;
            }
        }  
    }

How Can I Remove “public/index.php” in the URL Generated Laravel?

Laravel ships with a pretty URL .htaccess already... you should be good to go out of the box... http://laravel.com/docs/installation#pretty-urls

Make sure mod_rewrite is enabled and that your home path is set to the public directory of your application.

PHP session handling errors

Go to your PHP.ini file or find PHP.ini EZConfig on your Cpanel and set your session.save_path to the full path leading to the tmp file, i.e: /home/cpanelusername/tmp

Read file-contents into a string in C++

The most efficient is to create a buffer of the correct size and then read the file into the buffer.

#include <fstream>
#include <vector>

int main()
{
    std::ifstream       file("Plop");
    if (file)
    {
        /*
         * Get the size of the file
         */
        file.seekg(0,std::ios::end);
        std::streampos          length = file.tellg();
        file.seekg(0,std::ios::beg);

        /*
         * Use a vector as the buffer.
         * It is exception safe and will be tidied up correctly.
         * This constructor creates a buffer of the correct length.
         * Because char is a POD data type it is not initialized.
         *
         * Then read the whole file into the buffer.
         */
        std::vector<char>       buffer(length);
        file.read(&buffer[0],length);
    }
}

ActiveMQ connection refused

I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:

Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused

& I resolved it following way.

   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();

  connectionFactory.setBrokerURL("tcp://hostname:61616");
  connectionFactory.setUserName("admin");
  connectionFactory.setPassword("admin");

Issue with background color in JavaFX 8

Both these work for me. Maybe post a complete example?

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.Background;
import javafx.scene.layout.BackgroundFill;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.CornerRadii;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;

public class PaneBackgroundTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        BorderPane root = new BorderPane();
        VBox vbox = new VBox();
        root.setCenter(vbox);

        ToggleButton toggle = new ToggleButton("Toggle color");
        HBox controls = new HBox(5, toggle);
        controls.setAlignment(Pos.CENTER);
        root.setBottom(controls);

//        vbox.styleProperty().bind(Bindings.when(toggle.selectedProperty())
//                .then("-fx-background-color: cornflowerblue;")
//                .otherwise("-fx-background-color: white;"));

        vbox.backgroundProperty().bind(Bindings.when(toggle.selectedProperty())
                .then(new Background(new BackgroundFill(Color.CORNFLOWERBLUE, CornerRadii.EMPTY, Insets.EMPTY)))
                .otherwise(new Background(new BackgroundFill(Color.WHITE, CornerRadii.EMPTY, Insets.EMPTY))));

        Scene scene = new Scene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }

}

How can I reconcile detached HEAD with master/origin?

I had this problem today, where I had updated a submodule, but wasn't on any branch. I had already committed, so stashing, checkout, unstashing wouldn't work. I ended up cherry-picking the detached head's commit. So immediately after I committed (when the push failed), I did:

git checkout master
git cherry-pick 99fe23ab

My thinking went: I'm on a detached head, but I want to be on master. Assuming my detached state is not very different from master, if I could apply my commit to master, I'd be set. This is exactly what cherry-pick does.

Explode string by one or more spaces or tabs

$parts = preg_split('/\s+/', $str);

Remove rows with all or some NAs (missing values) in data.frame

My guess is that this could be more elegantly solved in this way:

  m <- matrix(1:25, ncol = 5)
  m[c(1, 6, 13, 25)] <- NA
  df <- data.frame(m)
  library(dplyr) 
  df %>%
  filter_all(any_vars(is.na(.)))
  #>   X1 X2 X3 X4 X5
  #> 1 NA NA 11 16 21
  #> 2  3  8 NA 18 23
  #> 3  5 10 15 20 NA

In C++ check if std::vector<string> contains a certain value

  1. If your container only contains unique values, consider using std::set instead. It allows querying of set membership with logarithmic complexity.

     std::set<std::string> s;
     s.insert("abc");
     s.insert("xyz");
     if (s.find("abc") != s.end()) { ...
    
  2. If your vector is kept sorted, use std::binary_search, it offers logarithmic complexity as well.

  3. If all else fails, fall back to std::find, which is a simple linear search.

How to create a custom scrollbar on a div (Facebook style)

If you're looking for a Facebook like scroll bar, then I'd highly recommend you take a look at this one:

http://rocha.la/jQuery-slimScroll

How to simulate a click with JavaScript?

You could save yourself a bunch of space by using jQuery. You only need to use:

$('#myElement').trigger("click")

How might I find the largest number contained in a JavaScript array?

Should be quite simple:

var countArray = [1,2,3,4,5,1,3,51,35,1,357,2,34,1,3,5,6];

var highestCount = 0;
for(var i=0; i<=countArray.length; i++){    
    if(countArray[i]>=highestCount){
    highestCount = countArray[i]
  }
}

console.log("Highest Count is " + highestCount);

gdb: how to print the current line or find the current line number?

All the answers above are correct, What I prefer is to use tui mode (ctrl+X A or 'tui enable') which shows your location and the function in a separate window which is very helpful for the users. Hope that helps too.

How do I request and process JSON with python?

For anything with requests to URLs you might want to check out requests. For JSON in particular:

>>> import requests
>>> r = requests.get('https://github.com/timeline.json')
>>> r.json()
[{u'repository': {u'open_issues': 0, u'url': 'https://github.com/...

Attribute Error: 'list' object has no attribute 'split'

The problem is that readlines is a list of strings, each of which is a line of filename. Perhaps you meant:

for line in readlines:
    Type = line.split(",")
    x = Type[1]
    y = Type[2]
    print(x,y)

jquery 3.0 url.indexOf error

Update all your code that calls load function like,

$(window).load(function() { ... });

To

$(window).on('load', function() { ... });

jquery.js:9612 Uncaught TypeError: url.indexOf is not a function

This error message comes from jQuery.fn.load function.

I've come across the same issue on my application. After some digging, I found this statement in jQuery blog,

.load, .unload, and .error, deprecated since jQuery 1.8, are no more. Use .on() to register listeners.

I simply just change how my jQuery objects call the load function like above. And everything works as expected.

Hash table runtime complexity (insert, search and delete)

Perhaps you were looking at the space complexity? That is O(n). The other complexities are as expected on the hash table entry. The search complexity approaches O(1) as the number of buckets increases. If at the worst case you have only one bucket in the hash table, then the search complexity is O(n).

Edit in response to comment I don't think it is correct to say O(1) is the average case. It really is (as the wikipedia page says) O(1+n/k) where K is the hash table size. If K is large enough, then the result is effectively O(1). But suppose K is 10 and N is 100. In that case each bucket will have on average 10 entries, so the search time is definitely not O(1); it is a linear search through up to 10 entries.

Text file with 0D 0D 0A line breaks

This typically stems from a bug in revision control system, or similar. This was a product from CVS, if a file was checked in from Windows to Unix server, and then checked out again...

In other words, it is just broken...

How do I upload a file to an SFTP server in C# (.NET)?

Following code shows how to upload a file to a SFTP server using our Rebex SFTP component.

// create client, connect and log in 
Sftp client = new Sftp();
client.Connect(hostname);
client.Login(username, password);

// upload the 'test.zip' file to the current directory at the server 
client.PutFile(@"c:\data\test.zip", "test.zip");

client.Disconnect();

You can write a complete communication log to a file using a LogWriter property as follows. Examples output (from FTP component but the SFTP output is similar) can be found here.

client.LogWriter = new Rebex.FileLogWriter(
   @"c:\temp\log.txt", Rebex.LogLevel.Debug); 

or intercept the communication using events as follows:

Sftp client = new Sftp();
client.CommandSent += new SftpCommandSentEventHandler(client_CommandSent);
client.ResponseRead += new SftpResponseReadEventHandler(client_ResponseRead);
client.Connect("sftp.example.org");

//... 
private void client_CommandSent(object sender, SftpCommandSentEventArgs e)
{
    Console.WriteLine("Command: {0}", e.Command);
}

private void client_ResponseRead(object sender, SftpResponseReadEventArgs e)
{
    Console.WriteLine("Response: {0}", e.Response);
}

For more info see tutorial or download a trial and check samples.

MySQL query to select events between start/end date

EDIT: I've squeezed the filter a lot. I couldn't wrap my head around it before how to make sure something really fit within the time period. It's this: Start date BEFORE the END of the time period, and End date AFTER the BEGINNING of the time period

With the help of someone in my office I think we've figured out how to include everyone in the filter. There are 5 scenarios where a student would be deemed active during the time period in question:

1) Student started and ended during the time period.

2) Student started before and ended during the time period.

3) Student started before and ended after the time period.

4) Student started during the time period and ended after the time period.

5) Student started during the time period and is still active (Doesn't have an end date yet)

Given these criteria, we can actually condense the statements into a few groups because a student can only end between the period dates, after the period date, or they don't have an end date:

1) Student ends during the time period AND [Student starts before OR during]

2) Student ends after the time period AND [Student starts before OR during]

3) Student hasn't finished yet AND [Student starts before OR during]

   (
        (
         student_programs.END_DATE  >=  '07/01/2017 00:0:0'
         OR
         student_programs.END_DATE  Is Null  
        )
        AND
        student_programs.START_DATE  <=  '06/30/2018 23:59:59'
   )

I think this finally covers all the bases and includes all scenarios where a student, or event, or anything is active during a time period when you only have start date and end date. Please, do not hesitate to tell me that I am missing something. I want this to be perfect so others can use this, as I don't believe the other answers have gotten everything right yet.

Which data structures and algorithms book should I buy?

Introduction to Algorithms by Cormen et. al. is a standard introductory algorithms book, and is used by many universities, including my own. It has pretty good coverage and is very approachable.

And anything by Robert Sedgewick is good too.

How can I alter a primary key constraint using SQL syntax?

PRIMARY KEY CONSTRAINT cannot be altered, you may only drop it and create again. For big datasets it can cause a long run time and thus - table inavailability.

How do I pass multiple attributes into an Angular.js attribute directive?

You could pass an object as attribute and read it into the directive like this:

<div my-directive="{id:123,name:'teo',salary:1000,color:red}"></div>

app.directive('myDirective', function () {
    return {            
        link: function (scope, element, attrs) {
           //convert the attributes to object and get its properties
           var attributes = scope.$eval(attrs.myDirective);       
           console.log('id:'+attributes.id);
           console.log('id:'+attributes.name);
        }
    };
});

Launch an app on OS X with command line

You can launch apps using open:

open -a APP_YOU_WANT

This should open the application that you want.

How to check if a variable is an integer or a string?

if you want to check what it is:

>>>isinstance(1,str)
False
>>>isinstance('stuff',str)
True
>>>isinstance(1,int)
True
>>>isinstance('stuff',int)
False

if you want to get ints from raw_input

>>>x=raw_input('enter thing:')
enter thing: 3
>>>try: x = int(x)
   except: pass

>>>isinstance(x,int)
True

Laravel 5 call a model function in a blade view

In new version of Laravel you can use "Service Injection".

https://laravel.com/docs/5.8/blade#service-injection

/resources/views/main.blade.php

@inject('project', 'App\Project')

<h1>{{ $project->get_title() }}</h1>

Will #if RELEASE work like #if DEBUG does in C#?

RELEASE is not defined, but you can use

#if (!DEBUG)
  ...
#endif

jQuery if div contains this text, replace that part of the text

var d = $('.text_div');
d.text(d.text().trim().replace(/contains/i, "hello everyone"));

How to pass a value from one Activity to another in Android?

Implement in this way

String i="hi";
Intent i = new Intent(this, ActivityTwo.class);
//Create the bundle
Bundle b = new Bundle();
//Add your data to bundle
b.putString(“stuff”, i);
i.putExtras(b);
startActivity(i);

Begin that second activity, inside this class to utilize the Bundle values use this code

Bundle bundle = getIntent().getExtras();
String text= bundle.getString("stuff");

ASP.NET MVC Dropdown List From SelectList

Try this, just an example:

u.UserTypeOptions = new SelectList(new[]
    {
        new { ID="1", Name="name1" },
        new { ID="2", Name="name2" },
        new { ID="3", Name="name3" },
    }, "ID", "Name", 1);

Or

u.UserTypeOptions = new SelectList(new List<SelectListItem>
    {
        new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
        new SelectListItem { Selected = false, Text = "Homeowner", Value = "2"},
        new SelectListItem { Selected = false, Text = "Contractor", Value = "3"},
    },"Value","Text");

How can I create a Java method that accepts a variable number of arguments?

This is just an extension to above provided answers.

  1. There can be only one variable argument in the method.
  2. Variable argument (varargs) must be the last argument.

Clearly explained here and rules to follow to use Variable Argument.

What are the new features in C++17?

Language features:

Templates and Generic Code

Lambda

Attributes

Syntax cleanup

Cleaner multi-return and flow control

  • Structured bindings

    • Basically, first-class std::tie with auto
    • Example:
      • const auto [it, inserted] = map.insert( {"foo", bar} );
      • Creates variables it and inserted with deduced type from the pair that map::insert returns.
    • Works with tuple/pair-likes & std::arrays and relatively flat structs
    • Actually named structured bindings in standard
  • if (init; condition) and switch (init; condition)

    • if (const auto [it, inserted] = map.insert( {"foo", bar} ); inserted)
    • Extends the if(decl) to cases where decl isn't convertible-to-bool sensibly.
  • Generalizing range-based for loops

    • Appears to be mostly support for sentinels, or end iterators that are not the same type as begin iterators, which helps with null-terminated loops and the like.
  • if constexpr

    • Much requested feature to simplify almost-generic code.

Misc

Library additions:

Data types

Invoke stuff

File System TS v1

New algorithms

  • for_each_n

  • reduce

  • transform_reduce

  • exclusive_scan

  • inclusive_scan

  • transform_exclusive_scan

  • transform_inclusive_scan

  • Added for threading purposes, exposed even if you aren't using them threaded

Threading

(parts of) Library Fundamentals TS v1 not covered above or below

Container Improvements

Smart pointer changes

Other std datatype improvements:

Misc

Traits

Deprecated

Isocpp.org has has an independent list of changes since C++14; it has been partly pillaged.

Naturally TS work continues in parallel, so there are some TS that are not-quite-ripe that will have to wait for the next iteration. The target for the next iteration is C++20 as previously planned, not C++19 as some rumors implied. C++1O has been avoided.

Initial list taken from this reddit post and this reddit post, with links added via googling or from the above isocpp.org page.

Additional entries pillaged from SD-6 feature-test list.

clang's feature list and library feature list are next to be pillaged. This doesn't seem to be reliable, as it is C++1z, not C++17.

these slides had some features missing elsewhere.

While "what was removed" was not asked, here is a short list of a few things ((mostly?) previous deprecated) that are removed in C++17 from C++:

Removed:

There were rewordings. I am unsure if these have any impact on code, or if they are just cleanups in the standard:

Papers not yet integrated into above:

  • P0505R0 (constexpr chrono)

  • P0418R2 (atomic tweaks)

  • P0512R0 (template argument deduction tweaks)

  • P0490R0 (structured binding tweaks)

  • P0513R0 (changes to std::hash)

  • P0502R0 (parallel exceptions)

  • P0509R1 (updating restrictions on exception handling)

  • P0012R1 (make exception specifications be part of the type system)

  • P0510R0 (restrictions on variants)

  • P0504R0 (tags for optional/variant/any)

  • P0497R0 (shared ptr tweaks)

  • P0508R0 (structured bindings node handles)

  • P0521R0 (shared pointer use count and unique changes?)

Spec changes:

Further reference:

How to overload __init__ method based on argument type?

A much neater way to get 'alternate constructors' is to use classmethods. For instance:

>>> class MyData:
...     def __init__(self, data):
...         "Initialize MyData from a sequence"
...         self.data = data
...     
...     @classmethod
...     def fromfilename(cls, filename):
...         "Initialize MyData from a file"
...         data = open(filename).readlines()
...         return cls(data)
...     
...     @classmethod
...     def fromdict(cls, datadict):
...         "Initialize MyData from a dict's items"
...         return cls(datadict.items())
... 
>>> MyData([1, 2, 3]).data
[1, 2, 3]
>>> MyData.fromfilename("/tmp/foobar").data
['foo\n', 'bar\n', 'baz\n']
>>> MyData.fromdict({"spam": "ham"}).data
[('spam', 'ham')]

The reason it's neater is that there is no doubt about what type is expected, and you aren't forced to guess at what the caller intended for you to do with the datatype it gave you. The problem with isinstance(x, basestring) is that there is no way for the caller to tell you, for instance, that even though the type is not a basestring, you should treat it as a string (and not another sequence.) And perhaps the caller would like to use the same type for different purposes, sometimes as a single item, and sometimes as a sequence of items. Being explicit takes all doubt away and leads to more robust and clearer code.

Using jq to parse and display multiple fields in a json serially

my approach will be (your json example is not well formed.. guess thats only a sample)

jq '.Front[] | [.Name,.Out,.In,.Groups] | join("|")'  front.json  > output.txt

returns something like this

"new.domain.com-80|8.8.8.8|192.168.2.2:80|192.168.3.29:80 192.168.3.30:80"
"new.domain.com -443|8.8.8.8|192.168.2.2:443|192.168.3.29:443 192.168.3.30:443"

and grep the output with regular expression.

How to check if a line has one of the strings in a list?

strings = ("string1", "string2", "string3")
for line in file:
    if any(s in line for s in strings):
        print "yay!"

How to convert all tables in database to one collation?

If you want a copy-paste bash script:

var=$(mysql -e 'SELECT CONCAT("ALTER TABLE ", TABLE_NAME," CONVERT TO CHARACTER SET utf8 COLLATE utf8_czech_ci;") AS execTabs FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="zabbix" AND TABLE_TYPE="BASE TABLE"' -uroot -p )

var+='ALTER DATABASE zabbix CHARACTER SET utf8 COLLATE utf8_general_ci;'

echo $var | cut -d " " -f2- | mysql -uroot -p zabbix

Change zabbix to your database name.

List of swagger UI alternatives

Yes, there are a few of them.

Hosted solutions that support swagger:

Check the following articles for more details:

Searching multiple files for multiple words

If you are using Notepad++ editor (like the tag of the question suggests), you can use the great "Find in Files" functionality.

Go to Search > Find in Files (Ctrl+Shift+F for the keyboard addicted) and enter:

  • Find What = (test1|test2)
  • Filters = *.txt
  • Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.
  • Search mode = Regular Expression

How can I write an anonymous function in Java?

Anonymous inner classes implementing or extending the interface of an existing type has been done in other answers, although it is worth noting that multiple methods can be implemented (often with JavaBean-style events, for instance).

A little recognised feature is that although anonymous inner classes don't have a name, they do have a type. New methods can be added to the interface. These methods can only be invoked in limited cases. Chiefly directly on the new expression itself and within the class (including instance initialisers). It might confuse beginners, but it can be "interesting" for recursion.

private static String pretty(Node node) {
    return "Node: " + new Object() {
        String print(Node cur) {
            return cur.isTerminal() ?
                cur.name() :
                ("("+print(cur.left())+":"+print(cur.right())+")");
        }
    }.print(node);
}

(I originally wrote this using node rather than cur in the print method. Say NO to capturing "implicitly final" locals?)

variable or field declared void

This is not actually a problem with the function being "void", but a problem with the function parameters. I think it's just g++ giving an unhelpful error message.

EDIT: As in the accepted answer, the fix is to use std::string instead of just string.

String.Format alternative in C++

You can just concatenate the strings and build a command line.

std::string command = a + ' ' + b + " > " + c;
system(command.c_str());

You don't need any extra libraries for this.

Sort a single String in Java

Convert to array of chars ? Sort ? Convert back to String:

String s = "edcba";
char[] c = s.toCharArray();        // convert to array of chars 
java.util.Arrays.sort(c);          // sort
String newString = new String(c);  // convert back to String
System.out.println(newString);     // "abcde"

Android ADT error, dx.jar was not loaded from the SDK folder

Updating Android SDK platform-tools with the Android SDK Manager and restarting Eclipse did it for me

Why should we include ttf, eot, woff, svg,... in a font-face

Woff is a compressed (zipped) form of the TrueType - OpenType font. It is small and can be delivered over the network like a graphic file. Most importantly, this way the font is preserved completely including rendering rule tables that very few people care about because they use only Latin script.

Take a look at [dead URL removed]. The font you see is an experimental web delivered smartfont (woff) that has thousands of combined characters making complex shapes. The underlying text is simple Latin code of romanized Singhala. (Copy and paste to Notepad and see).

Only woff can do this because nobody has this font and yet it is seen anywhere (Mac, Win, Linux and even on smartphones by all browsers except by IE. IE does not have full support for Open Types).

Put search icon near textbox using bootstrap

Adding a class with a width of 90% to your input element and adding the following input-icon class to your span would achieve what you want I think.

.input { width: 90%; }
.input-icon {
    display: inline-block;
    height: 22px;
    width: 22px;
    line-height: 22px;
    text-align: center;
    color: #000;
    font-size: 12px;
    font-weight: bold;
    margin-left: 4px;
}

EDIT Per dan's suggestion, it would not be wise to use .input as the class name, some more specific would be advised. I was simply using .input as a generic placeholder for your css

Failed to find Build Tools revision 23.0.1

Check your $ANDROID_HOME, sometimes is /usr/local/opt/android, but it's not your install sdk path, change it and fix this problem

How to execute a stored procedure within C# program

SqlConnection conn = null;
SqlDataReader rdr  = null;
conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
conn.Open();

// 1.  create a command object identifying
//     the stored procedure
SqlCommand cmd  = new SqlCommand("CustOrderHist", conn);

// 2. set the command object so it knows
//    to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;

// 3. add parameter to command, which
//    will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));

// execute the command
rdr = cmd.ExecuteReader();

// iterate through results, printing each to console
while (rdr.Read())
{
    Console.WriteLine("Product: {0,-35} Total: {1,2}", rdr["ProductName"], rdr["Total"]);
}

Difference between npx and npm?

Introducing npx: an npm package runner

NPM - Manages packages but doesn't make life easy executing any.
NPX - A tool for executing Node packages.

NPX comes bundled with NPM version 5.2+

NPM by itself does not simply run any package. it doesn't run any package in a matter of fact. If you want to run a package using NPM, you must specify that package in your package.json file.

When executables are installed via NPM packages, NPM links to them:

  1. local installs have "links" created at ./node_modules/.bin/ directory.
  2. global installs have "links" created from the global bin/ directory (e.g. /usr/local/bin) on Linux or at %AppData%/npm on Windows.

Documentation you should read


NPM:

One might install a package locally on a certain project:

npm install some-package

Now let's say you want NodeJS to execute that package from the command line:

$ some-package

The above will fail. Only globally installed packages can be executed by typing their name only.

To fix this, and have it run, you must type the local path:

$ ./node_modules/.bin/some-package

You can technically run a locally installed package by editing your packages.json file and adding that package in the scripts section:

{
  "name": "whatever",
  "version": "1.0.0",
  "scripts": {
    "some-package": "some-package"
  }
}

Then run the script using npm run-script (or npm run):

npm run some-package

NPX:

npx will check whether <command> exists in $PATH, or in the local project binaries, and execute it. So, for the above example, if you wish to execute the locally-installed package some-package all you need to do is type:

npx some-package

Another major advantage of npx is the ability to execute a package which wasn't previously installed:

$ npx create-react-app my-app

The above example will generate a react app boilerplate within the path the command had run in, and ensures that you always use the latest version of a generator or build tool without having to upgrade each time you’re about to use it.


Use-Case Example:

npx command may be helpful in the script section of a package.json file, when it is unwanted to define a dependency which might not be commonly used or any other reason:

"scripts": {
    "start": "npx [email protected]",
    "serve": "npx http-server"
}

Call with: npm run serve


Related questions:

  1. How to use package installed locally in node_modules?
  2. NPM: how to source ./node_modules/.bin folder?
  3. How do you run a js file using npm scripts?

How to make the corners of a button round?

This link has all the information you need. Here

Shape.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape      xmlns:android="http://schemas.android.com/apk/res/android"
            android:shape="rectangle">

    <solid   android:color="#EAEAEA"/>

    <corners    android:bottomLeftRadius="8dip"
                android:topRightRadius="8dip"
                android:topLeftRadius="1dip"
                android:bottomRightRadius="1dip"
                />
</shape>

and main.xml

<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="fill_parent"
              android:layout_height="fill_parent">

    <TextView   android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:text="Hello Android from NetBeans"/>

    <Button android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Nishant Nair"
            android:padding="5dip"
            android:layout_gravity="center"
            android:background="@drawable/button_shape"
            />
</LinearLayout>

This should give you your desired result.

Best of luck

Align div with fixed position on the right side

Trying to do the same thing. If you want it to be aligned on the right side then set the value of right to 0. In case you need some padding from the right, set the value to the size of the padding you need.

Example:

.test {
  position: fixed;
  right: 20px; /* Padding from the right side */
}

Smooth scrolling when clicking an anchor link

I suggest you to make this generic code :

$('a[href^="#"]').click(function(){

var the_id = $(this).attr("href");

    $('html, body').animate({
        scrollTop:$(the_id).offset().top
    }, 'slow');

return false;});

You can see a very good article here : jquery-effet-smooth-scroll-defilement-fluide

How can I list all collections in the MongoDB shell?

If you want to show all collections from the MongoDB shell (command line), use the shell helper,

show collections

that shows all collections for the current database. If you want to get all collection lists from your application then you can use the MongoDB database method

db.getCollectionNames()

For more information about the MongoDB shell helper, you can see mongo Shell Quick Reference.

What’s the best way to load a JSONObject from a json text file?

try this:

import net.sf.json.JSONObject;
import net.sf.json.JSONSerializer;
import org.apache.commons.io.IOUtils; 

    public class JsonParsing {

        public static void main(String[] args) throws Exception {
            InputStream is = 
                    JsonParsing.class.getResourceAsStream( "sample-json.txt");
            String jsonTxt = IOUtils.toString( is );

            JSONObject json = (JSONObject) JSONSerializer.toJSON( jsonTxt );        
            double coolness = json.getDouble( "coolness" );
            int altitude = json.getInt( "altitude" );
            JSONObject pilot = json.getJSONObject("pilot");
            String firstName = pilot.getString("firstName");
            String lastName = pilot.getString("lastName");

            System.out.println( "Coolness: " + coolness );
            System.out.println( "Altitude: " + altitude );
            System.out.println( "Pilot: " + lastName );
        }
    }

and this is your sample-json.txt , should be in json format

{
 'foo':'bar',
 'coolness':2.0,
 'altitude':39000,
 'pilot':
     {
         'firstName':'Buzz',
         'lastName':'Aldrin'
     },
 'mission':'apollo 11'
}

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

Removing child association cascading

So, you need to remove the @CascadeType.ALL from the @ManyToOne association. Child entities should not cascade to parent associations. Only parent entities should cascade to child entities.

@ManyToOne(fetch= FetchType.LAZY)

Notice that I set the fetch attribute to FetchType.LAZY because eager fetching is very bad for performance.

Setting both sides of the association

Whenever you have a bidirectional association, you need to synchronize both sides using addChild and removeChild methods in the parent entity:

public void addTransaction(Transaction transaction) {
    transcations.add(transaction);
    transaction.setAccount(this);
}

public void removeTransaction(Transaction transaction) {
    transcations.remove(transaction);
    transaction.setAccount(null);
}

Change package name for Android in React Native

very simple way :

cd /your/project/dir

run this command :

grep -rl "com.your.app" . | xargs sed -i 's/com.your.app/com.yournew.newapp/g'

rename your folder

android/app/src/main/java/com/your/app

change to

android/app/src/main/java/com/yournew/newapp

How do I get Flask to run on port 80?

On my scenario the following steps worked like a charm:

  • Installing the package:

    pip install --upgrade pip
    pip install python-dotenv
    
  • Creating a hidden file in my app directory "flaskr/.flaskenv"

  • Adding the following content:

    FLASK_APP=flaskr
    FLASK_RUN_HOST=localhost
    FLASK_RUN_PORT=8000
    
  • Finally, run the flask command one more time:

    flask run
    
  • The version which I am working on is:

    pip freeze |grep -i flask
    Flask==1.1.1
    

Send POST request using NSURLSession

    use like this.....

    Create file

    #import <Foundation/Foundation.h>`    
    #import "SharedManager.h"
    #import "Constant.h"
    #import "UserDetails.h"

    @interface APISession : NSURLSession<NSURLSessionDelegate>
    @property (nonatomic, retain) NSMutableData *responseData;
    +(void)postRequetsWithParam:(NSMutableDictionary* )objDic withAPIName:(NSString* 
    )strAPIURL completionHandler:(void (^)(id result, BOOL status))completionHandler;
    @end

****************.m*************************
    #import "APISession.h"
    #import <UIKit/UIKit.h>
    @implementation APISession

    +(void)postRequetsWithParam:(NSMutableDictionary *)objDic withAPIName:(NSString 
    *)strAPIURL completionHandler:(void (^)(id, BOOL))completionHandler
    {
    NSURL *url=[NSURL URLWithString:strAPIURL];
    NSMutableURLRequest *request=[[NSMutableURLRequest alloc]initWithURL:url];
    [request setHTTPMethod:@"POST"];
    [request addValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    NSError *err = nil;

    NSData *data=[NSJSONSerialization dataWithJSONObject:objDic options:NSJSONWritingPrettyPrinted error:&err];
    [request setHTTPBody:data];

    NSString *strJsonFormat = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSLog(@"API URL: %@ \t  Api Request Parameter ::::::::::::::%@",url,strJsonFormat);
    //    NSLog(@"Request data===%@",objDic);
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];

    //  NSURLSession *session=[NSURLSession sharedSession];

    NSURLSessionTask *task=[session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error)
                            {
                                if (error==nil) {
                                    NSDictionary *dicData=[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingAllowFragments error:&error];\
                                    NSLog(@"Response Data=============%@",dicData);
                                    if([[dicData valueForKey:@"tokenExpired"]integerValue] == 1)
                                    {

                                        NSLog(@"hello");
                                        NSDictionary *dict = [NSDictionary dictionaryWithObject:@"Access Token Expire." forKey:@"message"];
                                        [[NSNotificationCenter defaultCenter] postNotificationName:@"UserLogOut" object:self userInfo:dict];
                                    }
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        completionHandler(dicData,(error == nil));
                                    });
                                    NSLog(@"%@",dicData);
                                }
                                else{
                                    dispatch_async(dispatch_get_main_queue(), ^{
                                        completionHandler(error.localizedDescription,NO);
                                    });
                                }
                            }];
    //    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
    [task resume];
    //    });
    }
    @end

    *****************************in .your view controller***********
    #import "file"
    txtEmail.text = [txtEmail.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];

    {
            [SVProgressHUD showWithStatus:@"Loading..."];
            [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeGradient];

            NSMutableDictionary *objLoginDic=[[NSMutableDictionary alloc] init];
            [objLoginDic setValue:txtEmail.text forKey:@"email"];
            [objLoginDic setValue:@0            forKey:kDeviceType];
            [objLoginDic setValue:txtPassword.text forKey:kPassword];
            [objLoginDic setValue:@"376545432"  forKey:kDeviceTokan];
            [objLoginDic setValue:@""           forKey:kcountryId];
            [objLoginDic setValue:@""           forKey:kfbAccessToken];
            [objLoginDic setValue:@0            forKey:kloginType];

            [APISession postRequetsWithParam:objLoginDic withAPIName:KLOGIN_URL completionHandler:^(id result, BOOL status) {

                [SVProgressHUD dismiss];

                NSInteger statusResponse=[[result valueForKey:kStatus] integerValue];
                NSString *strMessage=[result valueForKey:KMessage];
                if (status) {
                    if (statusResponse == 1)
                {
                        UserDetails *objLoginUserDetail=[[UserDetails alloc] 
                        initWithObject:[result valueForKey:@"userDetails"]];
                          [[NSUserDefaults standardUserDefaults] 
                        setObject:@(objLoginUserDetail.userId) forKey:@"user_id"];
                        [[NSUserDefaults standardUserDefaults] synchronize];
                        [self clearTextfeilds];
                        HomeScreen *obj=[Kiran_Storyboard instantiateViewControllerWithIdentifier:@"HomeScreen"];
                        [self.navigationController pushViewController:obj animated:YES];
                    }
                    else{
                        [strMessage showAsAlert:self];
                    }
                }
            }];
        }
**********use model class for represnt data*************

    #import <Foundation/Foundation.h>
    #import "Constant.h"
    #import <objc/runtime.h>


    @interface UserDetails : NSObject
    @property(strong,nonatomic) NSString *emailId,
    *deviceToken,
    *countryId,
    *fbAccessToken,
    *accessToken,
    *countryName,
    *isProfileSetup,
    *profilePic,
    *firstName,
    *lastName,
    *password;

    @property (assign) NSInteger userId,deviceType,loginType;

    -(id)initWithObject :(NSDictionary *)dicUserData;
    -(void)saveLoginUserDetail;
    +(UserDetails *)getLoginUserDetail;
    -(UserDetails *)getEmptyModel;
    - (NSArray *)allPropertyNames;
    -(void)printDescription;
       -(NSMutableDictionary *)getDictionary;

    @end

    ******************model.m*************

    #import "UserDetails.h"
    #import "SharedManager.h"

    @implementation UserDetails



      -(id)initWithObject :(NSDictionary *)dicUserData
       {
       self = [[UserDetails alloc] init];
       if (self)
       {
           @try {
               [self setFirstName:([dicUserData valueForKey:@"firstName"] != [NSNull null])? 
               [dicUserData valueForKey:@"firstName"]:@""];


               [self setUserId:([dicUserData valueForKey:kUserId] != [NSNull null])? 
               [[dicUserData valueForKey:kUserId] integerValue]:0];


               }
        @catch (NSException *exception) {
            NSLog(@"Exception: %@",exception.description);
        }
        @finally {
        }
    }
    return self;
}

    -(UserDetails *)getEmptyModel{
    [self setFirstName:@""];
    [self setLastName:@""];



    [self setDeviceType:0];


    return self;
       }

     -  (void)encodeWithCoder:(NSCoder *)encoder {
    //    Encode properties, other class variables, etc
    [encoder encodeObject:_firstName forKey:kFirstName];


    [encoder encodeObject:[NSNumber numberWithInteger:_deviceType] forKey:kDeviceType];

    }

    - (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        _firstName = [decoder decodeObjectForKey:kEmailId];

        _deviceType= [[decoder decodeObjectForKey:kDeviceType] integerValue];

    }
    return self;
    }
    - (NSArray *)allPropertyNames
    {
    unsigned count;
    objc_property_t *properties = class_copyPropertyList([self class], &count);

    NSMutableArray *rv = [NSMutableArray array];

    unsigned i;
    for (i = 0; i < count; i++)
    {
        objc_property_t property = properties[i];
        NSString *name = [NSString stringWithUTF8String:property_getName(property)];
        [rv addObject:name];
    }

    free(properties);

    return rv; 
    } 

    -(void)printDescription{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];

    for(NSString *key in [self allPropertyNames])
    {
        [dic setValue:[self valueForKey:key] forKey:key];
    }
    NSLog(@"\n========================= User Detail ==============================\n");
    NSLog(@"%@",[dic description]);
    NSLog(@"\n=============================================================\n");
    }
    -(NSMutableDictionary *)getDictionary{
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    for(NSString *key in [self allPropertyNames])
    {
        [dic setValue:[self valueForKey:key] forKey:key];
    }
    return dic;
    }
    #pragma mark
    #pragma mark - Save and get User details
    -(void)saveLoginUserDetail{
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:self];
    [Shared_UserDefault setObject:encodedObject forKey:kUserDefault_SavedUserDetail];
    [Shared_UserDefault synchronize];
    }
      +(UserDetails *)getLoginUserDetail{
      NSData *encodedObject = [Shared_UserDefault objectForKey:kUserDefault_SavedUserDetail];
    UserDetails *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
   }
    @end


     ************************usefull code while add data into model and get data********

                   NSLog(@"Response %@",result);
                  NSString *strMessg = [result objectForKey:kMessage];
                 NSString *status = [NSString stringWithFormat:@"%@",[result 
                objectForKey:kStatus]];

            if([status isEqualToString:@"1"])
            {
                arryBankList =[[NSMutableArray alloc]init];

                NSMutableArray *arrEvents=[result valueForKey:kbankList];
                ShareOBJ.isDefaultBank = [result valueForKey:kisDefaultBank];
                if ([arrEvents count]>0)
                {

                for (NSMutableArray *dic in arrEvents)
                    {
                        BankList *objBankListDetail =[[BankList alloc]initWithObject:[dic 
                         mutableCopy]];
                        [arryBankList addObject:objBankListDetail];
                    }
           //display data using model...
           BankList *objBankListing  =[arryBankList objectAtIndex:indexPath.row];

TCPDF output without saving file

I've been using the Output("doc.pdf", "I"); and it doesn't work, I'm always asked for saving the file.

I took a look in documentation and found that

I send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects the "Save as" option on the link generating the PDF. http://www.tcpdf.org/doc/classTCPDF.html#a3d6dcb62298ec9d42e9125ee2f5b23a1

Then I think you have to use a plugin to print it, otherwise it is going to be downloaded.