Programs & Examples On #Qtableview

QTableView is a Qt class providing a default model/view implementation of a table view.

How to resolve the "ADB server didn't ACK" error?

Try the following:

  • Close Eclipse.
  • Restart your phone.
  • End adb.exe process in Task Manager (Windows). In Mac, force close in Activity Monitor.
  • Issue kill and start command in \platform-tools\
    • C:\sdk\platform-tools>adb kill-server
    • C:\sdk\platform-tools>adb start-server
  • If it says something like 'started successfully', you are good.

Regex to match URL end-of-line or "/" character

To match either / or end of content, use (/|\z)

This only applies if you are not using multi-line matching (i.e. you're matching a single URL, not a newline-delimited list of URLs).


To put that with an updated version of what you had:

/(\S+?)/(\d{4}-\d{2}-\d{2})-(\d+)(/|\z)

Note that I've changed the start to be a non-greedy match for non-whitespace ( \S+? ) rather than matching anything and everything ( .* )

CSS-moving text from left to right

You could simply use CSS animated text generator. There are pre-created templates already

What's the proper way to compare a String to an enum value?

public class Main {

    enum Vehical{
        Car,
        Bus,
        Van
    }

    public static void main(String[] args){

      String vehicalType = "CAR";

        if(vehicalType.equals(Vehical.Car.name())){
            System.out.println("The provider is Car");
        }

     String vehical_Type = "BUS";

       if(vehical_Type.equals(Vehical.Bus.toString())){
            System.out.println("The provider is Bus");
        }


    }
}

How do I see active SQL Server connections?

MS's query explaining the use of the KILL command is quite useful providing connection's information:

SELECT conn.session_id, host_name, program_name,
    nt_domain, login_name, connect_time, last_request_end_time 
FROM sys.dm_exec_sessions AS sess
JOIN sys.dm_exec_connections AS conn
   ON sess.session_id = conn.session_id;

Oracle - What TNS Names file am I using?

On my development machine I have three different versions of Oracle client software. I manage the tnsnames.ora file in one of them. In the other two, I have entered in the tnsnames.ora file:

ifile=path_to_tnsnames.ora_file/tnsnames.ora

This way, if for some reason the wrong tnsnames.ora file is used by a client, it will always end up at the up-to-date version.

How can I "disable" zoom on a mobile web page?

<script type="text/javascript">
document.addEventListener('touchmove', function (event) {
  if (event.scale !== 1) { event.preventDefault(); }
}, { passive: false });
</script>

Please Add the Script to Disable pinch, tap, focus Zoom

typedef struct vs struct definitions

struct and typedef are two very different things.

The struct keyword is used to define, or to refer to, a structure type. For example, this:

struct foo {
    int n;
};

creates a new type called struct foo. The name foo is a tag; it's meaningful only when it's immediately preceded by the struct keyword, because tags and other identifiers are in distinct name spaces. (This is similar to, but much more restricted than, the C++ concept of namespaces.)

A typedef, in spite of the name, does not define a new type; it merely creates a new name for an existing type. For example, given:

typedef int my_int;

my_int is a new name for int; my_int and int are exactly the same type. Similarly, given the struct definition above, you can write:

typedef struct foo foo;

The type already has a name, struct foo. The typedef declaration gives the same type a new name, foo.

The syntax allows you to combine a struct and typedef into a single declaration:

typedef struct bar {
    int n;
} bar;

This is a common idiom. Now you can refer to this structure type either as struct bar or just as bar.

Note that the typedef name doesn't become visible until the end of the declaration. If the structure contains a pointer to itself, you have use the struct version to refer to it:

typedef struct node {
    int data;
    struct node *next; /* can't use just "node *next" here */
} node;

Some programmers will use distinct identifiers for the struct tag and for the typedef name. In my opinion, there's no good reason for that; using the same name is perfectly legal and makes it clearer that they're the same type. If you must use different identifiers, at least use a consistent convention:

typedef struct node_s {
    /* ... */
} node;

(Personally, I prefer to omit the typedef and refer to the type as struct bar. The typedef save a little typing, but it hides the fact that it's a structure type. If you want the type to be opaque, this can be a good thing. If client code is going to be referring to the member n by name, then it's not opaque; it's visibly a structure, and in my opinion it makes sense to refer to it as a structure. But plenty of smart programmers disagree with me on this point. Be prepared to read and understand code written either way.)

(C++ has different rules. Given a declaration of struct blah, you can refer to the type as just blah, even without a typedef. Using a typedef might make your C code a little more C++-like -- if you think that's a good thing.)

Cheap way to search a large text file for a string

This is entirely inspired by laurasia's answer above, but it refines the structure.

It also adds some checks:

  • It will correctly return 0 when searching an empty file for the empty string. In laurasia's answer, this is an edge case that will return -1.
  • It also pre-checks whether the goal string is larger than the buffer size, and raises an error if this is the case.

In practice, the goal string should be much smaller than the buffer for efficiency, and there are more efficient methods of searching if the size of the goal string is very close to the size of the buffer.

def fnd(fname, goal, start=0, bsize=4096):
    if bsize < len(goal):
        raise ValueError("The buffer size must be larger than the string being searched for.")
    with open(fname, 'rb') as f:
        if start > 0:
            f.seek(start)
        overlap = len(goal) - 1
        while True:
            buffer = f.read(bsize)
            pos = buffer.find(goal)
            if pos >= 0:
                return f.tell() - len(buffer) + pos
            if not buffer:
                return -1
            f.seek(f.tell() - overlap)

height: 100% for <div> inside <div> with display: table-cell

When you use % for setting heights or widths, always set the widths/heights of parent elements as well:

_x000D_
_x000D_
.table {_x000D_
    display: table;_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.cell {_x000D_
    border: 2px solid black;_x000D_
    vertical-align: top;_x000D_
    display: table-cell;_x000D_
    height: 100%;_x000D_
}_x000D_
_x000D_
.container {_x000D_
    height: 100%;_x000D_
    border: 2px solid green;_x000D_
    -moz-box-sizing: border-box;_x000D_
}
_x000D_
<div class="table">_x000D_
    <div class="cell">_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
        <p>Text_x000D_
    </div>_x000D_
    <div class="cell">_x000D_
        <div class="container">Text</div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

InsecurePlatformWarning: A true SSLContext object is not available. This prevents urllib3 from configuring SSL appropriately

The docs give a fair indicator of what's required., however requests allow us to skip a few steps:

You only need to install the security package extras (thanks @admdrew for pointing it out)

$ pip install requests[security]

or, install them directly:

$ pip install pyopenssl ndg-httpsclient pyasn1

Requests will then automatically inject pyopenssl into urllib3


If you're on ubuntu, you may run into trouble installing pyopenssl, you'll need these dependencies:

$ apt-get install libffi-dev libssl-dev

python: sys is not defined

In addition to the answers given above, check the last line of the error message in your console. In my case, the 'site-packages' path in sys.path.append('.....') was wrong.

How to pass value from <option><select> to form action

Like @Shoaib answered, you dont need any jQuery or Javascript. You can to this simply with pure html!

<form method="POST" action="index.php?action=contact_agent">
  <select name="agent_id" required>
    <option value="1">Agent Homer</option>
    <option value="2">Agent Lenny</option>
    <option value="3">Agent Carl</option>
  </select>
  <input type="submit" value="Submit">
</form>
  1. Remove &agent_id= from form action since you don't need it there.
  2. Add name="agent_id" to the select
  3. Optionally add word required do indicate that this selection is required.

Since you are using PHP, then by posting the form to index.php you can catch agent_id with $_POST

/** Since you reference action on `form action` then value of $_GET['action'] will be contact_agent */
$action = $_GET['action'];

/** Value of $_POST['agent_id'] will be selected option value */
$agent_id = $_POST['agent_id']; 

As conclusion for such a simple task you should not use any javascript or jQuery. To @FelipeAlvarez that answers your comment

Maven: Failed to read artifact descriptor

I solved this issue by deleting in the repository folders where this error was shown everything except the .jar and .pom files.

How to combine paths in Java?

If you do not need more than strings, you can use com.google.common.io.Files

Files.simplifyPath("some/prefix/with//extra///slashes" + "file//name")

to get

"some/prefix/with/extra/slashes/file/name"

Serializing a list to JSON

If you're doing this in the context of a asp.Net Core API action, the conversion to Json is done implicitly.

[HttpGet]
public ActionResult Get()
{
    return Ok(TheList);
}

PHP PDO returning single row

Just fetch. only gets one row. So no foreach loop needed :D

$row  = $STH -> fetch();

example (ty northkildonan):

$dbh = new PDO(" --- connection string --- "); 
$stmt = $dbh->prepare("SELECT name FROM mytable WHERE id=4 LIMIT 1"); 
$stmt->execute(); 
$row = $stmt->fetch();

How can I make a TextArea 100% width without overflowing when padding is present in CSS?

You can make use of the box-sizing property, it's supported by all the main standard-compliant browsers and IE8+. You still will need a workaround for IE7 though. Read more here.

What is the equivalent of ngShow and ngHide in Angular 2+?

<div [hidden]="flagValue">
---content---
</div>

What does the Visual Studio "Any CPU" target mean?

Check out the article Visual Studio .NET Platform Target Explained.

The default setting, "Any CPU", means that the assembly will run natively on the CPU it is currently running on. Meaning, it will run as 64-bit on a 64-bit machine and 32-bit on a 32-bit machine. If the assembly is called from a 64-bit application, it will perform as a 64-bit assembly and so on.

The above link has been reported to be broken, so here is another article with a similar explanation: What AnyCPU Really Means As Of .NET 4.5 and Visual Studio 11

Give all permissions to a user on a PostgreSQL database

GRANT ALL PRIVILEGES ON DATABASE "my_db" to my_user;

an attempt was made to access a socket in a way forbbiden by its access permissions. why?

I've had this problem when trying to start a dotnet Core project using dotnet run when it tried to bind to the port.

The problem was caused by having a Visual Studio 2017 instance running with the project open - I'd previously started the project via VS for debugging and it appears that it was holding on to the port, even though debugging had finished and the application appeared closed.

Closing the Visual Studio instance and running "dotnet run" again solved the problem.

How can I output the value of an enum class in C++11

(I'm not allowed to comment yet.) I would suggest the following improvements to the already great answer of James McNellis:

template <typename Enumeration>
constexpr auto as_integer(Enumeration const value)
    -> typename std::underlying_type<Enumeration>::type
{
    static_assert(std::is_enum<Enumeration>::value, "parameter is not of type enum or enum class");
    return static_cast<typename std::underlying_type<Enumeration>::type>(value);
}

with

  • constexpr: allowing me to use an enum member value as compile-time array size
  • static_assert+is_enum: to 'ensure' compile-time that the function does sth. with enumerations only, as suggested

By the way I'm asking myself: Why should I ever use enum class when I would like to assign number values to my enum members?! Considering the conversion effort.

Perhaps I would then go back to ordinary enum as I suggested here: How to use enums as flags in C++?


Yet another (better) flavor of it without static_assert, based on a suggestion of @TobySpeight:

template <typename Enumeration>
constexpr std::enable_if_t<std::is_enum<Enumeration>::value,
std::underlying_type_t<Enumeration>> as_number(const Enumeration value)
{
    return static_cast<std::underlying_type_t<Enumeration>>(value);
}

How to provide password to a command that prompts for one in bash?

How to use autoexpect to pipe a password into a command:

These steps are illustrated with an Ubuntu 12.10 desktop. The exact commands for your distribution may be slightly different.

This is dangerous because you risk exposing whatever password you use to anyone who can read the autoexpect script file.

DO NOT expose your root password or power user passwords by piping them through expect like this. Root kits WILL find this in an instant and your box is owned.

EXPECT spawns a process, reads text that comes in then sends text predefined in the script file.

  1. Make sure you have expect and autoexpect installed:

    sudo apt-get install expect
    sudo apt-get install expect-dev
    
  2. Read up on it:

    man expect
    man autoexpect
    
  3. Go to your home directory:

    cd /home/el
    
  4. User el cannot chown a file to root and must enter a password:

    touch testfile.txt
    sudo chown root:root testfile.txt 
       [enter password to authorize the changing of the owner]
    
  5. This is the password entry we want to automate. Restart the terminal to ensure that sudo asks us for the password again. Go to /home/el again and do this:

    touch myfile.txt
    
    autoexpect -f my_test_expect.exp sudo chown root:root myfile.txt
    
        [enter password which authorizes the chown to root]
    
    autoexpect done, file is my_test_expect.exp
    
  6. You have created my_test_expect.exp file. Your super secret password is stored plaintext in this file. This should make you VERY uncomfortable. Mitigate some discomfort by restricting permissions and ownership as much as possible:

    sudo chown el my_test_expect.exp     //make el the owner.
    sudo chmod 700 my_test_expect.exp    //make file only readable by el.
    
  7. You see these sorts of commands at the bottom of my_test_expect.exp:

    set timeout -1
    spawn sudo chown root:root myfile.txt
    match_max 100000
    expect -exact "\[sudo\] password for el: "
    send -- "YourPasswordStoredInPlaintext\r"
    expect eof
    
  8. You will need to verify that the above expect commands are appropriate. If the autoexpect script is being overly sensitive or not sensitive enough then it will hang. In this case it's acceptable because the expect is waiting for text that will always arrive.

  9. Run the expect script as user el:

    expect my_test_expect.exp 
    spawn sudo chown root:root myfile.txt
    [sudo] password for el: 
    
  10. The password contained in my_test_expect.exp was piped into a chown to root by user el. To see if the password was accepted, look at myfile.txt:

    ls -l
    -rw-r--r--  1 root root          0 Dec  2 14:48 myfile.txt
    

It worked because it is root, and el never entered a password. If you expose your root, sudo, or power user password with this script, then acquiring root on your box will be easy. Such is the penalty for a security system that lets everybody in no questions asked.

How to install a specific version of package using Composer?

I tried to require a development branch from a different repository and not the latest version and I had the same issue and non of the above worked for me :(

after a while I saw in the documentation that in cases of dev branch you need to require with a 'dev-' prefix to the version and the following worked perfectly.

composer require [vendorName]/[packageName]:dev-[gitBranchName]

pthread function from a class

This is a bit old question but a very common issue which many face. Following is a simple and elegant way to handle this by using std::thread

#include <iostream>
#include <utility>
#include <thread>
#include <chrono>

class foo
{
    public:
        void bar(int j)
        {
            n = j;
            for (int i = 0; i < 5; ++i) {
                std::cout << "Child thread executing\n";
                ++n;
                std::this_thread::sleep_for(std::chrono::milliseconds(10));
            }
        }
        int n = 0;
};

int main()
{
    int n = 5;
    foo f;
    std::thread class_thread(&foo::bar, &f, n); // t5 runs foo::bar() on object f
    std::this_thread::sleep_for(std::chrono::milliseconds(20));
    std::cout << "Main Thread running as usual";
    class_thread.join();
    std::cout << "Final value of foo::n is " << f.n << '\n';
}

Above code also takes care of passing argument to the thread function.

Refer std::thread document for more details.

Javascript - Regex to validate date format

You can use regular multiple expressions with the use of OR (|) operator.

function validateDate(date){
    var regex=new RegExp("([0-9]{4}[-](0[1-9]|1[0-2])[-]([0-2]{1}[0-9]{1}|3[0-1]{1})|([0-2]{1}[0-9]{1}|3[0-1]{1})[-](0[1-9]|1[0-2])[-][0-9]{4})");
    var dateOk=regex.test(date);
    if(dateOk){
        alert("Ok");
    }else{
        alert("not Ok");
    }
}

Above function can validate YYYY-MM-DD, DD-MM-YYYY date formats. You can simply extend the regular expression to validate any date format. Assume you want to validate YYYY/MM/DD, just replace "[-]" with "[-|/]". This expression can validate dates to 31, months to 12. But leap years and months ends with 30 days are not validated.

onCreateOptionsMenu inside Fragments

try this,

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.menu_sample, menu);
    super.onCreateOptionsMenu(menu,inflater);
}

Finally, in onCreateView method, add this line to make the options appear in your Toolbar

setHasOptionsMenu(true);

Going from MM/DD/YYYY to DD-MMM-YYYY in java

java.time

You should use java.time classes with Java 8 and later. To use java.time, add:

import java.time.* ;

Below is an example, how you can format date.

DateTimeFormatter format = DateTimeFormatter.ofPattern("dd-MMM-yyyy");
String date = "15-Oct-2018";
LocalDate localDate = LocalDate.parse(date, formatter);

System.out.println(localDate); 
System.out.println(formatter.format(localDate));

How do I pass named parameters with Invoke-Command?

-ArgumentList is based on use with scriptblock commands, like:

Invoke-Command -Cn (gc Servers.txt) {param($Debug=$False, $Clear=$False) C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 } -ArgumentList $False,$True

When you call it with a -File it still passes the parameters like a dumb splatted array. I've submitted a feature request to have that added to the command (please vote that up).

So, you have two options:

If you have a script that looked like this, in a network location accessible from the remote machine (note that -Debug is implied because when I use the Parameter attribute, the script gets CmdletBinding implicitly, and thus, all of the common parameters):

param(
   [Parameter(Position=0)]
   $one
,
   [Parameter(Position=1)]
   $two
,
   [Parameter()]
   [Switch]$Clear
)

"The test is for '$one' and '$two' ... and we $(if($DebugPreference -ne 'SilentlyContinue'){"will"}else{"won't"}) run in debug mode, and we $(if($Clear){"will"}else{"won't"}) clear the logs after."

Without getting hung up on the meaning of $Clear ... if you wanted to invoke that you could use either of the following Invoke-Command syntaxes:

icm -cn (gc Servers.txt) { 
    param($one,$two,$Debug=$False,$Clear=$False)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 @PSBoundParameters
} -ArgumentList "uno", "dos", $false, $true

In that one, I'm duplicating ALL the parameters I care about in the scriptblock so I can pass values. If I can hard-code them (which is what I actually did), there's no need to do that and use PSBoundParameters, I can just pass the ones I need to. In the second example below I'm going to pass the $Clear one, just to demonstrate how to pass switch parameters:

icm -cn $Env:ComputerName { 
    param([bool]$Clear)
    C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $(Test-Path $Profile)

The other option

If the script is on your local machine, and you don't want to change the parameters to be positional, or you want to specify parameters that are common parameters (so you can't control them) you will want to get the content of that script and embed it in your scriptblock:

$script = [scriptblock]::create( @"
param(`$one,`$two,`$Debug=`$False,`$Clear=`$False)
&{ $(Get-Content C:\Scripts\ArchiveEventLogs\ver5\ArchiveEventLogs.ps1 -delimiter ([char]0)) } @PSBoundParameters
"@ )

Invoke-Command -Script $script -Args "uno", "dos", $false, $true

PostScript:

If you really need to pass in a variable for the script name, what you'd do will depend on whether the variable is defined locally or remotely. In general, if you have a variable $Script or an environment variable $Env:Script with the name of a script, you can execute it with the call operator (&): &$Script or &$Env:Script

If it's an environment variable that's already defined on the remote computer, that's all there is to it. If it's a local variable, then you'll have to pass it to the remote script block:

Invoke-Command -cn $Env:ComputerName { 
    param([String]$Script, [bool]$Clear)
    & $ScriptPath "uno" "dos" -Debug -Clear:$Clear
} -ArgumentList $ScriptPath, (Test-Path $Profile)

Is it possible to display my iPhone on my computer monitor?

The latest SDKs (beginning with 2.2, I believe), include TV-Out functionality. With a special cable connected to the iPhone dock connector, a program can send RCA signals representing its current screen contents through the iPhone->RCA cable. If you have a TV Tuner for your computer (i.e. I have an EyeTV Hybrid) with RCA inputs, you can display the screen contents of your iPhone directly in the TV viewer.

CSS 3 slide-in from left transition

USE THIS FOR RIGHT TO LEFT SLIDING :

HTML:

   <div class="nav ">
       <ul>
        <li><a href="#">HOME</a></li>
        <li><a href="#">ABOUT</a></li>
        <li><a href="#">SERVICES</a></li>
        <li><a href="#">CONTACT</a></li>
       </ul>
   </div>

CSS:

/*nav*/
.nav{
    position: fixed;
    right:0;
    top: 70px;
    width: 250px;
    height: calc(100vh - 70px);
    background-color: #333;
    transform: translateX(100%);
    transition: transform 0.3s ease-in-out;

}
.nav-view{
    transform: translateX(0);
}
.nav ul{
    margin: 0;
    padding: 0;
}
.nav ul li{
    margin: 0;
    padding: 0;
    list-style-type: none;
}
.nav ul li a{
    color: #fff;
    display: block;
    padding: 10px;
    border-bottom: solid 1px rgba(255,255,255,0.4);
    text-decoration: none;
}

JS:

  $(document).ready(function(){
  $('a#click-a').click(function(){
    $('.nav').toggleClass('nav-view');
  });
});

How can I add "href" attribute to a link dynamically using JavaScript?

var a = document.getElementById('yourlinkId'); //or grab it by tagname etc
a.href = "somelink url"

jquery remove "selected" attribute of option?

The question is asked in a misleading manner. "Removing the selected attribute" and "deselecting all options" are entirely different things.

To deselect all options in a documented, cross-browser manner use either

$("select").val([]);

or

// Note the use of .prop instead of .attr
$("select option").prop("selected", false);

Netbeans how to set command line arguments in Java

In NetBeans IDE 8.0 you can use a community contributed plugin https://github.com/tusharvjoshi/nbrunwithargs which will allow you to pass arguments while Run Project or Run Single File command.

For passing arguments to Run Project command either you have to set the arguments in the Project properties Run panel, or use the new command available after installing the plugin which says Run with Arguments

For passing command line arguments to a Java file having main method, just right click on the method and choose Run with Arguments command, of this plugin

UPDATE (24 mar 2014) This plugin is now available in NetBeans Plugin Portal that means it can be installed from Plugins dialog box from the available plugins shown from community contributed plugins, in NetBeans IDE 8.0

Run with Arguments plugin as shown in Plugin dialog box

Remove all values within one list from another list?

I was looking for fast way to do the subject, so I made some experiments with suggested ways. And I was surprised by results, so I want to share it with you.

Experiments were done using pythonbenchmark tool and with

a = range(1,50000) # Source list
b = range(1,15000) # Items to remove

Results:

 def comprehension(a, b):
     return [x for x in a if x not in b]

5 tries, average time 12.8 sec

def filter_function(a, b):
    return filter(lambda x: x not in b, a)

5 tries, average time 12.6 sec

def modification(a,b):
    for x in b:
        try:
            a.remove(x)
        except ValueError:
            pass
    return a

5 tries, average time 0.27 sec

def set_approach(a,b):
    return list(set(a)-set(b))

5 tries, average time 0.0057 sec

Also I made another measurement with bigger inputs size for the last two functions

a = range(1,500000)
b = range(1,100000)

And the results:

For modification (remove method) - average time is 252 seconds For set approach - average time is 0.75 seconds

So you can see that approach with sets is significantly faster than others. Yes, it doesn't keep similar items, but if you don't need it - it's for you. And there is almost no difference between list comprehension and using filter function. Using 'remove' is ~50 times faster, but it modifies source list. And the best choice is using sets - it's more than 1000 times faster than list comprehension!

The transaction log for database is full. To find out why space in the log cannot be reused, see the log_reuse_wait_desc column in sys.databases

As an aside, it is always a good practice (and possibly a solution for this type of issue) to delete a large number of rows by using batches:

WHILE EXISTS (SELECT 1 
              FROM   YourTable 
              WHERE  <yourCondition>) 
  DELETE TOP(10000) FROM YourTable 
  WHERE  <yourCondition>

How to print the contents of RDD?

The map function is a transformation, which means that Spark will not actually evaluate your RDD until you run an action on it.

To print it, you can use foreach (which is an action):

linesWithSessionId.foreach(println)

To write it to disk you can use one of the saveAs... functions (still actions) from the RDD API

What is the "continue" keyword and how does it work in Java?

"continue" in Java means go to end of the current loop, means: if the compiler sees continue in a loop it will go to the next iteration

Example: This is a code to print the odd numbers from 1 to 10

the compiler will ignore the print code whenever it sees continue moving into the next iteration

for (int i = 0; i < 10; i++) { 
    if (i%2 == 0) continue;    
    System.out.println(i+"");
}

Getting query parameters from react-router hash fragment

"react-router-dom": "^5.0.0",

you do not need to add any additional module, just in your component that has a url address like this:

http://localhost:3000/#/?authority'

you can try the following simple code:

    const search =this.props.location.search;
    const params = new URLSearchParams(search);
    const authority = params.get('authority'); //

install cx_oracle for python

This worked for me

python -m pip install cx_Oracle --upgrade

For details refer to the oracle quick start guide

https://cx-oracle.readthedocs.io/en/latest/installation.html#quick-start-cx-oracle-installation

how to do bitwise exclusive or of two strings in python?

If you want to operate on bytes or words then you'll be better to use Python's array type instead of a string. If you are working with fixed length blocks then you may be able to use H or L format to operate on words rather than bytes, but I just used 'B' for this example:

>>> import array
>>> a1 = array.array('B', 'Hello, World!')
>>> a1
array('B', [72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33])
>>> a2 = array.array('B', ('secret'*3))
>>> for i in range(len(a1)):
    a1[i] ^= a2[i]


>>> a1.tostring()
';\x00\x0f\x1e\nXS2\x0c\x00\t\x10R'

How to convert seconds to time format?

Sorry this is too late but maybe useful

function mediaTimeDeFormater($seconds)
{
    if (!is_numeric($seconds))
        throw new Exception("Invalid Parameter Type!");


    $ret = "";

    $hours = (string )floor($seconds / 3600);
    $secs = (string )$seconds % 60;
    $mins = (string )floor(($seconds - ($hours * 3600)) / 60);

    if (strlen($hours) == 1)
        $hours = "0" . $hours;
    if (strlen($secs) == 1)
        $secs = "0" . $secs;
    if (strlen($mins) == 1)
        $mins = "0" . $mins;

    if ($hours == 0)
        $ret = "$mins:$secs";
    else
        $ret = "$hours:$mins:$secs";

    return $ret;
}

echo mediaTimeDeFormater(216.064000);//3:36

SQL Server insert if not exists best practice

Don't know why anyone else hasn't said this yet;

NORMALISE.

You've got a table that models competitions? Competitions are made up of Competitors? You need a distinct list of Competitors in one or more Competitions......

You should have the following tables.....

CREATE TABLE Competitor (
    [CompetitorID] INT IDENTITY(1,1) PRIMARY KEY
    , [CompetitorName] NVARCHAR(255)
    )

CREATE TABLE Competition (
    [CompetitionID] INT IDENTITY(1,1) PRIMARY KEY
    , [CompetitionName] NVARCHAR(255)
    )

CREATE TABLE CompetitionCompetitors (
    [CompetitionID] INT
    , [CompetitorID] INT
    , [Score] INT

    , PRIMARY KEY (
        [CompetitionID]
        , [CompetitorID]
        )
    )

With Constraints on CompetitionCompetitors.CompetitionID and CompetitorID pointing at the other tables.

With this kind of table structure -- your keys are all simple INTS -- there doesn't seem to be a good NATURAL KEY that would fit the model so I think a SURROGATE KEY is a good fit here.

So if you had this then to get the the distinct list of competitors in a particular competition you can issue a query like this:

DECLARE @CompetitionName VARCHAR(50) SET @CompetitionName = 'London Marathon'

    SELECT
        p.[CompetitorName] AS [CompetitorName]
    FROM
        Competitor AS p
    WHERE
        EXISTS (
            SELECT 1
            FROM
                CompetitionCompetitor AS cc
                JOIN Competition AS c ON c.[ID] = cc.[CompetitionID]
            WHERE
                cc.[CompetitorID] = p.[CompetitorID]
                AND cc.[CompetitionName] = @CompetitionNAme
        )

And if you wanted the score for each competition a competitor is in:

SELECT
    p.[CompetitorName]
    , c.[CompetitionName]
    , cc.[Score]
FROM
    Competitor AS p
    JOIN CompetitionCompetitor AS cc ON cc.[CompetitorID] = p.[CompetitorID]
    JOIN Competition AS c ON c.[ID] = cc.[CompetitionID]

And when you have a new competition with new competitors then you simply check which ones already exist in the Competitors table. If they already exist then you don't insert into Competitor for those Competitors and do insert for the new ones.

Then you insert the new Competition in Competition and finally you just make all the links in CompetitionCompetitors.

Send JSON via POST in C# and Receive the JSON returned?

You can build your HttpContent using the combination of JObject to avoid and JProperty and then call ToString() on it when building the StringContent:

        /*{
          "agent": {                             
            "name": "Agent Name",                
            "version": 1                                                          
          },
          "username": "Username",                                   
          "password": "User Password",
          "token": "xxxxxx"
        }*/

        JObject payLoad = new JObject(
            new JProperty("agent", 
                new JObject(
                    new JProperty("name", "Agent Name"),
                    new JProperty("version", 1)
                    ),
                new JProperty("username", "Username"),
                new JProperty("password", "User Password"),
                new JProperty("token", "xxxxxx")    
                )
            );

        using (HttpClient client = new HttpClient())
        {
            var httpContent = new StringContent(payLoad.ToString(), Encoding.UTF8, "application/json");

            using (HttpResponseMessage response = await client.PostAsync(requestUri, httpContent))
            {
                response.EnsureSuccessStatusCode();
                string responseBody = await response.Content.ReadAsStringAsync();
                return JObject.Parse(responseBody);
            }
        }

String's Maximum length in Java - calling length() method

Considering the String class' length method returns an int, the maximum length that would be returned by the method would be Integer.MAX_VALUE, which is 2^31 - 1 (or approximately 2 billion.)

In terms of lengths and indexing of arrays, (such as char[], which is probably the way the internal data representation is implemented for Strings), Chapter 10: Arrays of The Java Language Specification, Java SE 7 Edition says the following:

The variables contained in an array have no names; instead they are referenced by array access expressions that use nonnegative integer index values. These variables are called the components of the array. If an array has n components, we say n is the length of the array; the components of the array are referenced using integer indices from 0 to n - 1, inclusive.

Furthermore, the indexing must be by int values, as mentioned in Section 10.4:

Arrays must be indexed by int values;

Therefore, it appears that the limit is indeed 2^31 - 1, as that is the maximum value for a nonnegative int value.

However, there probably are going to be other limitations, such as the maximum allocatable size for an array.

How to execute function in SQL Server 2008

I have come to this question and the one below several times.

how to call scalar function in sql server 2008

Each time, I try entering the Function using the syntax shown here in SQL Server Management Studio, or SSMS, to see the results, and each time I get the errors.

For me, that is because my result set is in tabular data format. Therefore, to see the results in SSMS, I have to call it like this:

SELECT * FROM dbo.Afisho_rankimin_TABLE(5);

I understand that the author's question involved a scalar function, so this answer is only to help others who come to StackOverflow often when they have a problem with a query (like me).

I hope this helps others.

"detached entity passed to persist error" with JPA/EJB code

I got the answer, I was using:

em.persist(user);

I used merge in place of persist:

em.merge(user);

But no idea, why persist didn't work. :(

EXEC sp_executesql with multiple parameters

maybe this help :

declare 
@statement AS NVARCHAR(MAX)
,@text1 varchar(50)='hello'
,@text2 varchar(50)='world'

set @statement = '
select '''+@text1+''' + '' beautifull '' + ''' + @text2 + ''' 
'
exec sp_executesql @statement;

this is same as below :

select @text1 + ' beautifull ' + @text2

How to display hidden characters by default (ZERO WIDTH SPACE ie. &#8203)

A very simple solution is to search your file(s) for non-ascii characters using a regular expression. This will nicely highlight all the spots where they are found with a border.

Search for [^\x00-\x7F] and check the box for Regex.

The result will look like this (in dark mode):

zero width space made visible

Inserting data to table (mysqli insert)

In mysqli_query(first parameter should be connection,your sql statement) so

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
mysqli_query($connection_name,'INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)');

but best practice is

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
$sql_statement="INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)";
mysqli_query($connection_name,$sql_statement);

Touch move getting stuck Ignored attempt to cancel a touchmove

I had this problem and all I had to do is return true from touchend and the warning went away.

How to override maven property in command line?

See Introduction to the POM

finalName is created as:

<build>
    <finalName>${project.artifactId}-${project.version}</finalName>
</build>

One of the solutions is to add own property:

<properties>
    <finalName>${project.artifactId}-${project.version}</finalName>
</properties>
<build>
    <finalName>${finalName}</finalName>
 </build>

And now try:

mvn -DfinalName=build clean package

How to enable Auto Logon User Authentication for Google Chrome

While moopasta's answer works, it doesn't appear to allow wildcards and there is another (potentially better) option. The Chromium project has some HTTP authentication documentation that is useful but incomplete.

Specifically the option that I found best is to whitelist sites that you would like to allow Chrome to pass authentication information to, you can do this by:

  • Launching Chrome with the auth-server-whitelist command line switch. e.g. --auth-server-whitelist="*example.com,*foobar.com,*baz". Downfall to this approach is that opening links from other programs will launch Chrome without the command line switch.
  • Installing, enabling, and configuring the AuthServerWhitelist/"Authentication server whitelist" Group Policy or Local Group Policy. This seems like the most stable option but takes more work to setup. You can set this up locally, no need to have this remotely deployed.

Those looking to set this up for an enterprise can likely follow the directions for using Group Policy or the Admin console to configure the AuthServerWhitelist policy. Those looking to set this up for one machine only can also follow the Group Policy instructions:

  1. Download and unzip the latest Chrome policy templates
  2. Start > Run > gpedit.msc
  3. Navigate to Local Computer Policy > Computer Configuration > Administrative Templates
  4. Right-click Administrative Templates, and select Add/Remove Templates
  5. Add the windows\adm\en-US\chrome.adm template via the dialog
  6. In Computer Configuration > Administrative Templates > Classic Administrative Templates > Google > Google Chrome > Policies for HTTP Authentication enable and configure Authentication server whitelist
  7. Restart Chrome and navigate to chrome://policy to view active policies

Convert to/from DateTime and Time in Ruby

require 'time'
require 'date'

t = Time.now
d = DateTime.now

dd = DateTime.parse(t.to_s)
tt = Time.parse(d.to_s)

Pip Install not installing into correct directory?

Make sure you pip version matches your python version.

to get your python version use:

python -V

then install the correct pip. You might already have intall in that case try to use:

pip-2.5 install ...

pip-2.7 install ...

or for those of you using macports make sure your version match using.

port select --list pip

then change to the same python version you are using.

sudo port select --set pip pip27

Hope this helps. It work on my end.

Multi-dimensional arraylist or list in C#?

Not exactly. But you can create a list of lists:

var ll = new List<List<int>>();
for(int i = 0; i < 10; ++i) {
    var l = new List<int>();
    ll.Add(l);
}

How to read all rows from huge table?

So it turns out that the crux of the problem is that by default, Postgres starts in "autoCommit" mode, and also it needs/uses cursors to be able to "page" through data (ex: read the first 10K results, then the next, then the next), however cursors can only exist within a transaction. So the default is to read all rows, always, into RAM, and then allow your program to start processing "the first result row, then the second" after it has all arrived, for two reasons, it's not in a transaction (so cursors don't work), and also a fetch size hasn't been set.

So how the psql command line tool achieves batched response (its FETCH_COUNT setting) for queries, is to "wrap" its select queries within a short-term transaction (if a transaction isn't yet open), so that cursors can work. You can do something like that also with JDBC:

  static void readLargeQueryInChunksJdbcWay(Connection conn, String originalQuery, int fetchCount, ConsumerWithException<ResultSet, SQLException> consumer) throws SQLException {
    boolean originalAutoCommit = conn.getAutoCommit();
    if (originalAutoCommit) {
      conn.setAutoCommit(false); // start temp transaction
    }
    try (Statement statement = conn.createStatement()) {
      statement.setFetchSize(fetchCount);
      ResultSet rs = statement.executeQuery(originalQuery);
      while (rs.next()) {
        consumer.accept(rs); // or just do you work here
      }
    } finally {
      if (originalAutoCommit) {
        conn.setAutoCommit(true); // reset it, also ends (commits) temp transaction
      }
    }
  }
  @FunctionalInterface
  public interface ConsumerWithException<T, E extends Exception> {
    void accept(T t) throws E;
  }

This gives the benefit of requiring less RAM, and, in my results, seemed to run overall faster, even if you don't need to save the RAM. Weird. It also gives the benefit that your processing of the first row "starts faster" (since it process it a page at a time).

And here's how to do it the "raw postgres cursor" way, along with full demo code, though in my experiments it seemed the JDBC way, above, was slightly faster for whatever reason.

Another option would be to have autoCommit mode off, everywhere, though you still have to always manually specify a fetchSize for each new Statement (or you can set a default fetch size in the URL string).

jQuery selectors on custom data attributes using HTML5

jQuery UI has a :data() selector which can also be used. It has been around since Version 1.7.0 it seems.

You can use it like this:

Get all elements with a data-company attribute

var companyElements = $("ul:data(group) li:data(company)");

Get all elements where data-company equals Microsoft

var microsoft = $("ul:data(group) li:data(company)")
                    .filter(function () {
                        return $(this).data("company") == "Microsoft";
                    });

Get all elements where data-company does not equal Microsoft

var notMicrosoft = $("ul:data(group) li:data(company)")
                       .filter(function () {
                           return $(this).data("company") != "Microsoft";
                       });

etc...

One caveat of the new :data() selector is that you must set the data value by code for it to be selected. This means that for the above to work, defining the data in HTML is not enough. You must first do this:

$("li").first().data("company", "Microsoft");

This is fine for single page applications where you are likely to use $(...).data("datakey", "value") in this or similar ways.

How do I encode/decode HTML entities in Ruby?

To decode characters in Rails use:

<%= raw '<html>' %>

So,

<%= raw '&lt;br&gt;' %>

would output

<br>

Limit number of characters allowed in form input text field

<input type="text" maxlength="5">

the maximum amount of letters that can be in the input is 5.

How do I find out if a column exists in a VB.Net DataRow

You can use DataSet.Tables(0).Columns.Contains(name) to check whether the DataTable contains a column with a particular name.

How does JavaScript .prototype work?

If you want to understand the concept of prototype and prototype based inheritance from the basics, check the official MDN docs, they explain it pretty well.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

When it comes to inheritance, JavaScript only has one construct: objects. Each object has a private property which holds a link to another object called its prototype. That prototype object has a prototype of its own, and so on until an object is reached with null as its prototype. By definition, null has no prototype, and acts as the final link in this prototype chain.

Also, here's another good resource that explains using simple examples - https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes

How to select the first row for each group in MySQL?

Select the first row for each group (as ordered by a column) in Mysql .

We have:

a table: mytable
a column we are ordering by: the_column_to_order_by
a column that we wish to group by: the_group_by_column

Here's my solution. The inner query gets you a unique set of rows, selected as a dual key. The outer query joins the same table by joining on both of those keys (with AND).

SELECT * FROM 
    ( 
        SELECT the_group_by_column, MAX(the_column_to_order_by) the_column_to_order_by 
        FROM mytable 
        GROUP BY the_group_by_column 
        ORDER BY MAX(the_column_to_order_by) DESC 
    ) as mytable1 
JOIN mytable mytable2 ON mytable2.the_group_by_column = 
mytablealiamytable2.the_group_by_column 
  AND mytable2.the_column_to_order_by = mytable1.the_column_to_order_by;

FYI: I haven't thought about efficiency at all for this and can't speak to that one way or the other.

How to add custom html attributes in JSX

For any custom attributes I use react-any-attr package https://www.npmjs.com/package/react-any-attr

jQuery - Create hidden form element on the fly

function addHidden(theForm, key, value) {
    // Create a hidden input element, and append it to the form:
    var input = document.createElement('input');
    input.type = 'hidden';
    input.name = key; //name-as-seen-at-the-server
    input.value = value;
    theForm.appendChild(input);
}

// Form reference:
var theForm = document.forms['detParameterForm'];

// Add data:
addHidden(theForm, 'key-one', 'value');

Google Play Services Missing in Emulator (Android 4.4.2)

You will not able to test the app using the Google-Play-Service library in emulator. In order to test that app in emulator you need to install some system framework in your emulator to make it work.

https://stackoverflow.com/a/11213598/1405008

Refer the above answer to install Google play service on your emulator.

How do I push to GitHub under a different username?

Go to Credential Manager Go to Windows Credentials Delete the entries under Generic Credentials Try connecting again.

How do I get hour and minutes from NSDate?

Use an NSDateFormatter to convert string1 into an NSDate, then get the required NSDateComponents:

Obj-C:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"<your date format goes here"];
NSDate *date = [dateFormatter dateFromString:string1];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSCalendarUnitHour | NSCalendarUnitMinute) fromDate:date];
NSInteger hour = [components hour];
NSInteger minute = [components minute];

Swift 1 and 2:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "Your date Format"
let date = dateFormatter.dateFromString(string1)
let calendar = NSCalendar.currentCalendar()
let comp = calendar.components([.Hour, .Minute], fromDate: date)
let hour = comp.hour
let minute = comp.minute

Swift 3:

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "Your date Format"
let date = dateFormatter.date(from: string1)
let calendar = Calendar.current
let comp = calendar.dateComponents([.hour, .minute], from: date)
let hour = comp.hour
let minute = comp.minute

More about the dateformat is on the official unicode site

how to make a jquery "$.post" request synchronous

From the Jquery docs: you specify the async option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.

Here's what your code would look like if changed as suggested:

beforecreate: function(node,targetNode,type,to) {
    jQuery.ajax({
         url:    url,
         success: function(result) {
                      if(result.isOk == false)
                          alert(result.message);
                  },
         async:   false
    });          
}

this is because $.ajax is the only request type that you can set the asynchronousity for

How do I parse a string with a decimal point to a double?

The following code does the job in any scenario. It's a little bit parsing.

List<string> inputs = new List<string>()
{
    "1.234.567,89",
    "1 234 567,89",
    "1 234 567.89",
    "1,234,567.89",
    "123456789",
    "1234567,89",
    "1234567.89",
};
string output;

foreach (string input in inputs)
{
    // Unify string (no spaces, only .)
    output = input.Trim().Replace(" ", "").Replace(",", ".");

    // Split it on points
    string[] split = output.Split('.');

    if (split.Count() > 1)
    {
        // Take all parts except last
        output = string.Join("", split.Take(split.Count()-1).ToArray());

        // Combine token parts with last part
        output = string.Format("{0}.{1}", output, split.Last());
    }

    // Parse double invariant
    double d = double.Parse(output, CultureInfo.InvariantCulture);
    Console.WriteLine(d);
}

MySQL Data Source not appearing in Visual Studio

I have faced the same problem and i have installed mysql-connector-net-8.0.11. But in visual studio is not showing the db connector for mysql. Then I was installed the mysql-for-visualstudio-1.2.8 and run the visual studio. Its working fine.

Thank you!

Print text in Oracle SQL Developer SQL Worksheet window

For me, I could only get it to work with

set serveroutput on format word_wrapped;

The wraped and WRAPPED just threw errors: SQLPLUS command failed - not enough arguments

How do I limit the number of returned items?

Find parameters

The parameters find function takes are as follows:

  1. conditions «Object».
  2. [projection] «Object|String» optional fields to return, see Query.prototype.select()
  3. [options] «Object» optional see Query.prototype.setOptions()
  4. [callback] «Function»

How to limit

const Post = require('./models/Post');

Post.find(
  { published: true }, 
  null, 
  { sort: { 'date': 'asc' }, limit: 20 },
  function(error, posts) {
   if (error) return `${error} while finding from post collection`;

   return posts; // posts with sorted length of 20
  }
);

Extra Info

Mongoose allows you to query your collections in different ways like: Official Documentation

// named john and at least 18
MyModel.find({ name: 'john', age: { $gte: 18 }});

// executes, passing results to callback
MyModel.find({ name: 'john', age: { $gte: 18 }}, function (err, docs) {});

// executes, name LIKE john and only selecting the "name" and "friends" fields
MyModel.find({ name: /john/i }, 'name friends', function (err, docs) { })

// passing options
MyModel.find({ name: /john/i }, null, { skip: 10 })

// passing options and executes
MyModel.find({ name: /john/i }, null, { skip: 10 }, function (err, docs) {});

// executing a query explicitly
var query = MyModel.find({ name: /john/i }, null, { skip: 10 })
query.exec(function (err, docs) {});

// using the promise returned from executing a query
var query = MyModel.find({ name: /john/i }, null, { skip: 10 });
var promise = query.exec();
promise.addBack(function (err, docs) {});

Testing pointers for validity (C/C++)

Technically you can override operator new (and delete) and collect information about all allocated memory, so you can have a method to check if heap memory is valid. but:

  1. you still need a way to check if pointer is allocated on stack ()

  2. you will need to define what is 'valid' pointer:

a) memory on that address is allocated

b) memory at that address is start address of object (e.g. address not in the middle of huge array)

c) memory at that address is start address of object of expected type

Bottom line: approach in question is not C++ way, you need to define some rules which ensure that function receives valid pointers.

Vuex - Computed property "name" was assigned to but it has no setter

It should be like this.

In your Component

computed: {
        ...mapGetters({
                nameFromStore: 'name'
            }),
        name: {
           get(){
             return this.nameFromStore
           },
           set(newName){
             return newName
           } 
        }
    }

In your store

export const store = new Vuex.Store({
         state:{
             name : "Stackoverflow"
         },
         getters: {
                 name: (state) => {
                     return state.name;
                 }
         }
}

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

Passing parameter using onclick or a click binding with KnockoutJS

Use a binding, like in this example:

<a href="#new-search" data-bind="click:SearchManager.bind($data,'1')">
  Search Manager
</a>
var ViewModelStructure = function () {
    var self = this;
    this.SearchManager = function (search) {
        console.log(search);
    };
}();

Python+OpenCV: cv2.imwrite

enter image description here enter image description here enter image description here

Alternatively, with MTCNN and OpenCV(other dependencies including TensorFlow also required), you can:

1 Perform face detection(Input an image, output all boxes of detected faces):

from mtcnn.mtcnn import MTCNN
import cv2

face_detector = MTCNN()

img = cv2.imread("Anthony_Hopkins_0001.jpg")
detect_boxes = face_detector.detect_faces(img)
print(detect_boxes)

[{'box': [73, 69, 98, 123], 'confidence': 0.9996458292007446, 'keypoints': {'left_eye': (102, 116), 'right_eye': (150, 114), 'nose': (129, 142), 'mouth_left': (112, 168), 'mouth_right': (146, 167)}}]

2 save all detected faces to separate files:

for i in range(len(detect_boxes)):
    box = detect_boxes[i]["box"]
    face_img = img[box[1]:(box[1] + box[3]), box[0]:(box[0] + box[2])]
    cv2.imwrite("face-{:03d}.jpg".format(i+1), face_img)

3 or Draw rectangles of all detected faces:

for box in detect_boxes:
    box = box["box"]
    pt1 = (box[0], box[1]) # top left
    pt2 = (box[0] + box[2], box[1] + box[3]) # bottom right
    cv2.rectangle(img, pt1, pt2, (0,255,0), 2)
cv2.imwrite("detected-boxes.jpg", img)

How can I export tables to Excel from a webpage

There are practical two ways to do this automaticly while only one solution can be used in all browsers. First of all you should use the open xml specification to build the excel sheet. There are free plugins from Microsoft available that make this format also available for older office versions. The open xml is standard since office 2007. The the two ways are obvious the serverside or the clientside.

The clientside implementation use a new standard of CSS that allow you to store data instead of just the URL to the data. This is a great approach coz you dont need any servercall, just the data and some javascript. The killing downside is that microsoft don't support all parts of it in the current IE (I don't know about IE9) releases. Microsoft restrict the data to be a image but we will need a document. In firefox it works quite fine. For me the IE was the killing point.

The other way is to user a serverside implementation. There should be a lot implementations of open XML for all languages. You just need to grap one. In most cases it will be the simplest way to modify a Viewmodel to result in a Document but for sure you can send all data from Clientside back to server and do the same.

Android Intent Cannot resolve constructor

You may use this:

Intent intent = new Intent(getApplicationContext(), ClassName.class);

How do you decrease navbar height in Bootstrap 3?

The answer above worked fine (MVC5 + Bootstrap 3.0), but the height returned to the default once the navbar button showed up (very small screen). Had to add the below in my .css to fix that as well.

.navbar-header .navbar-toggle {
    margin-top:0px;
    margin-bottom:0px;
    padding-bottom:0px;
}

How to Bulk Insert from XLSX file extension?

you can save the xlsx file as a tab-delimited text file and do

BULK INSERT TableName
        FROM 'C:\SomeDirectory\my table.txt'
            WITH
    (
                FIELDTERMINATOR = '\t',
                ROWTERMINATOR = '\n'
    )
GO

How can I determine the direction of a jQuery scroll event?

Use this to find the scroll direction. This is only to find the direction of the Vertical Scroll. Supports all cross browsers.

    var scrollableElement = document.getElementById('scrollableElement');

    scrollableElement.addEventListener('wheel', findScrollDirectionOtherBrowsers);

    function findScrollDirectionOtherBrowsers(event){
        var delta;

        if (event.wheelDelta){
            delta = event.wheelDelta;
        }else{
            delta = -1 * event.deltaY;
        }

        if (delta < 0){
            console.log("DOWN");
        }else if (delta > 0){
            console.log("UP");
        }

    }

Example

What is the difference between hg forget and hg remove?

'hg forget' is just shorthand for 'hg remove -Af'. From the 'hg remove' help:

...and -Af can be used to remove files from the next revision without deleting them from the working directory.

Bottom line: 'remove' deletes the file from your working copy on disk (unless you uses -Af) and 'forget' doesn't.

How does Zalgo text work?

Zalgo text works because of combining characters. These are special characters that allow to modify character that comes before.

enter image description here

OR

y + ̆ = y̆ which actually is

y + &#x0306; = y&#x0306;

Since you can stack them one atop the other you can produce the following:


y̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆

which actually is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;

The same goes for putting stuff underneath:


y̰̰̰̰̰̰̰̰̰̰̰̰̰̰̰̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆̆



that in fact is:

y&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0306;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;&#x0330;

In Unicode, the main block of combining diacritics for European languages and the International Phonetic Alphabet is U+0300–U+036F.

More about it here

To produce a list of combining diacritical marks you can use the following script (since links keep on dying)

_x000D_
_x000D_
for(var i=768; i<879; i++){console.log(new DOMParser().parseFromString("&#"+i+";", "text/html").documentElement.textContent +"  "+"&#"+i+";");}
_x000D_
_x000D_
_x000D_

Also check em out



Mͣͭͣ̾ Vͣͥͭ͛ͤͮͥͨͥͧ̾

Put icon inside input element in a form

This works for me:

_x000D_
_x000D_
input.valid {_x000D_
   border-color: #28a745;_x000D_
   padding-right: 30px;_x000D_
   background-image: url('https://www.stephenwadechryslerdodgejeep.com/wp-content/plugins/pm-motors-plugin/modules/vehicle_save/images/check.png');_x000D_
   background-repeat: no-repeat;_x000D_
   background-size: 20px 20px;_x000D_
   background-position: right center;_x000D_
}
_x000D_
<form>_x000D_
<label for="name">Name</label>_x000D_
<input class="valid" type="text" name="name" />_x000D_
</form>
_x000D_
_x000D_
_x000D_

Set a cookie to never expire

Set a far future absolute time:

setcookie("CookieName", "CookieValue", 2147483647);

It is better to use an absolute time than calculating it relative to the present as recommended in the accepted answer.

The maximum value compatible with 32 bits systems is:

2147483647 = 2^31 = ~year 2038

Run reg command in cmd (bat file)?

In command line it's better to use REG tool rather than REGEDIT:

REG IMPORT yourfile.reg

REG is designed for console mode, while REGEDIT is for graphical mode. This is why running regedit.exe /S yourfile.reg is a bad idea, since you will not be notified if the there's an error, whereas REG Tool will prompt:

>  REG IMPORT missing_file.reg

ERROR: Error opening the file. There may be a disk or file system error.

>  %windir%\System32\reg.exe /?

REG Operation [Parameter List]

  Operation  [ QUERY   | ADD    | DELETE  | COPY    |
               SAVE    | LOAD   | UNLOAD  | RESTORE |
               COMPARE | EXPORT | IMPORT  | FLAGS ]

Return Code: (Except for REG COMPARE)

  0 - Successful
  1 - Failed

For help on a specific operation type:

  REG Operation /?

Examples:

  REG QUERY /?
  REG ADD /?
  REG DELETE /?
  REG COPY /?
  REG SAVE /?
  REG RESTORE /?
  REG LOAD /?
  REG UNLOAD /?
  REG COMPARE /?
  REG EXPORT /?
  REG IMPORT /?
  REG FLAGS /?

Could not execute menu item (internal error)[Exception] - When changing PHP version from 5.3.1 to 5.2.9

To anyone who is reading this -> don't use php 5.3 anymore, switch to newer versions of php, because php 5.3 is using deprecated functions.

The following is a list of deprecated INI directives. Use of any of these INI directives will cause an E_DEPRECATED error to be thrown at startup, so I advise you to use newer version to develop.

define_syslog_variables
register_globals
register_long_arrays
safe_mode
magic_quotes_gpc
magic_quotes_runtime
magic_quotes_sybase
Comments starting with '#' are now deprecated in .INI files.

Deprecated functions:

call_user_method() (use call_user_func() instead)
call_user_method_array() (use call_user_func_array() instead)
define_syslog_variables()
dl()
ereg() (use preg_match() instead)
ereg_replace() (use preg_replace() instead)
eregi() (use preg_match() with the 'i' modifier instead)
eregi_replace() (use preg_replace() with the 'i' modifier instead)
set_magic_quotes_runtime() and its alias, magic_quotes_runtime()
session_register() (use the $_SESSION superglobal instead)
session_unregister() (use the $_SESSION superglobal instead)
session_is_registered() (use the $_SESSION superglobal instead)
set_socket_blocking() (use stream_set_blocking() instead)
split() (use preg_split() instead)
spliti() (use preg_split() with the 'i' modifier instead)
sql_regcase()
mysql_db_query() (use mysql_select_db() and mysql_query() instead)
mysql_escape_string() (use mysql_real_escape_string() instead)
Passing locale category names as strings is now deprecated. Use the LC_* family of constants instead.
The is_dst parameter to mktime(). Use the new timezone handling functions instead.

Deprecated features:

Assigning the return value of new by reference is now deprecated.
Call-time pass-by-reference is now deprecated.

What is the best way to implement constants in Java?

That's the right way to go.

Generally constants are not kept in separate "Constants" classes because they're not discoverable. If the constant is relevant to the current class, keeping them there helps the next developer.

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

It will be better to Create a New role, then grant execute, select ... etc permissions to this role and finally assign users to this role.

Create role

CREATE ROLE [db_SomeExecutor] 
GO

Grant Permission to this role

GRANT EXECUTE TO db_SomeExecutor
GRANT INSERT  TO db_SomeExecutor

to Add users database>security> > roles > databaseroles>Properties > Add ( bottom right ) you can search AD users and add then

OR

   EXEC sp_addrolemember 'db_SomeExecutor', 'domainName\UserName'

Please refer this post

Oracle SQL query for Date format

if you are using same date format and have select query where date in oracle :

   select count(id) from Table_name where TO_DATE(Column_date)='07-OCT-2015';

To_DATE provided by oracle

Convert string to JSON array

You can do the following:

JSONArray jsonArray = jsnobject.getJSONArray("locations");
    for (int i = 0; i < jsonArray.length(); i++) {
        JSONObject explrObject = jsonArray.getJSONObject(i);
}

Shell script to capture Process ID and kill it if exist

This should kill all processes matching the grep that you are permitted to kill.

-9 means "Kill all processes you can kill".

kill -9 $(ps -ef | grep [s]yncapp | awk '{print $2}')

Get year, month or day from numpy datetime64

Use dates.tolist() to convert to native datetime objects, then simply access year. Example:

>>> dates = np.array(['2010-10-17', '2011-05-13', '2012-01-15'], dtype='datetime64')
>>> [x.year for x in dates.tolist()]
[2010, 2011, 2012]

This is basically the same idea exposed in https://stackoverflow.com/a/35281829/2192272, but using simpler syntax.

Tested with python 3.6 / numpy 1.18.

jQuery if statement to check visibility

You can use .is(':visible') to test if something is visible and .is(':hidden') to test for the opposite:

$('#offers').toggle(!$('#column-left form').is(':visible')); // or:
$('#offers').toggle($('#column-left form').is(':hidden'));

Reference:

Django CSRF check failing with an Ajax POST request

Add this line to your jQuery code:

$.ajaxSetup({
  data: {csrfmiddlewaretoken: '{{ csrf_token }}' },
});

and done.

React: "this" is undefined inside a component function

In my case, for a stateless component that received the ref with forwardRef, I had to do what it is said here https://itnext.io/reusing-the-ref-from-forwardref-with-react-hooks-4ce9df693dd

From this (onClick doesn't have access to the equivalent of 'this')

const Com = forwardRef((props, ref) => {
  return <input ref={ref} onClick={() => {console.log(ref.current} } />
})

To this (it works)

const useCombinedRefs = (...refs) => {
  const targetRef = React.useRef()

  useEffect(() => {
    refs.forEach(ref => {
      if (!ref) return

      if (typeof ref === 'function') ref(targetRef.current)
      else ref.current = targetRef.current
    })
  }, [refs])

  return targetRef
}

const Com = forwardRef((props, ref) => {
  const innerRef = useRef()
  const combinedRef = useCombinedRefs(ref, innerRef)

  return <input ref={combinedRef } onClick={() => {console.log(combinedRef .current} } />
})

How to annotate MYSQL autoincrement field with JPA annotations

Using MySQL, only this approach was working for me:

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;

The other 2 approaches stated by Pascal in his answer were not working for me.

Is it better practice to use String.format over string Concatenation in Java?

Generally, string concatenation should be prefered over String.format. The latter has two main disadvantages:

  1. It does not encode the string to be built in a local manner.
  2. The building process is encoded in a string.

By point 1, I mean that it is not possible to understand what a String.format() call is doing in a single sequential pass. One is forced to go back and forth between the format string and the arguments, while counting the position of the arguments. For short concatenations, this is not much of an issue. In these cases however, string concatenation is less verbose.

By point 2, I mean that the important part of the building process is encoded in the format string (using a DSL). Using strings to represent code has many disadvantages. It is not inherently type-safe, and complicates syntax-highlighting, code analysis, optimization, etc.

Of course, when using tools or frameworks external to the Java language, new factors can come into play.

How do I use modulus for float/double?

fmod is the standard C function for handling floating-point modulus; I imagine your source was saying that Java handles floating-point modulus the same as C's fmod function. In Java you can use the % operator on doubles the same as on integers:

int x = 5 % 3; // x = 2
double y = .5 % .3; // y = .2

How do I make a request using HTTP basic authentication with PHP curl?

Unlike SOAP, REST isn't a standardized protocol so it's a bit difficult to have a "REST Client". However, since most RESTful services use HTTP as their underlying protocol, you should be able to use any HTTP library. In addition to cURL, PHP has these via PEAR:

HTTP_Request2

which replaced

HTTP_Request

A sample of how they do HTTP Basic Auth

// This will set credentials for basic auth
$request = new HTTP_Request2('http://user:[email protected]/secret/');

The also support Digest Auth

// This will set credentials for Digest auth
$request->setAuth('user', 'password', HTTP_Request2::AUTH_DIGEST);

Angular 6 Material mat-select change method removed

The changed it from change to selectionChange.

<mat-select (change)="doSomething($event)">

is now

<mat-select (selectionChange)="doSomething($event)">

https://material.angular.io/components/select/api

How can I initialize an array without knowing it size?

Use LinkedList instead. Than, you can create an array if necessary.

String Resource new line /n not possible?

If you put "\n" in a string in the xml file, it's taken as "\\n"

So , I did :

text = text.Replace("\\\n", "\n");   ( text is taken from resX file) 

And then I get a line jump on the screen

How can I get a resource "Folder" from inside my jar File?

Simple ... use OSGi. In OSGi you can iterate over your Bundle's entries with findEntries and findPaths.

How do I access nested HashMaps in Java?

I hit this discussion while trying to figure out how to get a value from a nested map of unknown depth and it helped me come up with the following solution to my problem. It is overkill for the original question but maybe it will be helpful to someone that finds themselves in a situation where you have less knowledge about the map being searched.

private static Object pullNestedVal(
        Map<Object, Object> vmap,
        Object ... keys) {
    if ((keys.length == 0) || (vmap.size() == 0)) {
        return null;
    } else if (keys.length == 1) {
        return vmap.get(keys[0]);
    }

    Object stageObj = vmap.get(keys[0]);
    if (stageObj instanceof Map) {
        Map<Object, Object> smap = (Map<Object, Object>) stageObj;
        Object[] skeys = Arrays.copyOfRange(keys, 1, keys.length);
        return pullNestedVal(smap, skeys);
    } else {
        return null;
    }
}

Rails - How to use a Helper Inside a Controller

You can use

  • helpers.<helper> in Rails 5+ (or ActionController::Base.helpers.<helper>)
  • view_context.<helper> (Rails 4 & 3) (WARNING: this instantiates a new view instance per call)
  • @template.<helper> (Rails 2)
  • include helper in a singleton class and then singleton.helper
  • include the helper in the controller (WARNING: will make all helper methods into controller actions)

What are libtool's .la file for?

According to http://blog.flameeyes.eu/2008/04/14/what-about-those-la-files, they're needed to handle dependencies. But using pkg-config may be a better option:

In a perfect world, every static library needing dependencies would have its own .pc file for pkg-config, and every package trying to statically link to that library would be using pkg-config --static to get the libraries to link to.

What is Ruby's double-colon `::`?

Surprisingly, all 10 answers here say the same thing. The '::' is a namespace resolution operator, and yes it is true. But there is one gotcha that you have to realize about the namespace resolution operator when it comes to the constant lookup algorithm. As Matz delineates in his book, 'The Ruby Programming Language', constant lookup has multiple steps. First, it searches a constant in the lexical scope where the constant is referenced. If it does not find the constant within the lexical scope, it then searches the inheritance hierarchy. Because of this constant lookup algorithm, below we get the expected results:

module A
  module B
      PI = 3.14
      module C
        class E
          PI = 3.15
        end
        class F < E
          def get_pi
            puts PI
          end
        end
      end
  end
end
f = A::B::C::F.new
f.get_pi
> 3.14

While F inherits from E, the B module is within the lexical scope of F. Consequently, F instances will refer to the constant PI defined in the module B. Now if module B did not define PI, then F instances will refer to the PI constant defined in the superclass E.

But what if we were to use '::' rather than nesting modules? Would we get the same result? No!

By using the namespace resolution operator when defining nested modules, the nested modules and classes are no longer within the lexical scope of their outer modules. As you can see below, PI defined in A::B is not in the lexical scope of A::B::C::D and thus we get uninitialized constant when trying to refer to PI in the get_pi instance method:

module A
end

module A::B
  PI = 3.14
end

module A::B::C
  class D
    def get_pi
      puts PI
    end
  end
end
d = A::B::C::D.new
d.get_pi
NameError: uninitialized constant A::B::C::D::PI
Did you mean?  A::B::PI

How can I link to a specific glibc version?

In my opinion, the laziest solution (especially if you don't rely on latest bleeding edge C/C++ features, or latest compiler features) wasn't mentioned yet, so here it is:

Just build on the system with the oldest GLIBC you still want to support.

This is actually pretty easy to do nowadays with technologies like chroot, or KVM/Virtualbox, or docker, even if you don't really want to use such an old distro directly on any pc. In detail, to make a maximum portable binary of your software I recommend following these steps:

  1. Just pick your poison of sandbox/virtualization/... whatever, and use it to get yourself a virtual older Ubuntu LTS and compile with the gcc/g++ it has in there by default. That automatically limits your GLIBC to the one available in that environment.

  2. Avoid depending on external libs outside of foundational ones: like, you should dynamically link ground-level system stuff like glibc, libGL, libxcb/X11/wayland things, libasound/libpulseaudio, possibly GTK+ if you use that, but otherwise preferrably statically link external libs/ship them along if you can. Especially mostly self-contained libs like image loaders, multimedia decoders, etc can cause less breakage on other distros (breakage can be caused e.g. if only present somewhere in a different major version) if you statically ship them.

With that approach you get an old-GLIBC-compatible binary without any manual symbol tweaks, without doing a fully static binary (that may break for more complex programs because glibc hates that, and which may cause licensing issues for you), and without setting up any custom toolchain, any custom glibc copy, or whatever.

How to pass arguments to entrypoint in docker-compose.yml

Whatever is specified in the command in docker-compose.yml should get appended to the entrypoint defined in the Dockerfile, provided entrypoint is defined in exec form in the Dockerfile.

If the EntryPoint is defined in shell form, then any CMD arguments will be ignored.

How to print to console when using Qt

If you are printing to stderr using the stdio library, a call to fflush(stderr) should flush the buffer and get you real-time logging.

HtmlEncode from Class Library

In case you are working with silverlight, use this:

System.Windows.Browser.HttpUtility.HtmlEncode(...);

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

PHPDoc type hinting for array of objects?

I know I'm late to the party, but I've been working on this problem recently. I hope someone sees this because the accepted answer, although correct, is not the best way you can do this. Not in PHPStorm at least, I haven't tested NetBeans though.

The best way involves extending the ArrayIterator class rather than using native array types. This allows you to type hint at a class-level rather than at an instance-level, meaning you only have to PHPDoc once, not throughout your code (which is not only messy and violates DRY, but can also be problematic when it comes to refactoring - PHPStorm has a habit of missing PHPDoc when refactoring)

See code below:

class MyObj
{
    private $val;
    public function __construct($val) { $this->val = $val; }
    public function getter() { return $this->val; }
}

/**
 * @method MyObj current()
 */
class MyObjCollection extends ArrayIterator
{
    public function __construct(Array $array = [])
    {
        foreach($array as $object)
        {
            if(!is_a($object, MyObj::class))
            {
                throw new Exception('Invalid object passed to ' . __METHOD__ . ', expected type ' . MyObj::class);
            }
        }
        parent::__construct($array);
    }

    public function echoContents()
    {
        foreach($this as $key => $myObj)
        {
            echo $key . ': ' . $myObj->getter() . '<br>';
        }
    }
}

$myObjCollection = new MyObjCollection([
    new MyObj(1),
    new MyObj('foo'),
    new MyObj('blah'),
    new MyObj(23),
    new MyObj(array())
]);

$myObjCollection->echoContents();

The key here is the PHPDoc @method MyObj current() overriding the return type inherited from ArrayIterator (which is mixed). The inclusion of this PHPDoc means that when we iterate over the class properties using foreach($this as $myObj), we then get code completion when referring to the variable $myObj->...

To me, this is the neatest way to achieve this (at least until PHP introduces Typed Arrays, if they ever do), as we're declaring the iterator type in the iterable class, not on instances of the class scattered throughout the code.

I haven't shown here the complete solution for extending ArrayIterator, so if you use this technique, you may also want to:

  • Include other class-level PHPDoc as required, for methods such as offsetGet($index) and next()
  • Move the sanity check is_a($object, MyObj::class) from the constructor into a private method
  • Call this (now private) sanity check from method overrides such as offsetSet($index, $newval) and append($value)

How do I get the YouTube video ID from a URL?

I have summed up all the suggestions and here is the universal and short answer to this question:

if(url.match('http://(www.)?youtube|youtu\.be')){
    youtube_id=url.split(/v\/|v=|youtu\.be\//)[1].split(/[?&]/)[0];
}

MySQL Multiple Where Clause

select unique red24.image_id from 
( 
    select image_id from `list` where style_id = 24 and style_value = 'red' 
) red24
inner join 
( 
    select image_id from `list` where style_id = 25 and style_value = 'big' 
) big25
on red24.image_id = big25.image_id
inner join 
( 
    select image_id from `list` where style_id = 27 and style_value = 'round' 
) round27
on red24.image_id = round27.image_id

Invoking a jQuery function after .each() has completed

I found a lot of responses dealing with arrays but not with a json object. My solution was simply to iterate through the object once while incrementing a counter and then when iterating through the object to perform your code you can increment a second counter. Then you simply compare the two counters together and get your solution. I know it's a little clunky but I haven't found a more elegant solution so far. This is my example code:

var flag1 = flag2 = 0;

$.each( object, function ( i, v ) { flag1++; });

$.each( object, function ( ky, val ) {

     /*
        Your code here
     */
     flag2++;
});

if(flag1 === flag2) {
   your function to call at the end of the iteration
}

Like I said, it's not the most elegant, but it works and it works well and I haven't found a better solution just yet.

Cheers, JP

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

I used to meet the similar problem because 'localhost' was not available on server when it restarted network service, e.g. 'ifdown -a' but followed by only 'ifup -eo1'. Besides server is not listening to the port, you can also check 'localhost' is available or not.

ps: Post it just hope someone who has the similar problem may benefit.

Why can't I change my input value in React even with the onChange listener

Unlike in the case of Angular, in React.js you need to update the state manually. You can do something like this:

<input
    className="form-control"
    type="text" value={this.state.name}
    id={'todoName' + this.props.id}
    onChange={e => this.onTodoChange(e.target.value)}
/>

And then in the function:

onTodoChange(value){
        this.setState({
             name: value
        });
    }

Also, you can set the initial state in the constructor of the component:

  constructor (props) {
    super(props);
    this.state = {
        updatable: false,
        name: props.name,
        status: props.status
    };
  }

java.net.BindException: Address already in use: JVM_Bind <null>:80

I deleted my server and added it back. IT happened because I shut down the eclipse manually via task manager and it did not shut down the tomcat.

Function for 'does matrix contain value X?'

Many ways to do this. ismember is the first that comes to mind, since it is a set membership action you wish to take. Thus

X = primes(20);
ismember([15 17],X)
ans =
      0    1

Since 15 is not prime, but 17 is, ismember has done its job well here.

Of course, find (or any) will also work. But these are not vectorized in the sense that ismember was. We can test to see if 15 is in the set represented by X, but to test both of those numbers will take a loop, or successive tests.

~isempty(find(X == 15))
~isempty(find(X == 17))

or,

any(X == 15)
any(X == 17)

Finally, I would point out that tests for exact values are dangerous if the numbers may be true floats. Tests against integer values as I have shown are easy. But tests against floating point numbers should usually employ a tolerance.

tol = 10*eps;
any(abs(X - 3.1415926535897932384) <= tol)

Round double value to 2 decimal places

You could do this:

NSNumberFormatter* f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
[f setFormat:@0.00"];

// test
NSNumber* a = @12;
NSString* s = [f stringFromNumber:a];
NSLog(@"%@", s);

Javascript - Get Image height

...but... wouldn't it be better to adjust the image size on the server side rather than transmitting the bytes to the browser and doing it there?

When I say adjust the image size, I don't mean set the height and width in the HTML image tag. If you do that, you are still shipping a large number of bytes from server to client. I mean, actually manipulate the image itself server side.

I have .NET C# code here that takes that approach, but there must be a php way to do it too: http://ifdefined.com/www/gallery.html

Also, by doing it server side, that opens up the possibility of doing the adjustment just once and then saving the adjusted image, which would be very fast.

How to get the total number of rows of a GROUP BY query?

Here is the solution for you

$sql="SELECT count(*) FROM [tablename] WHERE key == ? ";
$sth = $this->db->prepare($sql);
$sth->execute(array($key));
$rows = $sth->fetch(PDO::FETCH_NUM);
echo $rows[0];

Get the name of a pandas DataFrame

Sometimes df.name doesn't work.

you might get an error message:

'DataFrame' object has no attribute 'name'

try the below function:

def get_df_name(df):
    name =[x for x in globals() if globals()[x] is df][0]
    return name

Excel: macro to export worksheet as CSV file without leaving my current Excel sheet

As per my comment on @neves post, I slightly improved this by adding the xlPasteFormats as well as values part so dates go across as dates - I mostly save as CSV for bank statements, so needed dates.

Sub ExportAsCSV()

    Dim MyFileName As String
    Dim CurrentWB As Workbook, TempWB As Workbook

    Set CurrentWB = ActiveWorkbook
    ActiveWorkbook.ActiveSheet.UsedRange.Copy

    Set TempWB = Application.Workbooks.Add(1)
    With TempWB.Sheets(1).Range("A1")
        .PasteSpecial xlPasteValues
        .PasteSpecial xlPasteFormats
    End With

    'Dim Change below to "- 4"  to become compatible with .xls files
    MyFileName = CurrentWB.Path & "\" & Left(CurrentWB.Name, Len(CurrentWB.Name) - 5) & ".csv"

    Application.DisplayAlerts = False
    TempWB.SaveAs Filename:=MyFileName, FileFormat:=xlCSV, CreateBackup:=False, Local:=True
    TempWB.Close SaveChanges:=False
    Application.DisplayAlerts = True
End Sub

PHP/regex: How to get the string value of HTML tag?

Your HTML

$html='<ul id="main">
    <li>
        <h1><a href="[link]">My Title</a></h1>
        <span class="date">Date</span>
        <div class="section">
            [content]
        </div>
    </li>
</ul>';

//function call you can change the tag name

echo contentBetweenTags($html,"span");

// this function will help you to fetch the data from a specific tag

function contentBetweenTags($content, $tagname){
    $pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
    preg_match($pattern, $content, $matches);
    
    if(empty($matches))
        return;
    
    $str = "<$tagname>".html_entity_decode($matches[1])."</$tagname>";
    return $str;
}

django no such table:

sqlall just prints the SQL, it doesn't execute it. syncdb will create tables that aren't already created, but it won't modify existing tables.

How to calculate the intersection of two sets?

Yes there is retainAll check out this

Set<Type> intersection = new HashSet<Type>(s1);
intersection.retainAll(s2);

keyword not supported data source

I had this problem when I started using Entity Framework, it happened when I did not change the old SQL server connection to EntityFrameWork connection.

Solution: in the file where connection is made through web.config file "add name="Entities" connectionString=XYZ", make sure you are referring to the correct connection, in my case I had to do this

        public static string MyEntityFrameworkConnection
    {
        get
        {
             return ConfigurationManager.ConnectionStrings["Entities"].ConnectionString;
        }

    }

call MyEntityFrameworkConnection whenever connection need to be established.

private string strConnection= Library.DataAccessLayer.DBfile.AdoSomething.MyEntityFrameworkConnection;

note: the connection in web.config file will be generated automatically when adding Entity model to the solution.

Prevent PDF file from downloading and printing

(disclaimer - I work for Atalasoft)

If you present your PDF documents with the Atalasoft web image viewer, you can prevent the PDF from being downloaded. You could also control printing from javascript on the client side.

How do I send a POST request with PHP?

I'd like to add some thoughts about the curl-based answer of Fred Tanrikut. I know most of them are already written in the answers above, but I think it is a good idea to show an answer that includes all of them together.

Here is the class I wrote to make HTTP-GET/POST/PUT/DELETE requests based on curl, concerning just about the response body:

class HTTPRequester {
    /**
     * @description Make HTTP-GET call
     * @param       $url
     * @param       array $params
     * @return      HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPGet($url, array $params) {
        $query = http_build_query($params); 
        $ch    = curl_init($url.'?'.$query);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
    /**
     * @description Make HTTP-POST call
     * @param       $url
     * @param       array $params
     * @return      HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPPost($url, array $params) {
        $query = http_build_query($params);
        $ch    = curl_init();
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $query);
        $response = curl_exec($ch);
        curl_close($ch);
        return $response;
    }
    /**
     * @description Make HTTP-PUT call
     * @param       $url
     * @param       array $params
     * @return      HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPPut($url, array $params) {
        $query = \http_build_query($params);
        $ch    = \curl_init();
        \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
        \curl_setopt($ch, \CURLOPT_HEADER, false);
        \curl_setopt($ch, \CURLOPT_URL, $url);
        \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'PUT');
        \curl_setopt($ch, \CURLOPT_POSTFIELDS, $query);
        $response = \curl_exec($ch);
        \curl_close($ch);
        return $response;
    }
    /**
     * @category Make HTTP-DELETE call
     * @param    $url
     * @param    array $params
     * @return   HTTP-Response body or an empty string if the request fails or is empty
     */
    public static function HTTPDelete($url, array $params) {
        $query = \http_build_query($params);
        $ch    = \curl_init();
        \curl_setopt($ch, \CURLOPT_RETURNTRANSFER, true);
        \curl_setopt($ch, \CURLOPT_HEADER, false);
        \curl_setopt($ch, \CURLOPT_URL, $url);
        \curl_setopt($ch, \CURLOPT_CUSTOMREQUEST, 'DELETE');
        \curl_setopt($ch, \CURLOPT_POSTFIELDS, $query);
        $response = \curl_exec($ch);
        \curl_close($ch);
        return $response;
    }
}

Improvements

  • Using http_build_query to get the query-string out of an request-array.(you could also use the array itself, therefore see: http://php.net/manual/en/function.curl-setopt.php)
  • Returning the response instead of echoing it. Btw you can avoid the returning by removing the line curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);. After that the return value is a boolean(true = request was successful otherwise an error occured) and the response is echoed. See: http://php.net/en/manual/function.curl-exec.php
  • Clean session closing and deletion of the curl-handler by using curl_close. See: http://php.net/manual/en/function.curl-close.php
  • Using boolean values for the curl_setopt function instead of using any number.(I know that any number not equal zero is also considered as true, but the usage of true generates a more readable code, but that's just my opinion)
  • Ability to make HTTP-PUT/DELETE calls(useful for RESTful service testing)

Example of usage

GET

$response = HTTPRequester::HTTPGet("http://localhost/service/foobar.php", array("getParam" => "foobar"));

POST

$response = HTTPRequester::HTTPPost("http://localhost/service/foobar.php", array("postParam" => "foobar"));

PUT

$response = HTTPRequester::HTTPPut("http://localhost/service/foobar.php", array("putParam" => "foobar"));

DELETE

$response = HTTPRequester::HTTPDelete("http://localhost/service/foobar.php", array("deleteParam" => "foobar"));

Testing

You can also make some cool service tests by using this simple class.

class HTTPRequesterCase extends TestCase {
    /**
     * @description test static method HTTPGet
     */
    public function testHTTPGet() {
        $requestArr = array("getLicenses" => 1);
        $url        = "http://localhost/project/req/licenseService.php";
        $this->assertEquals(HTTPRequester::HTTPGet($url, $requestArr), '[{"error":false,"val":["NONE","AGPL","GPLv3"]}]');
    }
    /**
     * @description test static method HTTPPost
     */
    public function testHTTPPost() {
        $requestArr = array("addPerson" => array("foo", "bar"));
        $url        = "http://localhost/project/req/personService.php";
        $this->assertEquals(HTTPRequester::HTTPPost($url, $requestArr), '[{"error":false}]');
    }
    /**
     * @description test static method HTTPPut
     */
    public function testHTTPPut() {
        $requestArr = array("updatePerson" => array("foo", "bar"));
        $url        = "http://localhost/project/req/personService.php";
        $this->assertEquals(HTTPRequester::HTTPPut($url, $requestArr), '[{"error":false}]');
    }
    /**
     * @description test static method HTTPDelete
     */
    public function testHTTPDelete() {
        $requestArr = array("deletePerson" => array("foo", "bar"));
        $url        = "http://localhost/project/req/personService.php";
        $this->assertEquals(HTTPRequester::HTTPDelete($url, $requestArr), '[{"error":false}]');
    }
}

clearing select using jquery

$('option', '#theSelect').remove();

OpenSSL Verify return code: 20 (unable to get local issuer certificate)

With client authentication:

openssl s_client -cert ./client-cert.pem -key ./client-key.key -CApath /etc/ssl/certs/ -connect foo.example.com:443

How to determine day of week by passing specific date?

method below retrieves seven days and return short name of days in List Array in Kotlin though, you can just reformat then in Java format, just presenting idea how Calendar can return short name

private fun getDayDisplayName():List<String>{
        val calendar = Calendar.getInstance()
        val dates= mutableListOf<String>()
        dates.clear()
        val s=   calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US)
        dates.add(s)
        for(i in 0..5){
            calendar.roll( Calendar.DATE, -1)
            dates.add(calendar.getDisplayName(DAY_OF_WEEK, SHORT, Locale.US))
        }
        return dates.toList()
    }

out put results like

I/System.out: Wed
    Tue
    Mon
    Sun
I/System.out: Sat
    Fri
    Thu

How can I return NULL from a generic method in C#?

Another alternative to 2 answers presented above. If you change your return type to object, you can return null, while at the same time cast the non-null return.

static object FindThing<T>(IList collection, int id)
{
    foreach T thing in collecion
    {
        if (thing.Id == id)
            return (T) thing;
    }
    return null;  // allowed now
}

How to override application.properties during production in Spring-Boot?

I know you asked how to do this, but the answer is you should not do this.

Instead, have a application.properties, application-default.properties application-dev.properties etc., and switch profiles via args to the JVM: e.g. -Dspring.profiles.active=dev

You can also override some things at test time using @TestPropertySource

Ideally everything should be in source control so that there are no surprises e.g. How do you know what properties are sitting there in your server location, and which ones are missing? What happens if developers introduce new things?

Spring Boot is already giving you enough ways to do this right.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

How to check if a JavaScript variable is NOT undefined?

var lastname = "Hi";

if(typeof lastname !== "undefined")
{
  alert("Hi. Variable is defined.");
} 

How to delete a remote tag?

Delete local tag '12345'

git tag -d 12345

Delete remote tag '12345' (eg; GitHub version too)

git push origin :refs/tags/12345

alternative approach

git push --delete origin tagName
git tag -d tagName

enter image description here

Setting Column width in Apache POI

With Scala there is a nice Wrapper spoiwo

You can do it like this:

Workbook(mySheet.withColumns(
      Column(autoSized = true),
      Column(width = new Width(100, WidthUnit.Character)),
      Column(width = new Width(100, WidthUnit.Character)))
    )

Set encoding and fileencoding to utf-8 in Vim

You can set the variable 'fileencodings' in your .vimrc.

This is a list of character encodings considered when starting to edit an existing file. When a file is read, Vim tries to use the first mentioned character encoding. If an error is detected, the next one in the list is tried. When an encoding is found that works, 'fileencoding' is set to it. If all fail, 'fileencoding' is set to an empty string, which means the value of 'encoding' is used.

See :help filencodings

If you often work with e.g. cp1252, you can add it there:

set fileencodings=ucs-bom,utf-8,cp1252,default,latin9

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

Maybe try this

Select cust.*

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

How to create a inner border for a box in html?

You may also use box-shadow and add transparency to that dashed border via background-clip to let you see body background.

example

_x000D_
_x000D_
h1 {_x000D_
  text-align: center;_x000D_
  margin: auto;_x000D_
  box-shadow: 0 0 0 5px #1761A2;_x000D_
  border: dashed 3px #1761A2;_x000D_
  background: linear-gradient(#1761A2, #1761A2) no-repeat;_x000D_
  background-clip: border-box;_x000D_
  font-size: 2.5em;_x000D_
  text-shadow: 0 0 2px white, 0 0 2px white, 0 0 2px white, 0 0 2px white, 0 0 2px white;_x000D_
  font-size: 2.5em;_x000D_
  min-width: 12em;_x000D_
}_x000D_
body {_x000D_
  background: linear-gradient(to bottom left, yellow, gray, tomato, purple, lime, yellow, gray, tomato, purple, lime, yellow, gray, tomato, purple, lime);_x000D_
  height: 100vh;_x000D_
  margin: 0;_x000D_
  display: flex;_x000D_
}_x000D_
::first-line {_x000D_
  color: white;_x000D_
  text-transform: uppercase;_x000D_
  font-size: 0.7em;_x000D_
  text-shadow: 0 0_x000D_
}_x000D_
code {_x000D_
  color: tomato;_x000D_
  text-transform: uppercase;_x000D_
  text-shadow: 0 0;_x000D_
}_x000D_
em {_x000D_
  mix-blend-mode: screen;_x000D_
  text-shadow: 0 0 2px white, 0 0 2px white, 0 0 2px white, 0 0 2px white, 0 0 2px white_x000D_
}
_x000D_
<h1>transparent dashed border<br/>_x000D_
  <em>with</em> <code>background-clip</code>_x000D_
</h1>
_x000D_
_x000D_
_x000D_

Pen to play with

render in firefox: screenshot from the snippet

How to give spacing between buttons using bootstrap

Depends on how much space you want. I'm not sure I agree with the logic of adding a "col-XX-1" in between each one, because you are then defining an entire "column" in between each one.

If you just want "a little spacing" in between each button, I like to add padding to the encompassing row. That way, I can still use all 12 columns, while including a "space" in between each button.

Bootply: http://www.bootply.com/ugeXrxpPvD

How can I increase the cursor speed in terminal?

System Preferences => Keyboard => Key Repeat Rate

MySQL SELECT DISTINCT multiple columns

Taking a guess at the results you want so maybe this is the query you want then

SELECT DISTINCT a FROM my_table
UNION 
SELECT DISTINCT b FROM my_table
UNION
SELECT DISTINCT c FROM my_table
UNION
SELECT DISTINCT d FROM my_table

Visual Studio Error: (407: Proxy Authentication Required)

The situation is essentially that VS is not set up to go through a proxy to get to the resources it's trying to get to (when using FTP). This is the cause of the 407 error you're getting. I did some research on this and there are a few things that you can try to get this debugged. Fundamentally this is a bit of a flawed area in the product that is supposed to be reviewed in a later release.

Here are some solutions, in order of less complex to more complex:

  • If possible don't use the proxy for the specified domains that you're trying to get to.
  • Set up your proxy settings correctly Internet Explorer (even if you don't use it) as that affects system wide settings. Even go so far as to connect to the internet with internet explorer and leave it connected then go back and try again from VS.
  • In the devenv.exe.config add <servicePointManager expect100Continue="false" /> as laid out below:
  • <configuration>
      <system.net>
        <settings>
          <servicePointManager expect100Continue="false" />
        </settings>
      </system.net>
    </configuration>
    

  • Add defaultProxy settings as follows:
  • <system.net>
      <defaultProxy useDefaultCredentials="true" enabled="true">
          <proxy proxyaddress="http://your.proxyserver.ip:port"/>
      </defaultProxy>
      <settings>
      ...
    

  • Alternately you could try telling it to use system default (which should pull from internet explorer) like so:

    <defaultProxy useDefaultCredentials="true" enabled="true">
        <proxy usesystemdefault="True" />
    </defaultProxy>
    

  • There is an older solution involving creating a plugin here
  • Hope this solves it for you.

    Laravel csrf token mismatch for ajax POST Request

    In case your session expires, you can use this, to login again

    $(document).ajaxComplete(function(e, xhr, opt){
      if(xhr.status===419){
        if(xhr.responseJSON && xhr.responseJSON.message=='CSRF token mismatch.') window.location.reload();
      }
    });
    

    Generate Controller and Model

    Make resource controller with Model.

    php artisan make:controller PostController --model=Post

    Foreign key constraint may cause cycles or multiple cascade paths?

    I would point out that (functionally) there's a BIG difference between cycles and/or multiple paths in the SCHEMA and the DATA. While cycles and perhaps multipaths in the DATA could certainly complicated processing and cause performance problems (cost of "properly" handling), the cost of these characteristics in the schema should be close to zero.

    Since most apparent cycles in RDBs occur in hierarchical structures (org chart, part, subpart, etc.) it is unfortunate that SQL Server assumes the worst; i.e., schema cycle == data cycle. In fact, if you're using RI constraints you can't actually build a cycle in the data!

    I suspect the multipath problem is similar; i.e., multiple paths in the schema don't necessarily imply multiple paths in the data, but I have less experience with the multipath problem.

    Of course if SQL Server did allow cycles it'd still be subject to a depth of 32, but that's probably adequate for most cases. (Too bad that's not a database setting however!)

    "Instead of Delete" triggers don't work either. The second time a table is visited, the trigger is ignored. So, if you really want to simulate a cascade you'll have to use stored procedures in the presence of cycles. The Instead-of-Delete-Trigger would work for multipath cases however.

    Celko suggests a "better" way to represent hierarchies that doesn't introduce cycles, but there are tradeoffs.

    How to compare datetime with only date in SQL Server

    According to your query Select * from [User] U where U.DateCreated = '2014-02-07'

    SQL Server is comparing exact date and time i.e (comparing 2014-02-07 12:30:47.220 with 2014-02-07 00:00:00.000 for equality). that's why result of comparison is false

    Therefore, While comparing dates you need to consider time also. You can use
    Select * from [User] U where U.DateCreated BETWEEN '2014-02-07' AND '2014-02-08'.

    Compare objects in Angular

    I know it's kinda late answer but I just lost about half an hour debugging cause of this, It might save someone some time.

    BE MINDFUL, If you use angular.equals() on objects that have property obj.$something (property name starts with $) those properties will get ignored in comparison.

    Example:

    var obj1 = {
      $key0: "A",
      key1: "value1",
      key2: "value2",
      key3: {a: "aa", b: "bb"}
    }
    
    var obj2 = {
      $key0: "B"
      key2: "value2",
      key1: "value1",
      key3: {a: "aa", b: "bb"}
    }
    
    angular.equals(obj1, obj2) //<--- would return TRUE (despite it's not true)
    

    How to add checkboxes to JTABLE swing

    1) JTable knows JCheckbox with built-in Boolean TableCellRenderers and TableCellEditor by default, then there is contraproductive declare something about that,

    2) AbstractTableModel should be useful, where is in the JTable required to reduce/restrict/change nested and inherits methods by default implemented in the DefaultTableModel,

    3) consider using DefaultTableModel, (if you are not sure about how to works) instead of AbstractTableModel,

    table_with_BooleanType_column

    could be generated from simple code:

    import javax.swing.*;
    import javax.swing.table.*;
    
    public class TableCheckBox extends JFrame {
    
        private static final long serialVersionUID = 1L;
        private JTable table;
    
        public TableCheckBox() {
            Object[] columnNames = {"Type", "Company", "Shares", "Price", "Boolean"};
            Object[][] data = {
                {"Buy", "IBM", new Integer(1000), new Double(80.50), false},
                {"Sell", "MicroSoft", new Integer(2000), new Double(6.25), true},
                {"Sell", "Apple", new Integer(3000), new Double(7.35), true},
                {"Buy", "Nortel", new Integer(4000), new Double(20.00), false}
            };
            DefaultTableModel model = new DefaultTableModel(data, columnNames);
            table = new JTable(model) {
    
                private static final long serialVersionUID = 1L;
    
                /*@Override
                public Class getColumnClass(int column) {
                return getValueAt(0, column).getClass();
                }*/
                @Override
                public Class getColumnClass(int column) {
                    switch (column) {
                        case 0:
                            return String.class;
                        case 1:
                            return String.class;
                        case 2:
                            return Integer.class;
                        case 3:
                            return Double.class;
                        default:
                            return Boolean.class;
                    }
                }
            };
            table.setPreferredScrollableViewportSize(table.getPreferredSize());
            JScrollPane scrollPane = new JScrollPane(table);
            getContentPane().add(scrollPane);
        }
    
        public static void main(String[] args) {
            SwingUtilities.invokeLater(new Runnable() {
    
                @Override
                public void run() {
                    TableCheckBox frame = new TableCheckBox();
                    frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
                    frame.pack();
                    frame.setLocation(150, 150);
                    frame.setVisible(true);
                }
            });
        }
    }
    

    Adding onClick event dynamically using jQuery

    You can use the click event and call your function or move your logic into the handler:

    $("#bfCaptchaEntry").click(function(){ myFunction(); });
    

    You can use the click event and set your function as the handler:

    $("#bfCaptchaEntry").click(myFunction);
    

    .click()

    Bind an event handler to the "click" JavaScript event, or trigger that event on an element.

    http://api.jquery.com/click/


    You can use the on event bound to "click" and call your function or move your logic into the handler:

    $("#bfCaptchaEntry").on("click", function(){ myFunction(); });
    

    You can use the on event bound to "click" and set your function as the handler:

    $("#bfCaptchaEntry").on("click", myFunction);
    

    .on()

    Attach an event handler function for one or more events to the selected elements.

    http://api.jquery.com/on/

    Error inflating when extending a class

    in my case I added such cyclic resource:

    <drawable name="above_shadow">@drawable/above_shadow</drawable>
    

    then changed to

    <drawable name="some_name">@drawable/other_name</drawable>
    

    and it worked

    Angular ng-if="" with multiple arguments

    It is possible.

    <span ng-if="checked && checked2">
      I'm removed when the checkbox is unchecked.
    </span>
    

    http://plnkr.co/edit/UKNoaaJX5KG3J7AswhLV?p=preview

    jquery - Click event not working for dynamically created button

    the simple and easy way to do that is use on event:

    $('body').on('click','#element',function(){
        //somthing
    });
    

    but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

    <div id='div1'></div>
    

    Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

    var dynamicDiv = jQuery('#div1').clone(true);
    

    Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

    Passing arguments to "make run"

    TL;DR don't try to do this

    $ make run arg
    

    instead create script:

    #! /bin/sh
    # rebuild prog if necessary
    make prog
    # run prog with some arguments
    ./prog "$@"
    

    and do this:

    $ ./buildandrunprog.sh arg
    

    answer to the stated question:

    you can use a variable in the recipe

    run: prog
        ./prog $(var)
    

    then pass a variable assignment as an argument to make

    $ make run var=arg
    

    this will execute ./prog arg.

    but beware of pitfalls. i will elaborate about the pitfalls of this method and other methods further down.


    answer to the assumed intention behind the question:

    the assumption: you want to run prog with some arguments but have it rebuild before running if necessary.

    the answer: create a script which rebuilds if necessary then runs prog with args

    #! /bin/sh
    # rebuild prog if necessary
    make prog
    # run prog with some arguments
    ./prog "$@"
    

    this script makes the intention very clear. it uses make to do what it is good for: building. it uses a shell script to do what it is good for: batch processing.

    plus you can do whatever else you might need with the full flexibility and expressiveness of a shell script without all the caveats of a makefile.

    also the calling syntax is now practically identical:

    $ ./buildandrunprog.sh foo "bar baz"
    

    compare to:

    $ ./prog foo "bar baz"
    

    contrast to

    $ make run var="foo bar\ baz"
    

    background:

    make is not designed to pass arguments to a target. all arguments on the command line are interpreted either as a goal (a.k.a. target), as an option, or as a variable assignment.

    so if you run this:

    $ make run foo --wat var=arg
    

    make will interpret run and foo as goals (targets) to update according to their recipes. --wat as an option for make. and var=arg as a variable assignment.

    for more details see: https://www.gnu.org/software/make/manual/html_node/Goals.html#Goals

    for the terminology see: https://www.gnu.org/software/make/manual/html_node/Rule-Introduction.html#Rule-Introduction


    about the variable assignment method and why i recommend against it

    $ make run var=arg
    

    and the variable in the recipe

    run: prog
        ./prog $(var)
    

    this is the most "correct" and straightforward way to pass arguments to a recipe. but while it can be used to run a program with arguments it is certainly not designed to be used that way. see https://www.gnu.org/software/make/manual/html_node/Overriding.html#Overriding

    in my opinion this has one big disadvantage: what you want to do is run prog with argument arg. but instead of writing:

    $ ./prog arg
    

    you are writing:

    $ make run var=arg
    

    this gets even more awkward when trying to pass multiple arguments or arguments containing spaces:

    $ make run var="foo bar\ baz"
    ./prog foo bar\ baz
    argcount: 2
    arg: foo
    arg: bar baz
    

    compare to:

    $ ./prog foo "bar baz"
    argcount: 2
    arg: foo
    arg: bar baz
    

    for the record this is what my prog looks like:

    #! /bin/sh
    echo "argcount: $#"
    for arg in "$@"; do
      echo "arg: $arg"
    done
    

    also note that you should not put $(var) in quotes in the makefile:

    run: prog
        ./prog "$(var)"
    

    because then prog will always get just one argument:

    $ make run var="foo bar\ baz"
    ./prog "foo bar\ baz"
    argcount: 1
    arg: foo bar\ baz
    

    all this is why i recommend against this route.


    for completeness here are some other methods to "pass arguments to make run".

    method 1:

    run: prog
        ./prog $(filter-out $@, $(MAKECMDGOALS))
    
    %:
        @true
    

    super short explanation: filter out current goal from list of goals. create catch all target (%) which does nothing to silently ignore the other goals.

    method 2:

    ifeq (run, $(firstword $(MAKECMDGOALS)))
      runargs := $(wordlist 2, $(words $(MAKECMDGOALS)), $(MAKECMDGOALS))
      $(eval $(runargs):;@true)
    endif
    
    run:
        ./prog $(runargs)
    

    super short explanation: if the target is run then remove the first goal and create do nothing targets for the remaining goals using eval.

    both will allow you to write something like this

    $ make run arg1 arg2
    

    for deeper explanation study the manual of make: https://www.gnu.org/software/make/manual/html_node/index.html

    problems of method 1:

    • arguments that start with a dash will be interpreted by make and not passed as a goal.

      $ make run --foo --bar
      

      workaround

      $ make run -- --foo --bar
      
    • arguments with an equal sign will be interpreted by make and not passed

      $ make run foo=bar
      

      no workaround

    • arguments with spaces is awkward

      $ make run foo "bar\ baz"
      

      no workaround

    • if an argument happens to be run (equal to the target) it will also be removed

      $ make run foo bar run
      

      will run ./prog foo bar instead of ./prog foo bar run

      workaround possible with method 2

    • if an argument is a legitimate target it will also be run.

      $ make run foo bar clean
      

      will run ./prog foo bar clean but also the recipe for the target clean (assuming it exists).

      workaround possible with method 2

    • when you mistype a legitimate target it will be silently ignored because of the catch all target.

      $ make celan
      

      will just silently ignore celan.

      workaround is to make everything verbose. so you see what happens. but that creates a lot of noise for the legitimate output.

    problems of method 2:

    • if an argument has same name as an existing target then make will print a warning that it is being overwritten.

      no workaround that i know of

    • arguments with an equal sign will still be interpreted by make and not passed

      no workaround

    • arguments with spaces is still awkward

      no workaround

    • arguments with space breaks eval trying to create do nothing targets.

      workaround: create the global catch all target doing nothing as above. with the problem as above that it will again silently ignore mistyped legitimate targets.

    • it uses eval to modify the makefile at runtime. how much worse can you go in terms of readability and debugability and the Principle of least astonishment.

      workaround: don't do this!!1 instead write a shell script that runs make and then runs prog.

    i have only tested using gnu make. other makes may have different behaviour.


    TL;DR don't try to do this

    $ make run arg
    

    instead create script:

    #! /bin/sh
    # rebuild prog if necessary
    make prog
    # run prog with some arguments
    ./prog "$@"
    

    and do this:

    $ ./buildandrunprog.sh arg
    

    How to check which locks are held on a table

    You can also use the built-in sp_who2 stored procedure to get current blocked and blocking processes on a SQL Server instance. Typically you'd run this alongside a SQL Profiler instance to find a blocking process and look at the most recent command that spid issued in profiler.

    Multiple types were found that match the controller named 'Home'

    if you want to resolve it automatically.. you can use the application assambly just add the following code:

     routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
                namespaces: new[] { string.Format("{0}.Controllers", BuildManager.GetGlobalAsaxType().BaseType.Assembly.GetName().Name) }
            );
    

    What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

    in this link i mentioned before on the comment, read this part :

    A "fetch" join allows associations or collections of values to be initialized along with their parent objects using a single select. This is particularly useful in the case of a collection. It effectively overrides the outer join and lazy declarations of the mapping file for associations and collections.

    this "JOIN FETCH" will have it's effect if you have (fetch = FetchType.LAZY) property for a collection inside entity(example bellow).

    And it is only effect the method of "when the query should happen". And you must also know this:

    hibernate have two orthogonal notions : when is the association fetched and how is it fetched. It is important that you do not confuse them. We use fetch to tune performance. We can use lazy to define a contract for what data is always available in any detached instance of a particular class.

    when is the association fetched --> your "FETCH" type

    how is it fetched --> Join/select/Subselect/Batch

    In your case, FETCH will only have it's effect if you have department as a set inside Employee, something like this in the entity:

    @OneToMany(fetch = FetchType.LAZY)
    private Set<Department> department;
    

    when you use

    FROM Employee emp
    JOIN FETCH emp.department dep
    

    you will get emp and emp.dep. when you didnt use fetch you can still get emp.dep but hibernate will processing another select to the database to get that set of department.

    so its just a matter of performance tuning, about you want to get all result(you need it or not) in a single query(eager fetching), or you want to query it latter when you need it(lazy fetching).

    Use eager fetching when you need to get small data with one select(one big query). Or use lazy fetching to query what you need latter(many smaller query).

    use fetch when :

    • no large unneeded collection/set inside that entity you about to get

    • communication from application server to database server too far and need long time

    • you may need that collection latter when you don't have the access to it(outside of the transactional method/class)

    How to open an external file from HTML

    Try formatting the link like this (looks hellish, but it works in Firefox 3 under Vista for me) :

    <a href="file://///SERVER/directory/file.ext">file.ext</a>
    

    How to handle AssertionError in Python and find out which line or statement it occurred on?

    Use the traceback module:

    import sys
    import traceback
    
    try:
        assert True
        assert 7 == 7
        assert 1 == 2
        # many more statements like this
    except AssertionError:
        _, _, tb = sys.exc_info()
        traceback.print_tb(tb) # Fixed format
        tb_info = traceback.extract_tb(tb)
        filename, line, func, text = tb_info[-1]
    
        print('An error occurred on line {} in statement {}'.format(line, text))
        exit(1)
    

    An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

    Check if there is any conflict in your IIS authentication. i.e. you enable the anonymous authentication and ASP.NET impersonation both might cause the error also.

    Closing a Userform with Unload Me doesn't work

    It should also be noted that if you have buttons grouped together on your user form that it can link it to a different button in the group despite the one you intended being clicked.

    How can I login to a website with Python?

    Web page automation ? Definitely "webbot"

    webbot even works web pages which have dynamically changing id and classnames and has more methods and features than selenium or mechanize.

    Here's a snippet :)

    from webbot import Browser 
    web = Browser()
    web.go_to('google.com') 
    web.click('Sign in')
    web.type('[email protected]' , into='Email')
    web.click('NEXT' , tag='span')
    web.type('mypassword' , into='Password' , id='passwordFieldId') # specific selection
    web.click('NEXT' , tag='span') # you are logged in ^_^
    

    The docs are also pretty straight forward and simple to use : https://webbot.readthedocs.io

    How to clear the Entry widget after a button is pressed in Tkinter?

    Simply define a function and set the value of your Combobox to empty/null or whatever you want. Try the following.

    def Reset():
        cmb.set("")
    

    here, cmb is a variable in which you have assigned the Combobox. Now call that function in a button such as,

    btn2 = ttk.Button(root, text="Reset",command=Reset)
    

    Why use getters and setters/accessors?

    I wanted to post a real world example I just finished up:

    background - I hibernate tools to generate the mappings for my database, a database I am changing as I develop. I change the database schema, push the changes and then run hibernate tools to generate the java code. All is well and good until I want to add methods to those mapped entities. If I modify the generated files, they will be overwritten every time I make a change to the database. So I extend the generated classes like this:

    package com.foo.entities.custom
    class User extends com.foo.entities.User{
         public Integer getSomething(){
             return super.getSomething();             
         }
         public void setSomething(Integer something){
             something+=1;
             super.setSomething(something); 
         }
    }
    

    What I did above is override the existing methods on the super class with my new functionality (something+1) without ever touching the base class. Same scenario if you wrote a class a year ago and want to go to version 2 without changing your base classes (testing nightmare). hope that helps.

    What is the difference between include and require in Ruby?

    What's the difference between "include" and "require" in Ruby?

    Answer:

    The include and require methods do very different things.

    The require method does what include does in most other programming languages: run another file. It also tracks what you've required in the past and won't require the same file twice. To run another file without this added functionality, you can use the load method.

    The include method takes all the methods from another module and includes them into the current module. This is a language-level thing as opposed to a file-level thing as with require. The include method is the primary way to "extend" classes with other modules (usually referred to as mix-ins). For example, if your class defines the method "each", you can include the mixin module Enumerable and it can act as a collection. This can be confusing as the include verb is used very differently in other languages.

    Source

    So if you just want to use a module, rather than extend it or do a mix-in, then you'll want to use require.

    Oddly enough, Ruby's require is analogous to C's include, while Ruby's include is almost nothing like C's include.

    Blade if(isset) is not working Laravel

    Use ?? instead or {{ $usersType ?? '' }}

    Cross-browser bookmark/add to favorites JavaScript

    function bookmark(title, url) {
      if (window.sidebar) { 
        // Firefox
        window.sidebar.addPanel(title, url, '');
      } 
      else if (window.opera && window.print) 
      { 
        // Opera
        var elem = document.createElement('a');
        elem.setAttribute('href', url);
        elem.setAttribute('title', title);
        elem.setAttribute('rel', 'sidebar');
        elem.click(); //this.title=document.title;
      } 
      else if (document.all) 
      { 
        // ie
        window.external.AddFavorite(url, title);
      }
    }
    

    I used this & works great in IE, FF, Netscape. Chrome, Opera and safari do not support it!

    Get all Attributes from a HTML element with Javascript/jQuery

    Attributes to Object conversion

    *Requires: lodash

    function getAttributes(element, parseJson=false){
        let results = {}
        for (let i = 0, n = element.attributes.length; i < n; i++){
            let key = element.attributes[i].nodeName.replace('-', '.')
            let value = element.attributes[i].nodeValue
            if(parseJson){
                try{
                    if(_.isString(value))
                    value = JSON.parse(value)
                } catch(e) {}
            }
            _.set(results, key, value)
        }
        return results
    }
    

    This will convert all html attributes to a nested object

    Example HTML: <div custom-nested-path1="value1" custom-nested-path2="value2"></div>

    Result: {custom:{nested:{path1:"value1",path2:"value2"}}}

    If parseJson is set to true json values will be converted to objects

    Ajax Success and Error function failure

    You are sending a post type with data implemented for a get. your form must be the following:

    $.ajax({
    url: url,
    method: "POST",
    data: {data1:"data1",data2:"data2"},
    ...
    

    Cannot install signed apk to device manually, got error "App not installed"

    Kindly uninstall the debug app in the device or just increase the version code to overcome this issues

    Size of character ('a') in C/C++

    As Paul stated, it's because 'a' is an int in C but a char in C++.

    I cover that specific difference between C and C++ in something I wrote a few years ago, at: http://david.tribble.com/text/cdiffs.htm

    Uncaught TypeError: Cannot read property 'value' of undefined

    You code looks like automatically generated from other code - you should check that html elements with id=i1 and i2 and name=username and password exists before processing them.

    MySQL Database won't start in XAMPP Manager-osx

    maybe table innodb error after u reinstal or copy file db try to repair tbl innodb, if table cant be repair try delete db or table

    xamppfiles/var/mysql/your db

    or

    xamppfiles/var/mysql/your db/your table

    change permission folder to open folder database

    before delete backup ur folder database

    javac option to compile all java files under a given directory recursively

    I would advice you to learn using ant, which is very-well suited for this task and is very easy to grasp and well documented.

    You would just have to define a target like this in the build.xml file:

    <target name="compile">
        <javac srcdir="your/source/directory"
               destdir="your/output/directory"
               classpath="xyz.jar" />
    </target>
    

    What is the Swift equivalent to Objective-C's "@synchronized"?

    Using Bryan McLemore answer, I extended it to support objects that throw in a safe manor with the Swift 2.0 defer ability.

    func synchronized( lock:AnyObject, block:() throws -> Void ) rethrows
    {
        objc_sync_enter(lock)
        defer {
            objc_sync_exit(lock)
        }
    
        try block()
    }
    

    How to remove list elements in a for loop in Python?

    As other answers have said, the best way to do this involves making a new list - either iterate over a copy, or construct a list with only the elements you want and assign it back to the same variable. The difference between these depends on your use case, since they affect other variables for the original list differently (or, rather, the first affects them, the second doesn't).

    If a copy isn't an option for some reason, you do have one other option that relies on an understanding of why modifying a list you're iterating breaks. List iteration works by keeping track of an index, incrementing it each time around the loop until it falls off the end of the list. So, if you remove at (or before) the current index, everything from that point until the end shifts one spot to the left. But the iterator doesn't know about this, and effectively skips the next element since it is now at the current index rather than the next one. However, removing things that are after the current index doesn't affect things.

    This implies that if you iterate the list back to front, if you remove an item at the current index, everything to it's right shifts left - but that doesn't matter, since you've already dealt with all the elements to the right of the current position, and you're moving left - the next element to the left is unaffected by the change, and so the iterator gives you the element you expect.

    TL;DR:

    >>> a = list(range(5))
    >>> for b in reversed(a):
        if b == 3:
            a.remove(b)
    >>> a
    [0, 1, 2, 4]
    

    However, making a copy is usually better in terms of making your code easy to read. I only mention this possibility for sake of completeness.

    Are Git forks actually Git clones?

    I think fork is a copy of other repository but with your account modification. for example, if you directly clone other repository locally, the remote object origin is still using the account who you clone from. You can't commit and contribute your code. It is just a pure copy of codes. Otherwise, If you fork a repository, it will clone the repo with the update of your account setting in you github account. And then cloning the repo in the context of your account, you can commit your codes.

    How to remove a file from the index in git?

    git reset HEAD <file> 
    

    for removing a particular file from the index.

    and

    git reset HEAD

    for removing all indexed files.

    Check if boolean is true?

    If you're going to opt for

    if(foo == true)
    

    why not go all the way and do

    if(foo == true == true == true == true == true == true == true == true == true)
    

    Which is the same thing.

    I disagree that if its clearly named (ie: IsSomething) then its ok to not compare to true, but otherwise you should. If its in an if statement obviously it can be compared to true.

    if(monday)
    

    Is just as descriptive as

    if(monday == true)
    

    I also prefer the same standard for not:

    if(!monday)
    

    as opposed to

    if(monday == false)
    

    Bluetooth pairing without user confirmation

    If you are asking if you can pair two devices without the user EVER approving the pairing, no it cannot be done, it is a security feature. If you are paired over Bluetooth there is no need to exchange data over NFC, just exchange data over the Bluetooth link.

    I don't think you can circumvent Bluetooth security by passing an authentication packet over NFC, but I could be wrong.

    How to wrap text using CSS?

    This will work everywhere.

    <body>
      <table style="table-layout:fixed;">
      <tr>
        <td><div style="word-wrap: break-word; width: 100px" > gdfggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg</div></td>
      </tr>
      </table>
     </body>
    

    Load content of a div on another page

    You just need to add a jquery selector after the url.

    See: http://api.jquery.com/load/

    Example straight from the API:

    $('#result').load('ajax/test.html #container');
    

    So what that does is it loads the #container element from the specified url.

    When is the finalize() method called in Java?

    Class where we override finalize method

    public class TestClass {    
        public TestClass() {
            System.out.println("constructor");
        }
    
        public void display() {
            System.out.println("display");
        }
        @Override
        public void finalize() {
            System.out.println("destructor");
        }
    }
    

    The chances of finalize method being called

    public class TestGarbageCollection {
        public static void main(String[] args) {
            while (true) {
                TestClass s = new TestClass();
                s.display();
                System.gc();
            }
        }
    }
    

    when the memory is overloaded with dump objects the gc will call finalize method

    run and see the console, where you dont find the finalize method being called frequently, when the memory is getting overloaded then the finalize method will be called.

    Property 'map' does not exist on type 'Observable<Response>'

    In Angular v10.x and rxjs v6.x

    First import map top of my service,

    import {map} from 'rxjs/operators';

    Then I use map like this

    return this.http.get<return type>(URL)
      .pipe(map(x => {
        // here return your pattern
        return x.foo;
      }));
    

    Reading text files using read.table

    From ?read.table: The number of data columns is determined by looking at the first five lines of input (or the whole file if it has less than five lines), or from the length of col.names if it is specified and is longer. This could conceivably be wrong if fill or blank.lines.skip are true, so specify col.names if necessary.

    So, perhaps your data file isn't clean. Being more specific will help the data import:

    d = read.table("foobar.txt", 
                   sep="\t", 
                   col.names=c("id", "name"), 
                   fill=FALSE, 
                   strip.white=TRUE)
    

    will specify exact columns and fill=FALSE will force a two column data frame.

    AngularJS : When to use service instead of factory

    There is nothing a Factory cannot do or does better in comparison with a Service. And vice verse. Factory just seems to be more popular. The reason for that is its convenience in handling private/public members. Service would be more clumsy in this regard. When coding a Service you tend to make your object members public via “this” keyword and may suddenly find out that those public members are not visible to private methods (ie inner functions).

    var Service = function(){
    
      //public
      this.age = 13;
    
      //private
      function getAge(){
    
        return this.age; //private does not see public
    
      }
    
      console.log("age: " + getAge());
    
    };
    
    var s = new Service(); //prints 'age: undefined'
    

    Angular uses the “new” keyword to create a service for you, so the instance Angular passes to the controller will have the same drawback. Of course you may overcome the problem by using this/that:

    var Service = function(){
    
      var that = this;
    
      //public
      this.age = 13;
    
      //private
      function getAge(){
    
        return that.age;
    
      }
    
      console.log("age: " + getAge());
    
    };
    
    var s = new Service();// prints 'age: 13'  
    

    But with a large Service constant this\that-ing would make the code poorly readable. Moreover, the Service prototypes will not see private members – only public will be available to them:

    var Service = function(){
    
      var name = "George";
    
    };
    
    Service.prototype.getName = function(){
    
      return this.name; //will not see a private member
    
    };
    
    var s = new Service();
    console.log("name: " + s.getName());//prints 'name: undefined'
    

    Summing it up, using Factory is more convenient. As Factory does not have these drawbacks. I would recommend using it by default.

    how to get yesterday's date in C#

    DateTime.Today as it implies is todays date and you need to get the Date a day before so you subtract one day using AddDays(-1);

    There are sufficient options available in DateTime to get the formatting like ToShortDateString depending on your culture and you have no need to concatenate them individually.

    Also you can have a desirable format in the .ToString() version of the DateTime instance

    Making PHP var_dump() values display one line per value

    For devs needing something that works in the view source and the CLI, especially useful when debugging unit tests.

    echo vd([['foo'=>1, 'bar'=>2]]);
    
    function vd($in) {
      ob_start(); 
      var_dump($in);
      return "\n" . preg_replace("/=>[\r\n\s]+/", "=> ", ob_get_clean());
    }
    

    Yields:

    array(1) {
      [0] => array(2) {
        'foo' => int(1)
        'bar' => int(2)
      }
    }
    

    JSON Post with Customized HTTPHeader Field

    I tried as you mentioned, but only first parameter is going through and rest all are appearing in the server as undefined. I am passing JSONWebToken as part of header.

    .ajax({
        url: 'api/outletadd',
        type: 'post',
        data: { outletname:outletname , addressA:addressA , addressB:addressB, city:city , postcode:postcode , state:state , country:country , menuid:menuid },
        headers: {
            authorization: storedJWT
        },
        dataType: 'json',
        success: function (data){
            alert("Outlet Created");
        },
        error: function (data){
            alert("Outlet Creation Failed, please try again.");        
        }
    
        });
    

    How to ftp with a batch file?

    You can use PowerShell as well; this is what I did. As I needed to download a file based on a pattern I dynamically created a command file and then let ftp do the rest.

    I used basic PowerShell commands. I did not need to download any additional components. I first checked if the requisite number of files existed. If they I invoked the FTP the second time with an Mget. I run this from a Windows Server 2008 connecting to a Windows XP remote server.

    function make_ftp_command_file($p_file_pattern,$mget_flag)
    {
        # This function dynamically prepares the FTP file.
        # The file needs to be prepared daily because the
        # pattern changes daily.
        # PowerShell default encoding is Unicode.
        # Unicode command files are not compatible with FTP so
        # we need to make sure we create an ASCII file.
    
        write-output "USER" | out-file -filepath C:\fc.txt -encoding ASCII
        write-output "ftpusername" | out-file -filepath C:\fc.txt -encoding ASCII -Append
        write-output "password" | out-file -filepath C:\fc.txt -encoding ASCII -Append
        write-output "ASCII" | out-file -filepath C:\fc.txt -encoding ASCII -Append
        If ($mget_flag -eq "Y")
        {
            write-output "prompt" | out-file -filepath C:\fc.txt -encoding ASCII -Append
            write-output "mget $p_file_pattern" | out-file -filepath C:\fc.txt -encoding ASCII -Append
        }
        else
        {
            write-output "ls $p_file_pattern" | out-file -filepath C:\fc.txt -encoding ASCII -Append
        }
    
        write-output quit | out-file -filepath C:\fc.txt -encoding ASCII -Append
    }
    
    
    ###########################  Init Section ###############################
    $yesterday = (get-date).AddDays(-1)
    $yesterday_fmt = date $yesterday -format "yyyyMMdd"
    $file_pattern = "BRAE_GE_*" + $yesterday_fmt + "*.csv"
    $file_log = $yesterday_fmt + ".log"
    
    echo  $file_pattern
    echo  $file_log
    
    
    ############################## Main Section ############################
    # Change location to folder where the files need to be downloaded
    cd c:\remotefiles
    
    # Dynamically create the FTP Command to get a list of files from
    # the remote servers
    echo "Call function that creates a FTP Command "
    make_ftp_command_file $file_pattern N
    
    
    #echo "Connect to remote site via FTP"
    # Connect to Remote Server and get file listing
    ftp -n -v -s:C:\Clover\scripts\fc.txt 10.129.120.31 > C:\logs\$file_log
    
    $matches=select-string -pattern "BRAE_GE_[A-Z][A-Z]*" C:\logs\$file_log
    
    # Check if the required number of Files available for download
    if ($matches.count -eq 36)
    {
        # Create the FTP command file
    
        # This time the command file has an mget rather than an ls
        make_ftp_command_file $file_pattern Y
    
        # Change directory if not done so
        cd c:\remotefiles
    
        # Invoke ftp with newly created command file
        ftp -n -v -s:C:\Clover\scripts\fc.txt 10.129.120.31 > C:\logs\$file_log
    }
    else
    {
        echo "The full set of files is not available"
    }
    

    Launch an event when checking a checkbox in Angular2

    You can use ngModel like

    <input type="checkbox" [ngModel]="checkboxValue" (ngModelChange)="addProp($event)" data-md-icheck/>
    

    To update the checkbox state by updating the property checkboxValue in your code and when the checkbox is changed by the user addProp() is called.