Programs & Examples On #Inspections

How to resolve Unneccessary Stubbing exception

If you use any() when mocking, you have to relpace @RunWith(MockitoJUnitRunner.class) with @RunWith(MockitoJUnitRunner.Silent.class).

IntelliJ inspection gives "Cannot resolve symbol" but still compiles code

I tried invalidating cache, it didnt work for me.

However, I tried removing the jdk from Platform Settings and added it back and it worked.

Here's how to do it.

Project Settings -> SDKs -> Select the SDK -> Remove (-) -> Add it back again (+)

Permissions error when connecting to EC2 via SSH on Mac OSx

After about a half hour of searching and trying to debug this I was able to figure it out. My situation involved me using the same pem file for two different ec2 instance and it working for one and not the other.

My first instance it worked on was the standard aws linux ami amzn-ami-hvm-2014.03.2.x86_64-ebs. I simply used

ssh -i mypemfile.pem ec2-user@myec2ipaddress 

and it worked.

I then launched a fedora instance Fedora-x86_64-19-20140407-sda and tried the same command but kept getting:

Permission denied (publickey,gssapi-keyex,gssapi-with-mic).

After changing my username from ec2-user to fedora it worked!

ssh -i mypemfile.pem fedora@myec2address

How to get current user in asp.net core

Have another way of getting current user in Asp.NET Core - and I think I saw it somewhere here, on SO ^^

// Stores UserManager
private readonly UserManager<ApplicationUser> _manager; 

// Inject UserManager using dependency injection.
// Works only if you choose "Individual user accounts" during project creation.
public DemoController(UserManager<ApplicationUser> manager)  
{  
    _manager = manager;  
}

// You can also just take part after return and use it in async methods.
private async Task<ApplicationUser> GetCurrentUser()  
{  
    return await _manager.GetUserAsync(HttpContext.User);  
}  

// Generic demo method.
public async Task DemoMethod()  
{  
    var user = await GetCurrentUser(); 
    string userEmail = user.Email; // Here you gets user email 
    string userId = user.Id;
}  

That code goes to controller named DemoController. Won't work without both await (won't compile) ;)

Running a cron job at 2:30 AM everyday

As seen in the other answers, the syntax to use is:

  30 2 * * * /your/command
# ^  ^
# |   hour
# minute

Following the crontab standard format:

 +---------------- minute (0 - 59)
 |  +------------- hour (0 - 23)
 |  |  +---------- day of month (1 - 31)
 |  |  |  +------- month (1 - 12)
 |  |  |  |  +---- day of week (0 - 6) (Sunday=0 or 7)
 |  |  |  |  |
 *  *  *  *  *  command to be executed

It is also useful to use crontab.guru to check crontab expressions.

The expressions are added into crontab using crontab -e. Once you are done, save and exit (if you are using vi, typing :x does it). The good think of using this tool is that if you write an invalid command you are likely to get a message prompt on the form:

$ crontab -e
crontab: installing new crontab
"/tmp/crontab.tNt1NL/crontab":7: bad minute
errors in crontab file, can't install.
Do you want to retry the same edit? (y/n) 

If you have further problems with crontab not running you can check Debugging crontab or Why is crontab not executing my PHP script?.

Convert list to array in Java

Try this:

List list = new ArrayList();
list.add("Apple");
list.add("Banana");

Object[] ol = list.toArray();

#1045 - Access denied for user 'root'@'localhost' (using password: YES)

First you have to go config.inc.php file then change the following instruction

$cfg['Servers'][$i]['user'] ='';
$cfg['Servers'][$i]['password'] =''; 

or

enter image description here

VHDL - How should I create a clock in a testbench?

If multiple clock are generated with different frequencies, then clock generation can be simplified if a procedure is called as concurrent procedure call. The time resolution issue, mentioned by Martin Thompson, may be mitigated a little by using different high and low time in the procedure. The test bench with procedure for clock generation is:

library ieee;
use ieee.std_logic_1164.all;

entity tb is
end entity;

architecture sim of tb is

  -- Procedure for clock generation
  procedure clk_gen(signal clk : out std_logic; constant FREQ : real) is
    constant PERIOD    : time := 1 sec / FREQ;        -- Full period
    constant HIGH_TIME : time := PERIOD / 2;          -- High time
    constant LOW_TIME  : time := PERIOD - HIGH_TIME;  -- Low time; always >= HIGH_TIME
  begin
    -- Check the arguments
    assert (HIGH_TIME /= 0 fs) report "clk_plain: High time is zero; time resolution to large for frequency" severity FAILURE;
    -- Generate a clock cycle
    loop
      clk <= '1';
      wait for HIGH_TIME;
      clk <= '0';
      wait for LOW_TIME;
    end loop;
  end procedure;

  -- Clock frequency and signal
  signal clk_166 : std_logic;
  signal clk_125 : std_logic;

begin

  -- Clock generation with concurrent procedure call
  clk_gen(clk_166, 166.667E6);  -- 166.667 MHz clock
  clk_gen(clk_125, 125.000E6);  -- 125.000 MHz clock

  -- Time resolution show
  assert FALSE report "Time resolution: " & time'image(time'succ(0 fs)) severity NOTE;

end architecture;

The time resolution is printed on the terminal for information, using the concurrent assert last in the test bench.

If the clk_gen procedure is placed in a separate package, then reuse from test bench to test bench becomes straight forward.

Waveform for clocks are shown in figure below.

Waveforms for clk_166 and clk_125

An more advanced clock generator can also be created in the procedure, which can adjust the period over time to match the requested frequency despite the limitation by time resolution. This is shown here:

-- Advanced procedure for clock generation, with period adjust to match frequency over time, and run control by signal
procedure clk_gen(signal clk : out std_logic; constant FREQ : real; PHASE : time := 0 fs; signal run : std_logic) is
  constant HIGH_TIME   : time := 0.5 sec / FREQ;  -- High time as fixed value
  variable low_time_v  : time;                    -- Low time calculated per cycle; always >= HIGH_TIME
  variable cycles_v    : real := 0.0;             -- Number of cycles
  variable freq_time_v : time := 0 fs;            -- Time used for generation of cycles
begin
  -- Check the arguments
  assert (HIGH_TIME /= 0 fs) report "clk_gen: High time is zero; time resolution to large for frequency" severity FAILURE;
  -- Initial phase shift
  clk <= '0';
  wait for PHASE;
  -- Generate cycles
  loop
    -- Only high pulse if run is '1' or 'H'
    if (run = '1') or (run = 'H') then
      clk <= run;
    end if;
    wait for HIGH_TIME;
    -- Low part of cycle
    clk <= '0';
    low_time_v := 1 sec * ((cycles_v + 1.0) / FREQ) - freq_time_v - HIGH_TIME;  -- + 1.0 for cycle after current
    wait for low_time_v;
    -- Cycle counter and time passed update
    cycles_v := cycles_v + 1.0;
    freq_time_v := freq_time_v + HIGH_TIME + low_time_v;
  end loop;
end procedure;

Again reuse through a package will be nice.

Div height 100% and expands to fit content

Set the height to auto and min-height to 100%. This should solve it for most browsers.

body {
  position: relative;
  height: auto;
  min-height: 100% !important;
}

How to convert string to IP address and vice versa

The third inet_pton parameter is a pointer to an in_addr structure. After a successful inet_pton call, the in_addr structure will be populated with the address information. The structure's S_addr field contains the IP address in network byte order (reverse order).

Example : 

#include <arpa/inet.h>
uint32_t NodeIpAddress::getIPv4AddressInteger(std::string IPv4Address) {
    int result;
    uint32_t IPv4Identifier = 0;
    struct in_addr addr;
    // store this IP address in sa:
    result = inet_pton(AF_INET, IPv4Address.c_str(), &(addr));
    if (result == -1) {         
gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4 Address. Due to invalid family of %d. WSA Error of %d"), IPv4Address.c_str(), AF_INET, result);
    }
    else if (result == 0) {
        gpLogFile->Write(LOGPREFIX, LogFile::LOGLEVEL_ERROR, _T("Failed to convert IP %hs to IPv4"), IPv4Address.c_str());
    }
    else {
        IPv4Identifier = ntohl(*((uint32_t *)&(addr)));
    }
    return IPv4Identifier;
}

Adding external resources (CSS/JavaScript/images etc) in JSP

The reason that you get the 404 File Not Found error, is that your path to CSS given as a value to the href attribute is missing context path.

An HTTP request URL contains the following parts:

http://[host]:[port][request-path]?[query-string]

The request path is further composed of the following elements:

  • Context path: A concatenation of a forward slash (/) with the context root of the servlet's web application. Example: http://host[:port]/context-root[/url-pattern]

  • Servlet path: The path section that corresponds to the component alias that activated this request. This path starts with a forward slash (/).

  • Path info: The part of the request path that is not part of the context path or the servlet path.

Read more here.


Solutions

There are several solutions to your problem, here are some of them:

1) Using <c:url> tag from JSTL

In my Java web applications I usually used <c:url> tag from JSTL when defining the path to CSS/JavaScript/image and other static resources. By doing so you can be sure that those resources are referenced always relative to the application context (context path).

If you say, that your CSS is located inside WebContent folder, then this should work:

<link type="text/css" rel="stylesheet" href="<c:url value="/globalCSS.css" />" />

The reason why it works is explained in the "JavaServer Pages™ Standard Tag Library" version 1.2 specification chapter 7.5 (emphasis mine):

7.5 <c:url>
Builds a URL with the proper rewriting rules applied.
...
The URL must be either an absolute URL starting with a scheme (e.g. "http:// server/context/page.jsp") or a relative URL as defined by JSP 1.2 in JSP.2.2.1 "Relative URL Specification". As a consequence, an implementation must prepend the context path to a URL that starts with a slash (e.g. "/page2.jsp") so that such URLs can be properly interpreted by a client browser.

NOTE
Don't forget to use Taglib directive in your JSP to be able to reference JSTL tags. Also see an example JSP page here.


2) Using JSP Expression Language and implicit objects

An alternative solution is using Expression Language (EL) to add application context:

<link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath}/globalCSS.css" />

Here we have retrieved the context path from the request object. And to access the request object we have used the pageContext implicit object.


3) Using <c:set> tag from JSTL

DISCLAIMER
The idea of this solution was taken from here.

To make accessing the context path more compact than in the solution ?2, you can first use the JSTL <c:set> tag, that sets the value of an EL variable or the property of an EL variable in any of the JSP scopes (page, request, session, or application) for later access.

<c:set var="root" value="${pageContext.request.contextPath}"/>
...
<link type="text/css" rel="stylesheet" href="${root}/globalCSS.css" />

IMPORTANT NOTE
By default, in order to set the variable in such manner, the JSP that contains this set tag must be accessed at least once (including in case of setting the value in the application scope using scope attribute, like <c:set var="foo" value="bar" scope="application" />), before using this new variable. For instance, you can have several JSP files where you need this variable. So you must ether a) both set the new variable holding context path in the application scope AND access this JSP first, before using this variable in other JSP files, or b) set this context path holding variable in EVERY JSP file, where you need to access to it.


4) Using ServletContextListener

The more effective way to make accessing the context path more compact is to set a variable that will hold the context path and store it in the application scope using a Listener. This solution is similar to solution ?3, but the benefit is that now the variable holding context path is set right at the start of the web application and is available application wide, no need for additional steps.

We need a class that implements ServletContextListener interface. Here is an example of such class:

package com.example.listener;

import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

@WebListener
public class AppContextListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent event) {
        ServletContext sc = event.getServletContext();
        sc.setAttribute("ctx", sc.getContextPath());
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {}

}

Now in a JSP we can access this global variable using EL:

<link type="text/css" rel="stylesheet" href="${ctx}/globalCSS.css" />

NOTE
@WebListener annotation is available since Servlet version 3.0. If you use a servlet container or application server that supports older Servlet specifications, remove the @WebServlet annotation and instead configure the listener in the deployment descriptor (web.xml). Here is an example of web.xml file for the container that supports maximum Servlet version 2.5 (other configurations are omitted for the sake of brevity):

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
                        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    version="2.5">
    ...  
    <listener>
        <listener-class>com.example.listener.AppContextListener</listener-class>
    </listener>
    ...
</webapp>


5) Using scriptlets

As suggested by user @gavenkoa you can also use scriptlets like this:

<%= request.getContextPath() %>

For such a small thing it is probably OK, just note that generally the use of scriptlets in JSP is discouraged.


Conclusion

I personally prefer either the first solution (used it in my previous projects most of the time) or the second, as they are most clear, intuitive and unambiguous (IMHO). But you choose whatever suits you most.


Other thoughts

You can deploy your web app as the default application (i.e. in the default root context), so it can be accessed without specifying context path. For more info read the "Update" section here.

Laravel Redirect Back with() Message

I stopped writing this myself for laravel in favor of the Laracasts package that handles it all for you. It is really easy to use and keeps your code clean. There is even a laracast that covers how to use it. All you have to do:

Pull in the package through Composer.

"require": {
  "laracasts/flash": "~1.0"
}

Include the service provider within app/config/app.php.

'providers' => [
  'Laracasts\Flash\FlashServiceProvider'
];

Add a facade alias to this same file at the bottom:

'aliases' => [
  'Flash' => 'Laracasts\Flash\Flash'
];

Pull the HTML into the view:

@include('flash::message') 

There is a close button on the right of the message. This relies on jQuery so make sure that is added before your bootstrap.

optional changes:

If you aren't using bootstrap or want to skip the include of the flash message and write the code yourself:

@if (Session::has('flash_notification.message'))
  <div class="{{ Session::get('flash_notification.level') }}">
    {{ Session::get('flash_notification.message') }}
  </div>
@endif

If you would like to view the HTML pulled in by @include('flash::message'), you can find it in vendor/laracasts/flash/src/views/message.blade.php.

If you need to modify the partials do:

php artisan view:publish laracasts/flash

The two package views will now be located in the `app/views/packages/laracasts/flash/' directory.

Java ArrayList clear() function

data.removeAll(data); will do the work, I think.

How to convert milliseconds to "hh:mm:ss" format?

Going by Bohemian's answer we need need not use TimeUnit to find a known value. Much more optimal code would be

String hms = String.format("%02d:%02d:%02d", millisLeft/(3600*1000),
                    millisLeft/(60*1000) % 60,
                    millisLeft/1000 % 60);

Hope it helps

What's the yield keyword in JavaScript?

A simple example:

const strArr = ["red", "green", "blue", "black"];

const strGen = function*() {
    for(let str of strArr) {
        yield str;
    }
};

let gen = strGen();

for (let i = 0; i < 5; i++) {
    console.log(gen.next())
}

//prints: {value: "red", done: false} -> 5 times with different colors, if you try it again as below:

console.log(gen.next());

//prints: {value: undefined, done: true}

How to get the Parent's parent directory in Powershell?

To extrapolate a bit on the other answers (in as Beginner-friendly a way as possible):

  • String objects that point to valid paths can be converted to DirectoryInfo/FileInfo objects via functions like Get-Item and Get-ChildItem.
  • .Parent can only be used on a DirectoryInfo object.
  • .Directory converts FileInfo object to a DirectoryInfo object, and will return null if used on any other type (even another DirectoryInfo object).
  • .DirectoryName converts a FileInfo object to a String object, and will return null if used on any other type (even another String object).
  • .FullName converts a DirectoryInfo/FileInfo object to a String object, and will return null if used on any other type (even another DirectoryInfo/FileInfo object).

Check the object type with the GetType Method to see what you're working with: $scriptPath.GetType()

Lastly, a quick tip that helps with making one-liners: Get-Item has the gi alias and Get-ChildItem has the gci alias.

Is there possibility of sum of ArrayList without looping

for me the clearest way is this:

doubleList.stream().reduce((a,b)->a+b).get();

or

doubleList.parallelStream().reduce((a,b)->a+b).get();

It also use internal loops, but it is not possible without loops.

Bootstrap 4, How do I center-align a button?

Here is the full HTML that I use to center by button in Bootsrap form after closing form-group:

<div class="form-row text-center">
    <div class="col-12">
        <button type="submit" class="btn btn-primary">Submit</button>
    </div>
 </div>

Save the plots into a PDF

If someone ends up here from google, looking to convert a single figure to a .pdf (that was what I was looking for):

import matplotlib.pyplot as plt

f = plt.figure()
plt.plot(range(10), range(10), "o")
plt.show()

f.savefig("foo.pdf", bbox_inches='tight')

How do I invoke a Java method when given the method name as a string?

For those who are calling the method within the same class from a non-static method, see below codes:

class Person {
    public void method1() {
        try {
            Method m2 = this.getClass().getDeclaredMethod("method2");
            m1.invoke(this);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public void method2() {
        // Do something
    }

}

How to remove leading and trailing white spaces from a given html string?

See the String method trim() - https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/Trim

var myString = '  bunch    of <br> string data with<p>trailing</p> and leading space   ';
myString = myString.trim();
// or myString = String.trim(myString);

Edit

As noted in other comments, it is possible to use the regex approach. The trim method is effectively just an alias for a regex:

if(!String.prototype.trim) {  
  String.prototype.trim = function () {  
    return this.replace(/^\s+|\s+$/g,'');  
  };  
} 

... this will inject the method into the native prototype for those browsers who are still swimming in the shallow end of the pool.

Problems installing the devtools package

I found solution by seeing errors by R-Studio when I tried to install devtools package...Basically Error is because of dependence libraries not installed in linux Look at ANTICONF ERROR Below

Installing package into ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6’
(as ‘lib’ is unspecified)
also installing the dependencies ‘curl’, ‘gh’, ‘openssl’, ‘xml2’, ‘usethis’, ‘covr’, ‘httr’, ‘roxygen2’, ‘rversions’


trying URL 'https://cloud.r-project.org/src/contrib/curl_4.3.tar.gz'
Content type 'application/x-gzip' length 673779 bytes (657 KB)
==================================================
downloaded 657 KB

trying URL 'https://cloud.r-project.org/src/contrib/gh_1.1.0.tar.gz'
Content type 'application/x-gzip' length 29043 bytes (28 KB)
==================================================
downloaded 28 KB

trying URL 'https://cloud.r-project.org/src/contrib/openssl_1.4.2.tar.gz'
Content type 'application/x-gzip' length 1204168 bytes (1.1 MB)
==================================================
downloaded 1.1 MB

trying URL 'https://cloud.r-project.org/src/contrib/xml2_1.3.2.tar.gz'
Content type 'application/x-gzip' length 271876 bytes (265 KB)
==================================================
downloaded 265 KB

trying URL 'https://cloud.r-project.org/src/contrib/usethis_1.6.1.tar.gz'
Content type 'application/x-gzip' length 255052 bytes (249 KB)
==================================================
downloaded 249 KB

trying URL 'https://cloud.r-project.org/src/contrib/covr_3.5.0.tar.gz'
Content type 'application/x-gzip' length 146148 bytes (142 KB)
==================================================
downloaded 142 KB

trying URL 'https://cloud.r-project.org/src/contrib/httr_1.4.2.tar.gz'
Content type 'application/x-gzip' length 159950 bytes (156 KB)
==================================================
downloaded 156 KB

trying URL 'https://cloud.r-project.org/src/contrib/roxygen2_7.1.1.tar.gz'
Content type 'application/x-gzip' length 254118 bytes (248 KB)
==================================================
downloaded 248 KB

trying URL 'https://cloud.r-project.org/src/contrib/rversions_2.0.2.tar.gz'
Content type 'application/x-gzip' length 41558 bytes (40 KB)
==================================================
downloaded 40 KB

trying URL 'https://cloud.r-project.org/src/contrib/devtools_2.3.1.tar.gz'
Content type 'application/x-gzip' length 373604 bytes (364 KB)
==================================================
downloaded 364 KB

* installing *source* package ‘curl’ ...
** package ‘curl’ successfully unpacked and MD5 sums checked
** using staged installation
Package libcurl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl' found
Package libcurl was not found in the pkg-config search path.
Perhaps you should add the directory containing `libcurl.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libcurl' found
Using PKG_CFLAGS=
Using PKG_LIBS=-lcurl
------------------------- ANTICONF ERROR ---------------------------
Configuration failed because libcurl was not found. Try installing:
  deb: **libcurl4-openssl-dev** (Debian, Ubuntu, etc)
 * rpm: libcurl-devel (Fedora, CentOS, RHEL)
 * csw: libcurl_dev (Solaris)
If libcurl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libcurl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
ERROR: configuration failed for package ‘curl’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/curl’
Warning in install.packages :
  installation of package ‘curl’ had non-zero exit status
* installing *source* package ‘openssl’ ...
** package ‘openssl’ successfully unpacked and MD5 sums checked
** using staged installation
Using PKG_CFLAGS=
--------------------------- [ANTICONF] --------------------------------
Configuration failed because openssl was not found. Try installing:
  deb: **libssl-dev** (Debian, Ubuntu, etc)
 * rpm: openssl-devel (Fedora, CentOS, RHEL)
 * csw: libssl_dev (Solaris)
 * brew: [email protected] (Mac OSX)
If openssl is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a openssl.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
-------------------------- [ERROR MESSAGE] ---------------------------
tools/version.c:1:10: fatal error: openssl/opensslv.h: No such file or directory
    1 | #include <openssl/opensslv.h>
      |          ^~~~~~~~~~~~~~~~~~~~
compilation terminated.
--------------------------------------------------------------------
ERROR: configuration failed for package ‘openssl’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/openssl’
Warning in install.packages :
  installation of package ‘openssl’ had non-zero exit status
* installing *source* package ‘xml2’ ...
** package ‘xml2’ successfully unpacked and MD5 sums checked
** using staged installation
Package libxml-2.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing `libxml-2.0.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libxml-2.0' found
Package libxml-2.0 was not found in the pkg-config search path.
Perhaps you should add the directory containing `libxml-2.0.pc'
to the PKG_CONFIG_PATH environment variable
No package 'libxml-2.0' found
Using PKG_CFLAGS=
Using PKG_LIBS=-lxml2
------------------------- ANTICONF ERROR ---------------------------
Configuration failed because libxml-2.0 was not found. Try installing:
 deb: **libxml2-dev** (Debian, Ubuntu, etc)
 * rpm: libxml2-devel (Fedora, CentOS, RHEL)
 * csw: libxml2_dev (Solaris)
If libxml-2.0 is already installed, check that 'pkg-config' is in your
PATH and PKG_CONFIG_PATH contains a libxml-2.0.pc file. If pkg-config
is unavailable you can set INCLUDE_DIR and LIB_DIR manually via:
R CMD INSTALL --configure-vars='INCLUDE_DIR=... LIB_DIR=...'
--------------------------------------------------------------------
ERROR: configuration failed for package ‘xml2’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/xml2’
Warning in install.packages :
  installation of package ‘xml2’ had non-zero exit status
ERROR: dependencies ‘curl’, ‘openssl’ are not available for package ‘httr’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/httr’
Warning in install.packages :
  installation of package ‘httr’ had non-zero exit status
ERROR: dependency ‘xml2’ is not available for package ‘roxygen2’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/roxygen2’
Warning in install.packages :
  installation of package ‘roxygen2’ had non-zero exit status
ERROR: dependencies ‘curl’, ‘xml2’ are not available for package ‘rversions’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/rversions’
Warning in install.packages :
  installation of package ‘rversions’ had non-zero exit status
ERROR: dependency ‘httr’ is not available for package ‘gh’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/gh’
Warning in install.packages :
  installation of package ‘gh’ had non-zero exit status
ERROR: dependency ‘httr’ is not available for package ‘covr’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/covr’
Warning in install.packages :
  installation of package ‘covr’ had non-zero exit status
ERROR: dependencies ‘curl’, ‘gh’ are not available for package ‘usethis’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/usethis’
Warning in install.packages :
  installation of package ‘usethis’ had non-zero exit status
ERROR: dependencies ‘usethis’, ‘covr’, ‘httr’, ‘roxygen2’, ‘rversions’ are not available for package ‘devtools’
* removing ‘/home/hafiz/R/x86_64-pc-linux-gnu-library/3.6/devtools’
Warning in install.packages :
  installation of package ‘devtools’ had non-zero exit status

The downloaded source packages are in
    ‘/tmp/Rtmpexapon/downloaded_packages’

look at bold libraries which are missing libssl-dev libxml2-dev

just you need to install these libraries in ubuntu terminal or

whatever operating system you are using you will find relative errors w r t operating system see errors in details.. R-studio mentioned relative library package name against operating system

for ubuntu i did this

sudo apt-get install libssl-dev

**sudo apt-get install libxml2-dev **

sudo apt-get install libcurl4-openssl-dev

g++ undefined reference to typeinfo

I've got same error when my interface (with all pure virtual functions) needed one more function and I forgot to "null" it.

I had

class ICommProvider { public: /** * @brief If connection is established, it sends the message into the server. * @param[in] msg - message to be send * @return 0 if success, error otherwise */ virtual int vaSend(const std::string &msg) = 0; /** * @brief If connection is established, it is waiting will server response back. * @param[out] msg is the message received from server * @return 0 if success, error otherwise */ virtual int vaReceive(std::string &msg) = 0; virtual int vaSendRaw(const char *buff, int bufflen) = 0; virtual int vaReceiveRaw(char *buff, int bufflen) = 0; /** * @bief Closes current connection (if needed) after serving * @return 0 if success, error otherwise */ virtual int vaClose(); };

Last vaClose is not virtual so compiled did not know where to get implementation for it and thereby got confused. my message was:

...TCPClient.o:(.rodata+0x38): undefined reference to `typeinfo for ICommProvider'

Simple change from

virtual int vaClose();

to

virtual int vaClose() = 0;

fixed the problem. hope it helps

How do I iterate through each element in an n-dimensional matrix in MATLAB?

You want to simulate n-nested for loops.

Iterating through n-dimmensional array can be seen as increasing the n-digit number.

At each dimmension we have as many digits as the lenght of the dimmension.

Example:

Suppose we had array(matrix)

int[][][] T=new int[3][4][5];

in "for notation" we have:

for(int x=0;x<3;x++)
   for(int y=0;y<4;y++)
       for(int z=0;z<5;z++)
          T[x][y][z]=...

to simulate this you would have to use the "n-digit number notation"

We have 3 digit number, with 3 digits for first, 4 for second and five for third digit

We have to increase the number, so we would get the sequence

0 0 0
0 0 1
0 0 2    
0 0 3
0 0 4
0 1 0
0 1 1
0 1 2
0 1 3
0 1 4
0 2 0
0 2 1
0 2 2
0 2 3
0 2 4
0 3 0
0 3 1
0 3 2
0 3 3
0 3 4
and so on

So you can write the code for increasing such n-digit number. You can do it in such way that you can start with any value of the number and increase/decrease the digits by any numbers. That way you can simulate nested for loops that begin somewhere in the table and finish not at the end.

This is not an easy task though. I can't help with the matlab notation unfortunaly.

Chart.js v2 hide dataset labels

Just set the label and tooltip options like so

...
options: {
    legend: {
        display: false
    },
    tooltips: {
        callbacks: {
           label: function(tooltipItem) {
                  return tooltipItem.yLabel;
           }
        }
    }
}

Fiddle - http://jsfiddle.net/g19220r6/

Generate 'n' unique random numbers within a range

Generate the range of data first and then shuffle it like this

import random
data = range(numLow, numHigh)
random.shuffle(data)
print data

By doing this way, you will get all the numbers in the particular range but in a random order.

But you can use random.sample to get the number of elements you need, from a range of numbers like this

print random.sample(range(numLow, numHigh), 3)

How to send a POST request using volley with string body?

Name = editTextName.getText().toString().trim();
Email = editTextEmail.getText().toString().trim();
Phone = editTextMobile.getText().toString().trim();


JSONArray jsonArray = new JSONArray();
jsonArray.put(Name);
jsonArray.put(Email);
jsonArray.put(Phone);
final String mRequestBody = jsonArray.toString();

StringRequest stringRequest = new StringRequest(Request.Method.PUT, OTP_Url, new Response.Listener<String>() {
    @Override
    public void onResponse(String response) {
        Log.v("LOG_VOLLEY", response);

    }
}, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        Log.e("LOG_VOLLEY", error.toString());
    }
}) {
    @Override
    public String getBodyContentType() {
        return "application/json; charset=utf-8";
    }

    @Override
    public byte[] getBody() throws AuthFailureError {
        try {
            return mRequestBody == null ? null : mRequestBody.getBytes("utf-8");
        } catch (UnsupportedEncodingException uee) {
            VolleyLog.wtf("Unsupported Encoding while trying to get the bytes of %s using %s", mRequestBody, "utf-8");
            return null;
        }
    }

};
stringRequest.setShouldCache(false);
VollySupport.getmInstance(RegisterActivity.this).addToRequestque(stringRequest);

Creating a JSON array in C#

new {var_data[counter] =new [] { 
                new{  "S NO":  "+ obj_Data_Row["F_ID_ITEM_MASTER"].ToString() +","PART NAME": " + obj_Data_Row["F_PART_NAME"].ToString() + ","PART ID": " + obj_Data_Row["F_PART_ID"].ToString() + ","PART CODE":" + obj_Data_Row["F_PART_CODE"].ToString() + ", "CIENT PART ID": " + obj_Data_Row["F_ID_CLIENT"].ToString() + ","TYPES":" + obj_Data_Row["F_TYPE"].ToString() + ","UOM":" + obj_Data_Row["F_UOM"].ToString() + ","SPECIFICATION":" + obj_Data_Row["F_SPECIFICATION"].ToString() + ","MODEL":" + obj_Data_Row["F_MODEL"].ToString() + ","LOCATION":" + obj_Data_Row["F_LOCATION"].ToString() + ","STD WEIGHT":" + obj_Data_Row["F_STD_WEIGHT"].ToString() + ","THICKNESS":" + obj_Data_Row["F_THICKNESS"].ToString() + ","WIDTH":" + obj_Data_Row["F_WIDTH"].ToString() + ","HEIGHT":" + obj_Data_Row["F_HEIGHT"].ToString() + ","STUFF QUALITY":" + obj_Data_Row["F_STUFF_QTY"].ToString() + ","FREIGHT":" + obj_Data_Row["F_FREIGHT"].ToString() + ","THRESHOLD FG":" + obj_Data_Row["F_THRESHOLD_FG"].ToString() + ","THRESHOLD CL STOCK":" + obj_Data_Row["F_THRESHOLD_CL_STOCK"].ToString() + ","DESCRIPTION":" + obj_Data_Row["F_DESCRIPTION"].ToString() + "}
        }
    };

"Object doesn't support this property or method" error in IE11

This unfortunately breaks other things. Here is the fix I found on another site that seemed to work for me:

I'd say leave the X-UA-Compatible as "IE=8" and add the following code to the bottom of your master page:

<script language="javascript">
    /* IE11 Fix for SP2010 */
    if (typeof(UserAgentInfo) != 'undefined' && !window.addEventListener) 
    {
        UserAgentInfo.strBrowser=1; 
    } 
</script>

This fixes a bug in core.js which incorrectly calculates that sets UserAgentInfo.strBrowse=3 for IE11 and thus supporting addEventListener. I'm not entirely sure on the details other than that but the combination of keeping IE=8 and using this script is working for me. Fingers crossed until I find the next IE11/SharePoint "bug"!

Change One Cell's Data in mysql

Try the following:

UPDATE TableName SET ValueName=@parameterName WHERE
IdName=@ParameterIdName

Trying to get property of non-object in

<?php foreach ($sidemenus->mname as $sidemenu): ?>
<?php echo $sidemenu ."<br />";?>

or

$sidemenus = mysql_fetch_array($results);

then

<?php echo $sidemenu['mname']."<br />";?>

Spring - applicationContext.xml cannot be opened because it does not exist

You actually need to understand the ApplicationContext. It is an interface and it will have different implementations based on configuration.

As you are using new ClassPathXmlApplicationContext("applicationContext.xml"); , kindly pay attention to initial right hand-side , it says ClassPathXmlApplicationContext , so the XML must be present in the class path. So drag your applicationContext.xml wherever it is to the src folder.

Gist: new ClassPathXmlApplicationContext as the name [ClassPathXml]will look for the xml file in the src folder of your project, so drag your xml file there only.

? ClassPathXmlApplicationContext—Loads a context definition from an XML file located in the classpath, treating context definition files as classpath resources.

? FileSystemXmlApplicationContext—Loads a context definition from an XML file in the file system.

? XmlWebApplicationContext—Loads context definitions from an XML file contained within a web application.

How do I install pip on macOS or OS X?

I'm surprised no-one has mentioned this - since 2013, python itself is capable of installing pip, no external commands (and no internet connection) required.

sudo -H python -m ensurepip

This will create a similar install to what easy_install would.

how to update spyder on anaconda

To expand on juanpa.arrivillaga's comment:

If you want to update Spyder in the root environment, then conda update spyder works for me.

If you want to update Spyder for a virtual environment you have created (e.g., for a different version of Python), then conda update -n $ENV_NAME spyder where $ENV_NAME is your environment name.

EDIT: In case conda update spyder isn't working, this post indicates you might need to run conda update anaconda before updating spyder. Also note that you can specify an exact spyder version if you want.

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

some dynamic situation holder.edit_pin.setInputType(InputType.TYPE_CLASS_NUMBER); will not work so better use both like that

holder.edit_pin.setInputType(InputType.TYPE_CLASS_NUMBER);
holder.edit_pin.setTransformationMethod(PasswordTransformationMethod.getInstance());

Note : this is suitable for when you are using dynamic controls like using arrayaapter

Avoid printStackTrace(); use a logger call instead

It means you should use logging framework like or and instead of printing exceptions directly:

e.printStackTrace();

you should log them using this frameworks' API:

log.error("Ops!", e);

Logging frameworks give you a lot of flexibility, e.g. you can choose whether you want to log to console or file - or maybe skip some messages if you find them no longer relevant in some environment.

What is the python keyword "with" used for?

In python the with keyword is used when working with unmanaged resources (like file streams). It is similar to the using statement in VB.NET and C#. It allows you to ensure that a resource is "cleaned up" when the code that uses it finishes running, even if exceptions are thrown. It provides 'syntactic sugar' for try/finally blocks.

From Python Docs:

The with statement clarifies code that previously would use try...finally blocks to ensure that clean-up code is executed. In this section, I’ll discuss the statement as it will commonly be used. In the next section, I’ll examine the implementation details and show how to write objects for use with this statement.

The with statement is a control-flow structure whose basic structure is:

with expression [as variable]:
    with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

Update fixed VB callout per Scott Wisniewski's comment. I was indeed confusing with with using.

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

Did you try to specify resource only in context.xml

<Resource name="jdbc/PollDatasource" auth="Container" type="javax.sql.DataSource"
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
url="jdbc:derby://localhost:1527/poll_database;create=true"
username="suhail" password="suhail"
maxActive="20" maxIdle="10" maxWait="-1" />

and remove <resource-ref> section from web.xml?

In one project I've seen configuration without <resource-ref> section in web.xml and it worked.

It's an educated guess, but I think <resource-ref> declaration of JNDI resource named jdbc/PollDatasource in web.xml may override declaration of resource with same name in context.xml and the declaration in web.xml is missing both driverClassName and url hence the NPEs for that properties.

SDK Location not found Android Studio + Gradle

If none of the answers work for you which happened to me on macbook pro in one of the projects you can always try to run Android Studio with an alias command passing sdk.dir with each run:

alias studio='launchctl setenv ANDROID_HOME '\''/Users/username/Library/Android/sdk'\'' && open -a '\''Android Studio'\'''

Should I use the Reply-To header when sending emails as a service to others?

You may want to consider placing the customer's name in the From header and your address in the Sender header:

From: Company A <[email protected]>
Sender: [email protected]

Most mailers will render this as "From [email protected] on behalf of Company A", which is accurate. And then a Reply-To of Company A's address won't seem out of sorts.

From RFC 5322:

The "From:" field specifies the author(s) of the message, that is, the mailbox(es) of the person(s) or system(s) responsible for the writing of the message. The "Sender:" field specifies the mailbox of the agent responsible for the actual transmission of the message. For example, if a secretary were to send a message for another person, the mailbox of the secretary would appear in the "Sender:" field and the mailbox of the actual author would appear in the "From:" field.

jQuery UI Dialog with ASP.NET button postback

The exact solution is;

$("#dialogDiv").dialog({ other options...,
    open: function (type, data) {
        $(this).parent().appendTo("form");
    }
});

What is the difference between JavaScript and ECMAScript?

I think a little history lesson is due.

JavaScript was originally named Mocha and changed to Livescript but ultimately became JavaScript.

It's important to note that JavaScript came before ECMAscript and the history will tell you why.

To start from the beginning, JavaScript derived its name from Java and initially Brendan Eich (the creator of JS) was asked to develop a language that resembled Java for the web for Netscape.

Eich, however decided that Java was too complicated with all its rules and so set out to create a simpler language that even a beginner could code in. This is evident in such things like the relaxing of the need to have a semicolon.

After the language was complete, the marketing team of Netscape requested Sun to allow them to name it JavaScript as a marketing stunt and hence why most people who have never used JavaScript think it's related to Java.

About a year or two after JavaScript's release in the browser, Microsoft's IE took the language and started making its own implementations such as JScript. At the same time, IE was dominating the market and not long after Netscape had to shut its project.

Before Netscape went down, they decided to start a standard that would guide the path of JavaScript, named ECMAScript.

ECMAScript had a few releases and in 1999 they released their last version (ECMAScript 3) before they went into hibernation for the next 10 years. During this 10 years, Microsoft dominated the scenes but at the same time they weren't improving their product and hence Firefox was born (led by Eich) and a whole heap of other browsers such as Chrome, Opera.

ECMAScript released its 5th Edition in 2009 (the 4th edition was abandoned) with features such as strict mode. Since then, ECMAScript has gained a lot of momentum and is scheduled to release its 6th Edition in a few months from now with the biggest changes its had thus far.

You can use a list of features for ECMAScript 6 here http://kangax.github.io/es5-compat-table/es6/ and also the browser support. You can even start writing Ecmascript 6 like you do with CoffeeScript and use a compiler to compile down to Ecmascript 5.

Whether ECMAScript is the language and JavaScript is a dialect is arguable, but not important. If you continue to think like this it might confuse you. There is no compiler out there that would run ECMAScript, and I believe JavaScript is considered the Language which implements a standard called ECMAScript.

There are also other noticeable languages that implement ECMAScript such as ActionScript (used for Flash)

How to add font-awesome to Angular 2 + CLI project

If for some reason you cant install package throw npm. You can always edit index.html and add font awesome CSS in the head. And then just used it in the project.

Django 1.7 - makemigrations not detecting changes

You want to check the settings.py in the INSTALLED_APPS list and make sure all the apps with models are listed in there.

Running makemigrations in the project folder means it will look to update all the tables related to all the apps included in settings.py for the project. Once you include it, makemigrations will automatically include the app (this saves a lot of work so you don't have to run makemigrations app_name for every app in your project/site).

How to implement zoom effect for image view in android?

Lazy man can use this lib, Just import inside your project and

ImageView mImageView;
PhotoViewAttacher mAttacher;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Any implementation of ImageView can be used!
    mImageView = (ImageView) findViewById(R.id.iv_photo);

    // Set the Drawable displayed
    Drawable bitmap = getResources().getDrawable(R.drawable.wallpaper);
    mImageView.setImageDrawable(bitmap);

    // Attach a PhotoViewAttacher, which takes care of all of the zooming functionality.
    mAttacher = new PhotoViewAttacher(mImageView);
}


// If you later call mImageView.setImageDrawable/setImageBitmap/setImageResource/etc then you just need to call
mAttacher.update();

How to open maximized window with Javascript?

Checkout this jquery window plugin: http://fstoke.me/jquery/window/

// create a window
sampleWnd = $.window({
   .....
});

// resize the window by passed w,h parameter
sampleWnd.resize(screen.width, screen.height);

C - reading command line parameters

#include <stdio.h>
#include <stdlib.h>

int main(int argc, char **argv) {
  int i, parameter = 0;
  if (argc >= 2) {
    /* there is 1 parameter (or more) in the command line used */
    /* argv[0] may point to the program name */
    /* argv[1] points to the 1st parameter */
    /* argv[argc] is NULL */
    parameter = atoi(argv[1]); /* better to use strtol */
    if (parameter > 0) {
      for (i = 0; i < parameter; i++) printf("%d ", i);
    } else {
      fprintf(stderr, "Please use a positive integer.\n");
    }
  }
  return 0;
}

java.net.SocketTimeoutException: Read timed out under Tomcat

I have the same issue. The java.net.SocketTimeoutException: Read timed out error happens on Tomcat under Mac 11.1, but it works perfectly in Mac 10.13. Same Tomcat folder, same WAR file. Have tried setting timeout values higher, but nothing I do works. If I run the same SpringBoot code in a regular Java application (outside Tomcat 9.0.41 (tried other versions too), then it works also.

Mac 11.1 appears to be interfering with Tomcat.

As another test, if I copy the WAR file to an AWS EC2 instance, it works fine there too.

Spent several days trying to figure this out, but cannot resolve.

Suggestions very welcome! :)

What is aria-label and how should I use it?

The title attribute displays a tooltip when the mouse is hovering the element. While this is a great addition, it doesn't help people who cannot use the mouse (due to mobility disabilities) or people who can't see this tooltip (e.g.: people with visual disabilities or people who use a screen reader).

As such, the mindful approach here would be to serve all users. I would add both title and aria-label attributes (serving different types of users and different types of usage of the web).

Here's a good article that explains aria-label in depth

How can I generate UUID in C#

I have a GitHub Gist with a Java like UUID implementation in C#: https://gist.github.com/rickbeerendonk/13655dd24ec574954366

The UUID can be created from the least and most significant bits, just like in Java. It also exposes them. The implementation has an explicit conversion to a GUID and an implicit conversion from a GUID.

Toggle show/hide on click with jQuery

You can use this code for toggle your element var ele = jQuery("yourelementid"); ele.slideToggle('slow'); this will work for you :)

Installing Pandas on Mac OSX

Not an innovative way but below two steps might save a ton of time and energy.

  1. Updating (Installing Command Line Tool) Code.

This can be done by openinig XCode -> Menu -> Preference -> Components -> Command Line Tool

  1. Removing all but Python 2.7

I did installed different instances of python at different time and removing all but 2.7 was helpful in my case. Note : You may have to install modules after doing it. So get ready with pip/easy_install/ports.

Uninstall can be done with super easy steps mentioned in following link.

How to uninstall Python 2.7 on a Mac OS X 10.6.4?

How to use Utilities.sleep() function

Serge is right - my workaround:

function mySleep (sec)
{
  SpreadsheetApp.flush();
  Utilities.sleep(sec*1000);
  SpreadsheetApp.flush();
}

data.frame Group By column

This is a common question. In base, the option you're looking for is aggregate. Assuming your data.frame is called "mydf", you can use the following.

> aggregate(B ~ A, mydf, sum)
  A  B
1 1  5
2 2  3
3 3 11

I would also recommend looking into the "data.table" package.

> library(data.table)
> DT <- data.table(mydf)
> DT[, sum(B), by = A]
   A V1
1: 1  5
2: 2  3
3: 3 11

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

This is how I solved this issue.

downgrade to python 3.6.x 64bit. I installed3.6.8 64bit.

install virtualenv by pip install virtualenv

upgrade pip to the latest version, for me it’s 19.3

go to the folder you want to create a virtual environment and type virtualenv ENV after created the virtual environment, go to the subfolder \PATH\ENV\Script and execute activate.bat. Now you will be in the virtual environment.

pip install rasa The problem is tensorflow 15 requires 64 bit python with no more than 3.6

Change Placeholder Text using jQuery

You can use following code to update a placeholder by id:

$("#serMemtb").attr("placeholder", "Type a Location").val("").focus().blur();

How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites

My stab at this based on other answers.

function timeSince(date) {
    let minute = 60;
    let hour   = minute * 60;
    let day    = hour   * 24;
    let month  = day    * 30;
    let year   = day    * 365;

    let suffix = ' ago';

    let elapsed = Math.floor((Date.now() - date) / 1000);

    if (elapsed < minute) {
        return 'just now';
    }

    // get an array in the form of [number, string]
    let a = elapsed < hour  && [Math.floor(elapsed / minute), 'minute'] ||
            elapsed < day   && [Math.floor(elapsed / hour), 'hour']     ||
            elapsed < month && [Math.floor(elapsed / day), 'day']       ||
            elapsed < year  && [Math.floor(elapsed / month), 'month']   ||
            [Math.floor(elapsed / year), 'year'];

    // pluralise and append suffix
    return a[0] + ' ' + a[1] + (a[0] === 1 ? '' : 's') + suffix;
}

Is it possible to have a custom facebook like button?

It's possible with a lot of work.

Basically, you have to post likes action via the Open Graph API. Then, you can add a custom design to your like button.

But then, you''ll need to keep track yourself of the likes so a returning user will be able to unlike content he liked previously.

Plus, you'll need to ask user to log into your app and ask them the publish_action permission.

All in all, if you're doing this for an application, it may worth it. For a website where you basically want user to like articles, then this is really to much.

Also, consider that you increase your drop-off rate each time you ask user a permission via a Facebook login.

If you want to see an example, I've recently made an app using the open graph like button, just hover on some photos in the mosaique to see it

Set Windows process (or user) memory limit

Depending on your applications, it might be easier to limit the memory the language interpreter uses. For example with Java you can set the amount of RAM the JVM will be allocated.

Otherwise it is possible to set it once for each process with the windows API

SetProcessWorkingSetSize Function

Clearing coverage highlighting in Eclipse

If you would like to remove active session/project/folder then you can follow

Click the "Remove Active Session" button in the toolbar of the "Coverage" view.

How to replace specific values in a oracle database column?

If you need to update the value in a particular table:

UPDATE TABLE-NAME SET COLUMN-NAME = REPLACE(TABLE-NAME.COLUMN-NAME, 'STRING-TO-REPLACE', 'REPLACEMENT-STRING');

where

  TABLE-NAME         - The name of the table being updated
  COLUMN-NAME        - The name of the column being updated
  STRING-TO-REPLACE  - The value to replace
  REPLACEMENT-STRING - The replacement

Java/Groovy - simple date reformatting

Your DateFormat pattern does not match you input date String. You could use

new SimpleDateFormat("dd-MMM-yyyy")

How to access a value defined in the application.properties file in Spring Boot

You can use the @Value annotation and access the property in whichever Spring bean you're using

@Value("${userBucket.path}")
private String userBucketPath;

The Externalized Configuration section of the Spring Boot docs, explains all the details that you might need.

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

This worked for me:-
Make all your IIS websites point to localhost(All Unassigned) only

enter image description here

How to rotate a div using jQuery

EDIT: Updated for jQuery 1.8

Since jQuery 1.8 browser specific transformations will be added automatically. jsFiddle Demo

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: Added code to make it a jQuery function.

For those of you who don't want to read any further, here you go. For more details and examples, read on. jsFiddle Demo.

var rotation = 0;

jQuery.fn.rotate = function(degrees) {
    $(this).css({'-webkit-transform' : 'rotate('+ degrees +'deg)',
                 '-moz-transform' : 'rotate('+ degrees +'deg)',
                 '-ms-transform' : 'rotate('+ degrees +'deg)',
                 'transform' : 'rotate('+ degrees +'deg)'});
    return $(this);
};

$('.rotate').click(function() {
    rotation += 5;
    $(this).rotate(rotation);
});

EDIT: One of the comments on this post mentioned jQuery Multirotation. This plugin for jQuery essentially performs the above function with support for IE8. It may be worth using if you want maximum compatibility or more options. But for minimal overhead, I suggest the above function. It will work IE9+, Chrome, Firefox, Opera, and many others.


Bobby... This is for the people who actually want to do it in the javascript. This may be required for rotating on a javascript callback.

Here is a jsFiddle.

If you would like to rotate at custom intervals, you can use jQuery to manually set the css instead of adding a class. Like this! I have included both jQuery options at the bottom of the answer.

HTML

<div class="rotate">
    <h1>Rotatey text</h1>
</div>

CSS

/* Totally for style */
.rotate {
    background: #F02311;
    color: #FFF;
    width: 200px;
    height: 200px;
    text-align: center;
    font: normal 1em Arial;
    position: relative;
    top: 50px;
    left: 50px;
}

/* The real code */
.rotated {
    -webkit-transform: rotate(45deg);  /* Chrome, Safari 3.1+ */
    -moz-transform: rotate(45deg);  /* Firefox 3.5-15 */
    -ms-transform: rotate(45deg);  /* IE 9 */
    -o-transform: rotate(45deg);  /* Opera 10.50-12.00 */
    transform: rotate(45deg);  /* Firefox 16+, IE 10+, Opera 12.10+ */
}

jQuery

Make sure these are wrapped in $(document).ready

$('.rotate').click(function() {
    $(this).toggleClass('rotated');
});

Custom intervals

var rotation = 0;
$('.rotate').click(function() {
    rotation += 5;
    $(this).css({'-webkit-transform' : 'rotate('+ rotation +'deg)',
                 '-moz-transform' : 'rotate('+ rotation +'deg)',
                 '-ms-transform' : 'rotate('+ rotation +'deg)',
                 'transform' : 'rotate('+ rotation +'deg)'});
});

Show and hide a View with a slide up/down animation

Easiest solution: set android:animateLayoutChanges="true" on the container holding your views.

To put it into some context: If you have a layout like below, all visibility changes to the views in this container will be animated automatically.

<LinearLayout android:id="@+id/container"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true"
    >

    <Views_which_change_visibility>

</LinearLayout>

You can find more details about this on Animating Layout Changes - Android Developer

SQL Server, division returns zero

Simply mutiply the bottom of the division by 1.0 (or as many decimal places as you want)

PRINT @set1 
PRINT @set2 
SET @weight= @set1 / @set2 *1.00000; 
PRINT @weight

Is there a shortcut to make a block comment in Xcode?

UPDATE: Xcode 8 Update

Now with xcode 8 you can do:

? + ? + /

Note: Below method will not work in xcode version => 8

Very simple steps to add Block Comment functionality to any editor of mac OS X

  1. Open Automator
  2. Choose Services
  3. Search Run Shell Script and double click it

Add the below applescript in textarea

awk 'BEGIN{print "/*"}{print $0}END{print "*/"}'

apple script for block comment

  1. Save script as Block Comment

Add a keyboard shortcut

Open System Preference > Keyboard > Shortcuts, add new shortcut by clicking + and right the same name i.e. Block Comment as you given to applescript in the 4th step. Add your Keyboard Shortcut and click Add button.

New keyboard shortcut

Now you should be able to use block comment in Xcode or any other editor, select some text, use your shortcut key to block comment any line of code or right click, the context menu, and the name you gave to this script should show near the bottom.

What is the Linux equivalent to DOS pause?

This function works in both bash and zsh, and ensures I/O to the terminal:

# Prompt for a keypress to continue. Customise prompt with $*
function pause {
  >/dev/tty printf '%s' "${*:-Press any key to continue... }"
  [[ $ZSH_VERSION ]] && read -krs  # Use -u0 to read from STDIN
  [[ $BASH_VERSION ]] && </dev/tty read -rsn1
  printf '\n'
}
export_function pause

Put it in your .{ba,z}shrc for Great Justice!

What is the difference between a cer, pvk, and pfx file?

Windows uses .cer extension for an X.509 certificate. These can be in "binary" (ASN.1 DER), or it can be encoded with Base-64 and have a header and footer applied (PEM); Windows will recognize either. To verify the integrity of a certificate, you have to check its signature using the issuer's public key... which is, in turn, another certificate.

Windows uses .pfx for a PKCS #12 file. This file can contain a variety of cryptographic information, including certificates, certificate chains, root authority certificates, and private keys. Its contents can be cryptographically protected (with passwords) to keep private keys private and preserve the integrity of root certificates.

Windows uses .pvk for a private key file. I'm not sure what standard (if any) Windows follows for these. Hopefully they are PKCS #8 encoded keys. Emmanuel Bourg reports that these are a proprietary format. Some documentation is available.

You should never disclose your private key. These are contained in .pfx and .pvk files.

Generally, you only exchange your certificate (.cer) and the certificates of any intermediate issuers (i.e., the certificates of all of your CAs, except the root CA) with other parties.

How do you add UI inside cells in a google spreadsheet using app script?

Status 2018:

There seems to be no way to place buttons (drawings, images) within cells in a way that would allow them to be linked to Apps Script functions.


This being said, there are some things that you can indeed do:

You can...

You can place images within cells using IMAGE(URL), but they cannot be linked to Apps Script functions.

You can place images within cells and link them to URLs using:
=HYPERLINK("http://example.com"; IMAGE("http://example.com/myimage.png"; 1))

You can create drawings as described in the answer of @Eduardo and they can be linked to Apps Script functions, but they will be stand-alone items that float freely "above" the spreadsheet and cannot be positioned in cells. They cannot be copied from cell to cell and they do not have a row or col position that the script function could read.

Get current cursor position

You get the cursor position by calling GetCursorPos.

POINT p;
if (GetCursorPos(&p))
{
    //cursor position now in p.x and p.y
}

This returns the cursor position relative to screen coordinates. Call ScreenToClient to map to window coordinates.

if (ScreenToClient(hwnd, &p))
{
    //p.x and p.y are now relative to hwnd's client area
}

You hide and show the cursor with ShowCursor.

ShowCursor(FALSE);//hides the cursor
ShowCursor(TRUE);//shows it again

You must ensure that every call to hide the cursor is matched by one that shows it again.

Replace text inside td using jQuery having td containing other elements

How about:

function changeText() {
    $("#demoTable td").each(function () {
       $(this).html().replace("8: Tap on APN and Enter <B>www</B>", "");
    }
}

Convert pyQt UI to python

The question has already been answered, but if you are looking for a shortcut during development, including this at the top of your python script will save you some time but mostly let you forget about actually having to make the conversion.

import os #Used in Testing Script
os.system("pyuic4 -o outputFile.py inpuiFile.ui")

How to output to the console in C++/Windows

There is a good solution

if (AllocConsole() == 0)
{
    // Handle error here. Use ::GetLastError() to get the error.
}

// Redirect CRT standard input, output and error handles to the console window.
FILE * pNewStdout = nullptr;
FILE * pNewStderr = nullptr;
FILE * pNewStdin = nullptr;

::freopen_s(&pNewStdout, "CONOUT$", "w", stdout);
::freopen_s(&pNewStderr, "CONOUT$", "w", stderr);
::freopen_s(&pNewStdin, "CONIN$", "r", stdin);

// Clear the error state for all of the C++ standard streams. Attempting to accessing the streams before they refer
// to a valid target causes the stream to enter an error state. Clearing the error state will fix this problem,
// which seems to occur in newer version of Visual Studio even when the console has not been read from or written
// to yet.
std::cout.clear();
std::cerr.clear();
std::cin.clear();

std::wcout.clear();
std::wcerr.clear();
std::wcin.clear();

How to change an image on click using CSS alone?

some people have suggested the "visited", but the visited links remain in the browsers cache, so the next time your user visits the page, the link will have the second image.. i dont know it that's the desired effect you want. Anyway you coul mix JS and CSS:

<style>
.off{
    color:red;
}
.on{
    color:green;
}
</style>
<a href="" class="off" onclick="this.className='on';return false;">Foo</a>

using the onclick event, you can change (or toggle maybe?) the class name of the element. In this example i change the text color but you could also change the background image.

Good Luck

Why use #define instead of a variable

The #define allows you to establish a value in a header that would otherwise compile to size-greater-than-zero. Your headers should not compile to size-greater-than-zero.

// File:  MyFile.h

// This header will compile to size-zero.
#define TAX_RATE 0.625

// NO:  static const double TAX_RATE = 0.625;
// NO:  extern const double TAX_RATE;  // WHAT IS THE VALUE?

EDIT: As Neil points out in the comment to this post, the explicit definition-with-value in the header would work for C++, but not C.

How to populate HTML dropdown list with values from database

My guess is that you have a problem since you don't close your select-tag after the loop. Could that do the trick?

<select name="owner">
<?php 
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){
echo "<option value=\"owner1\">" . $row['username'] . "</option>";
}
?>
</select>

How to get href value using jQuery?

if the page have one <a> It Works,but,many <a> ,have to use var href = $(this).attr('href');

How to use Google fonts in React.js?

Another option to all of the good answers here is the npm package react-google-font-loader, found here.

The usage is simple:

import GoogleFontLoader from 'react-google-font-loader';

// Somewhere in your React tree:

<GoogleFontLoader
    fonts={[
        {
            font: 'Bungee Inline',
            weights: [400],
        },
    ]}
/>

Then you can just use the family name in your CSS:

body {
    font-family: 'Bungee Inline', cursive;
}

Disclaimer: I'm the author of the react-google-font-loader package.

Delete specific line number(s) from a text file using sed?

You can delete a particular single line with its line number by

sed -i '33d' file

This will delete the line on 33 line number and save the updated file.

Angular2 handling http response

Update alpha 47

As of alpha 47 the below answer (for alpha46 and below) is not longer required. Now the Http module handles automatically the errores returned. So now is as easy as follows

http
  .get('Some Url')
  .map(res => res.json())
  .subscribe(
    (data) => this.data = data,
    (err) => this.error = err); // Reach here if fails

Alpha 46 and below

You can handle the response in the map(...), before the subscribe.

http
  .get('Some Url')
  .map(res => {
    // If request fails, throw an Error that will be caught
    if(res.status < 200 || res.status >= 300) {
      throw new Error('This request has failed ' + res.status);
    } 
    // If everything went fine, return the response
    else {
      return res.json();
    }
  })
  .subscribe(
    (data) => this.data = data, // Reach here if res.status >= 200 && <= 299
    (err) => this.error = err); // Reach here if fails

Here's a plnkr with a simple example.

Note that in the next release this won't be necessary because all status codes below 200 and above 299 will throw an error automatically, so you won't have to check them by yourself. Check this commit for more info.

What is web.xml file and what are all things can I do with it?

  1. No, there isn't anything that should be avoided
  2. The parameters related to performance are not in web.xml they are in the servlet container configuration files (server.xml on tomcat)
  3. No. But the default servlet (mapped in a web.xml at a common location in your servlet container) should preferably disable file listings (so that users don't see the contents of your web folders):

    listings true

Using Bootstrap Tooltip with AngularJS

_x000D_
_x000D_
var app = angular.module('MyApp', ['mgcrea.ngStrap']);  
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.3.15/angular.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.2/angular-strap.min.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-strap/2.1.2/angular-strap.tpl.min.js"></script>_x000D_
_x000D_
<div ng-app="MyApp" class="container" >_x000D_
_x000D_
  <button type="button" _x000D_
          class="btn btn-default" _x000D_
          data-trigger="hover" _x000D_
          data-placement="right"_x000D_
          data-title="Tooltip on right"_x000D_
          bs-tooltip>_x000D_
    MyButton_x000D_
  </button>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Implode an array with JavaScript?

For future reference, if you want to mimic the behaviour of PHP's implode() when no delimiter is specified (literally just join the pieces together), you need to pass an empty string into Javascript's join() otherwise it defaults to using commas as delimiters:

var bits = ['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd'];
alert(bits.join());    // H,e,l,l,o, ,W,o,r,l,d
alert(bits.join(''));  // Hello World

How to convert a Binary String to a base 10 integer in Java

Now you want to do from binary string to Decimal but Afterword, You might be needed contrary method. It's down below.

public static String decimalToBinaryString(int value) {
    String str = "";
    while(value > 0) {
        if(value % 2 == 1) {
            str = "1"+str;
        } else {
            str = "0"+str;
        }
        value /= 2;
    }
    return str;
}

Docker error response from daemon: "Conflict ... already in use by container"

Instead of command: docker run

You should use:

docker start **CONTAINER ID**

because the container is already exist

More info

How do I set the default page of my application in IIS7?

If you want to do something like,User enter url "www.xxxxxx.com/views/root/" & default page is displayed then I guess you have to set the default/home/welcome page attribute in IIS. But if user just enters "www.xxxxxx.com" and you still want to forward to your url, then you have write a line of code in the default page to forward to your desired url. This default page should be in root directory of your application, so www.xxxxx.com will load www.xxxx.com/index.html which will redirect the user to your desired url

Error 1022 - Can't write; duplicate key in table

As others have mentioned, it's possible that the name for your constraint is already in use by another table in your DB. They must be unique across the database.

A good convention for naming foreign key constraints is:

fk_TableName_ColumnName

To investigate whether there's a possible clash, you can list all constraints used by your database with this query:

SELECT * FROM information_schema.table_constraints WHERE constraint_schema = 'YOUR_DB';

When I ran this query, I discovered I had previously made a temporary copy of a table and this copy was already using the constraint name I was attempting to use.

SQL Server SELECT into existing table

SELECT ... INTO ... only works if the table specified in the INTO clause does not exist - otherwise, you have to use:

INSERT INTO dbo.TABLETWO
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:

INSERT INTO dbo.TABLETWO
  (col1, col2)
SELECT col1, col2
  FROM dbo.TABLEONE
 WHERE col3 LIKE @search_key

MongoDB not equal to

Use $ne instead of $not

http://docs.mongodb.org/manual/reference/operator/ne/#op._S_ne

db.collections.find({"name": {$ne: ""}});

Application Error - The connection to the server was unsuccessful. (file:///android_asset/www/index.html)

Here is the working solution

create a new page main.html

example:

<!doctype html>
<html>
  <head>
   <title>tittle</title>
   <script>
     window.location='./index.html';
   </script>
  </head>
  <body>
  </body>
</html>

change the following in mainactivity.java

super.loadUrl("file:///android_asset/www/index.html");

to

super.loadUrl("file:///android_asset/www/main.html");

Now build your application and it works on any slow connection

refernce.

NOTE: This is a workaround I found in 2013.

How do I "Add Existing Item" an entire directory structure in Visual Studio?

Below is the icon for the 'Show All Files', just for easy reference.

Enter image description here

How to check if curl is enabled or disabled

Its always better to go for a generic reusable function in your project which returns whether the extension loaded. You can use the following function to check -

function isExtensionLoaded($extension_name){
    return extension_loaded($extension_name);
}

Usage

echo isExtensionLoaded('curl');
echo isExtensionLoaded('gd');

How do I use $rootScope in Angular to store variables?

first store the values in $rootScope as

.run(function($rootScope){
$rootScope.myData = {name : "nikhil"}
})

.controller('myCtrl', function($scope) {
var a ="Nikhilesh";
$scope.myData.name = a;
});

.controller('myCtrl2', function($scope) {
var b = $scope.myData.name;
)}

$rootScope is the parent of all $scope, each $scope receives a copy of $rootScope data which you can access using $scope itself.

Why is AJAX returning HTTP status code 0?

We had similar problem - status code 0 on jquery ajax call - and it took us whole day to diagnose it. Since no one had mentioned this reason yet, I thought I'll share.

In our case the problem was HTTP server crash. Some bug in PHP was blowing Apache, so on client end it looked like this:

mirek@toccata:~$ telnet our.server.com 80
Trying 180.153.xxx.xxx...
Connected to our.server.com.
Escape character is '^]'.
GET /test.php HTTP/1.0
Host: our.server.com

Connection closed by foreign host.
mirek@toccata:~$ 

where test.php contained the crashing code. No data returned from the server (not even headers) => ajax call was aborted with status 0.

Twitter API returns error 215, Bad Authentication Data

Here first every one need to use oauth2/token api then use followers/list api.
Other wise you will get this error. Because followers/list api requires Authentication.

In swift (for mobile app) me also got the same problem.

If you want to know the api's and it's parameters follow this link , Get twitter friends list in swift?

Limit String Length

You can use the wordwrap() function then explode on newline and take the first part, if you don't want to split words.

$str = 'Stack Overflow is as frictionless and painless to use as we could make it.';
$str = wordwrap($str, 28);
$str = explode("\n", $str);
$str = $str[0] . '...';

Source: https://stackoverflow.com/a/1104329/1060423

If you don't care about splitting words, then simply use the php substr function.

echo substr($str, 0, 28) . '...';

How can I send emails through SSL SMTP with the .NET Framework?

I know I'm joining late to the discussion, but I think this can be useful to others.

I wanted to avoid deprecated stuff and after a lot of fiddling I found a simple way to send to servers requiring Implicit SSL: use NuGet and add the MailKit package to the project. (I used VS2017 targetting .NET 4.6.2 but it should work on lower .NET versions...)

Then you'll only need to do something like this:

using MailKit.Net.Smtp;
using MimeKit;

var client = new SmtpClient();
client.Connect("server.name", 465, true);

// Note: since we don't have an OAuth2 token, disable the XOAUTH2 authentication mechanism.
client.AuthenticationMechanisms.Remove ("XOAUTH2");

if (needsUserAndPwd)
{
    // Note: only needed if the SMTP server requires authentication
    client.Authenticate (user, pwd);
}

var msg = new MimeMessage();
msg.From.Add(new MailboxAddress("[email protected]"));
msg.To  .Add(new MailboxAddress("[email protected]"));
msg.Subject = "This is a test subject";

msg.Body = new TextPart("plain") {
    Text = "This is a sample message body"
};

client.Send(msg);
client.Disconnect(true);

Of course you can also tweak it to use Explicit SSL or no transport security at all.

Passing multiple values to a single PowerShell script parameter

Parameters take input before arguments. What you should do instead is add a parameter that accepts an array, and make it the first position parameter. ex:

param(
    [Parameter(Position = 0)]
    [string[]]$Hosts,
    [string]$VLAN
    )

foreach ($i in $Hosts)  
{ 
    Do-Stuff $i
}

Then call it like:

.\script.ps1 host1, host2, host3 -VLAN 2

Notice the comma between the values. This collects them in an array

Fast way to discover the row count of a table in PostgreSQL

For SQL Server (2005 or above) a quick and reliable method is:

SELECT SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=OBJECT_ID('MyTableName')   
AND (index_id=0 or index_id=1);

Details about sys.dm_db_partition_stats are explained in MSDN

The query adds rows from all parts of a (possibly) partitioned table.

index_id=0 is an unordered table (Heap) and index_id=1 is an ordered table (clustered index)

Even faster (but unreliable) methods are detailed here.

How to check if current thread is not main thread

You can try Thread.currentThread().isDaemon()

How to return multiple rows from the stored procedure? (Oracle PL/SQL)

You may use Oracle pipelined functions

Basically, when you would like a PLSQL (or java or c) routine to be the «source» of data -- instead of a table -- you would use a pipelined function.

Simple Example - Generating Some Random Data
How could you create N unique random numbers depending on the input argument?

create type array
as table of number;


create function  gen_numbers(n in number default null)
return array
PIPELINED
as
begin
  for i in 1 .. nvl(n,999999999)
  loop
     pipe row(i);
 end loop;
 return;
end;

Suppose we needed three rows for something. We can now do that in one of two ways:

select * from TABLE(gen_numbers(3));

COLUMN_VALUE


       1
       2
       3

or

select * from TABLE(gen_numbers)
 where rownum <= 3;

COLUMN_VALUE


       1
       2
       3

pipelied Functions1 pipelied Functions2

Get the element triggering an onclick event in jquery?

If you don't want to pass the clicked on element to the function through a parameter, then you need to access the event object that is happening, and get the target from that object. This is most easily done if you bind the click event like this:

$('#sendButton').click(function(e){
    var SendButton = $(e.target);
    var TheForm = SendButton.parents('form');
    TheForm.submit();

    return false;
});

Start an external application from a Google Chrome Extension?

I go for hypothesys since I can't verify now.

With Apache, if you make a php script on your local machine calling your executable, and then call this script via POST or GET via html/javascript?

would it function?

let me know.

Bootstrap Element 100% Width

I would use two separate 'container' div as below:

<div class="container">
   /* normal*/
</div>
<div class="container-fluid">
   /*full width container*/
</div>

Bare in mind that container-fluid does not follow your breakpoints and it is a full width container.

Determine if a cell (value) is used in any formula

Have you tried Tools > Formula Auditing?

How can I select the first day of a month in SQL?

Here we can use below query to the first date of the month and last date of the month.

SELECT DATEADD(DAY,1,EOMONTH(Getdate(),-1)) as 'FD',Cast(Getdate()-1 as Date)
as 'LD'

Maximum and minimum values in a textbox

https://jsfiddle.net/co1z0qg0/141/

<input type="text">
<script>
$('input').on('keyup', function() {
    var val = parseInt($(this).val()),
        max = 100;

    val = isNaN(val) ? 0 : Math.max(Math.min(val, max), 0);
    $(this).val(val);
});
</script>

or better

https://jsfiddle.net/co1z0qg0/142/

<input type="number" max="100">
<script>
$(function() {
    $('input[type="number"]').on('keyup', function() {
        var el = $(this),
            val = Math.max((0, el.val())),
            max = parseInt(el.attr('max'));

        el.val(isNaN(max) ? val : Math.min(max, val));
  });
});
</script>
<style>
input[type="number"]::-webkit-outer-spin-button,
input[type="number"]::-webkit-inner-spin-button {
    -webkit-appearance: none;
    margin: 0;
}
input[type="number"] {
    -moz-appearance: textfield;
}
</style>

How to view the committed files you have not pushed yet?

git diff HEAD origin/master

Where origin is the remote repository and master is the default branch where you will push. Also, do a git fetch before the diff so that you are not diffing against a stale origin/master.

P.S. I am also new to git, so in case the above is wrong, please rectify.

How to print_r $_POST array?

The foreach loops work just fine, but you can also simply

print_r($_POST);

Or for pretty printing in a browser:

echo "<pre>";
print_r($_POST);
echo "</pre>";

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

As I experienced whenever I add a new file to my project, I got to stop and restarting the ng server.

Apache HttpClient Interim Error: NoHttpResponseException

Nowadays, most HTTP connections are considered persistent unless declared otherwise. However, to save server ressources the connection is rarely kept open forever, the default connection timeout for many servers is rather short, for example 5 seconds for the Apache httpd 2.2 and above.

The org.apache.http.NoHttpResponseException error comes most likely from one persistent connection that was closed by the server.

It's possible to set the maximum time to keep unused connections open in the Apache Http client pool, in milliseconds.

With Spring Boot, one way to achieve this:

public class RestTemplateCustomizers {
    static public class MaxConnectionTimeCustomizer implements RestTemplateCustomizer {

        @Override
        public void customize(RestTemplate restTemplate) {
            HttpClient httpClient = HttpClientBuilder
                .create()
                .setConnectionTimeToLive(1000, TimeUnit.MILLISECONDS)
                .build();

            restTemplate.setRequestFactory(
                new HttpComponentsClientHttpRequestFactory(httpClient));
        }
    }
}

// In your service that uses a RestTemplate
public MyRestService(RestTemplateBuilder builder ) {
    restTemplate = builder
         .customizers(new RestTemplateCustomizers.MaxConnectionTimeCustomizer())
         .build();
}

This certificate has an invalid issuer Apple Push Services

In Apple's Developer's portal, add a new certificate, and when asked "What type of certificate do you need?" choose "WorldWide developer relations certificate". Generate the new certificate, download and install. The moment you do that, you will no longer see the message you have described.

Edit:
The certificate can be downloaded from the following page: https://www.apple.com/certificateauthority/ You can choose one of the following two certificates: "WWDR Certificate (Expiring 02/07/23)" or "WWDR Certificate (Expiring 02/14/16)"

How to make primary key as autoincrement for Room Persistence lib

Its unbelievable after so many answers, but I did it little differently in the end. I don't like primary key to be nullable, I want to have it as first argument and also want to insert without defining it and also it should not be var.

@Entity(tableName = "employments")
data class Employment(
    @PrimaryKey(autoGenerate = true) val id: Long,
    @ColumnInfo(name = "code") val code: String,
    @ColumnInfo(name = "title") val name: String
){
    constructor(code: String, name: String) : this(0, code, name)
}

R memory management / cannot allocate vector of size n Mb

Here is a presentation on this topic that you might find interesting:

http://www.bytemining.com/2010/08/taking-r-to-the-limit-part-ii-large-datasets-in-r/

I haven't tried the discussed things myself, but the bigmemory package seems very useful

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

Horizontal swipe slider with jQuery and touch devices support?

I have made somthink like this for one of my website accualy in developpement.

I have used StepCarousel for the caroussel because it's the only one I found that can accept different image size in the same carrousel.

In addition to this to add the touch swipe effect, I have used jquery.touchswipe plugin;

And stepcarousel move panel rigth or left with a fonction so I can make :

$("#slider-actu").touchwipe({
    wipeLeft: function() {stepcarousel.stepBy('slider-actu', 3);},
    wipeRight: function() {stepcarousel.stepBy('slider-actu', -3);},
    min_move_x: 20
});

You can view the actual render at this page

Hope that help you.

base64 encoded images in email signatures

Recently I had the same problem to include QR image/png in email. The QR image is a byte array which is generated using ZXing. We do not want to save it to a file because saving/reading from a file is too expensive (slow). So both of the answers above do not work for me. Here's what I did to solve this problem:

import javax.mail.util.ByteArrayDataSource;
import org.apache.commons.mail.ImageHtmlEmail;
...
ImageHtmlEmail email = new ImageHtmlEmail();
byte[] qrImageBytes = createQRCode(); // get your image byte array
ByteArrayDataSource qrImageDataSource = new ByteArrayDataSource(qrImageBytes, "image/png");
String contentId = email.embed(qrImageDataSource, "QR Image");

Let's say the contentId is "111122223333", then your HTML part should have this:

<img src="cid: 111122223333">

There's no need to convert the byte array to Base64 because Commons Mail does the conversion for you automatically. Hope this helps.

How to import popper.js?

I really don't understand why Javascript world trying to do thing more complicated. Why not just download and include in html? Trying to have something like Maven in Java? But we have to manually include it in html anyway? So, what is the point? Maybe someday I will understand but not now.

This is how I can get it

  • download & install NodeJs
  • run "npm install popper.js --save"
  • then I get this message

    [email protected] added 1 package in 1.215s

  • then where is "add package" ? very informative , right? I found it in my C:\Users\surasin\node_modules\popper.js\dist

Hope this help

Bind event to right mouse click

Is contextmenu an event?

I would use onmousedown or onclick then grab the MouseEvent's button property to determine which button was pressed (0 = left, 1 = middle, 2 = right).

How can I get the UUID of my Android phone in an application?

Instead of getting IMEI from TelephonyManager use ANDROID_ID.

Settings.Secure.ANDROID_ID

This works for each android device irrespective of having telephony.

.Contains() on a list of custom class objects

By default reference types have reference equality (i.e. two instances are only equal if they are the same object).

You need to override Object.Equals (and Object.GetHashCode to match) to implement your own equality. (And it is then good practice to implement an equality, ==, operator.)

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

I was having the exact same error in my development environment. In the end all I needed to do in order to fix it was to add:

config.assets.manifest = Rails.root.join("public/assets")

to my config/environments/development.rb file and it fixed it. My final config in development related to assets looks like:

config.assets.compress = false  
config.assets.precompile += %w[bootstrap-alerts.js] #Lots of other space separated files
config.assets.compile = false
config.assets.digest = true
config.assets.manifest = Rails.root.join("public/assets")
config.assets.debug = true

Reading a registry key in C#

string InstallPath = (string)Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\MyApplication\AppPath", "Installed", null);    
if (InstallPath != null)
{
    // Do stuff
}

That code should get your value. You'll need to be

using Microsoft.Win32;

for that to work though.

Reversing a linked list in Java, recursively

Here is C# version of Reverse for linklist.

    public void Reverse()
    {
        Node currentNode, nextNode=null, prevNode=null;
        currentNode = head;
        while(currentNode!=null)
        {
            nextNode = currentNode.next;
            currentNode.next = prevNode;
            prevNode = currentNode;
            currentNode = nextNode;
        }
        head = prevNode;
    }  

Best practices for SQL varchar column length

VARCHAR(255) and VARCHAR(2) take exactly the same amount of space on disk! So the only reason to limit it is if you have a specific need for it to be smaller. Otherwise make them all 255.

Specifically, when doing sorting, larger column do take up more space, so if that hurts performance, then you need to worry about it and make them smaller. But if you only ever select 1 row from that table, then you can just make them all 255 and it won't matter.

See: What are the optimum varchar sizes for MySQL?

LDAP Authentication using Java

Following Code authenticates from LDAP using pure Java JNDI. The Principle is:-

  1. First Lookup the user using a admin or DN user.
  2. The user object needs to be passed to LDAP again with the user credential
  3. No Exception means - Authenticated Successfully. Else Authentication Failed.

Code Snippet

public static boolean authenticateJndi(String username, String password) throws Exception{
    Properties props = new Properties();
    props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
    props.put(Context.SECURITY_PRINCIPAL, "uid=adminuser,ou=special users,o=xx.com");//adminuser - User with special priviledge, dn user
    props.put(Context.SECURITY_CREDENTIALS, "adminpassword");//dn user password


    InitialDirContext context = new InitialDirContext(props);

    SearchControls ctrls = new SearchControls();
    ctrls.setReturningAttributes(new String[] { "givenName", "sn","memberOf" });
    ctrls.setSearchScope(SearchControls.SUBTREE_SCOPE);

    NamingEnumeration<javax.naming.directory.SearchResult> answers = context.search("o=xx.com", "(uid=" + username + ")", ctrls);
    javax.naming.directory.SearchResult result = answers.nextElement();

    String user = result.getNameInNamespace();

    try {
        props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        props.put(Context.PROVIDER_URL, "ldap://LDAPSERVER:PORT");
        props.put(Context.SECURITY_PRINCIPAL, user);
        props.put(Context.SECURITY_CREDENTIALS, password);

   context = new InitialDirContext(props);
    } catch (Exception e) {
        return false;
    }
    return true;
}

How to "comment-out" (add comment) in a batch/cmd?

Putting comments on the same line with commands: use & :: comment

color C          & :: set red font color
echo IMPORTANT INFORMATION
color            & :: reset the color to default

Explanation:

& separates two commands, so in this case color C is the first command and :: set red font color is the second one.


Important:

This statement with comment looks intuitively correct:

goto error1         :: handling the error

but it is not a valid use of the comment. It works only because goto ignores all arguments past the first one. The proof is easy, this goto will not fail either:

goto error1 handling the error

But similar attempt

color 17            :: grey on blue

fails executing the command due to 4 arguments unknown to the color command: ::, grey, on, blue.

It will only work as:

color 17     &      :: grey on blue

So the ampersand is inevitable.

increase font size of hyperlink text html

There is a way simpler way. You put the href in a paragraph just created for that href. For example:

HREF name

Creating a byte array from a stream

While Jon's answer is correct, he is rewriting code that already exists in CopyTo. So for .Net 4 use Sandip's solution, but for previous version of .Net use Jon's answer. Sandip's code would be improved by use of "using" as exceptions in CopyTo are, in many situations, quite likely and would leave the MemoryStream not disposed.

public static byte[] ReadFully(Stream input)
{
    using (MemoryStream ms = new MemoryStream())
    {
        input.CopyTo(ms);
        return ms.ToArray();
    }
}

Can you put two conditions in an xslt test attribute?

Maybe this is a no-brainer for the xslt-professional, but for me at beginner/intermediate level, this got me puzzled. I wanted to do exactly the same thing, but I had to test a responsetime value from an xml instead of a plain number. Following this thread, I tried this:

<xsl:when test="responsetime/@value &gt;= 5000 and responsetime/@value &lt;= 8999"> 

which generated an error. This works:

<xsl:when test="number(responsetime/@value) &gt;= 5000 and number(responsetime/@value) &lt;= 8999">

Don't really understand why it doesn't work without number(), though. Could it be that without number() the value is treated as a string and you can't compare numbers with a string?

Anyway, hope this saves someone a lot of searching...

Remove multiple items from a Python list in just one statement

I'm reposting my answer from here because I saw it also fits in here. It allows removing multiple values or removing only duplicates of these values and returns either a new list or modifies the given list in place.


def removed(items, original_list, only_duplicates=False, inplace=False):
    """By default removes given items from original_list and returns
    a new list. Optionally only removes duplicates of `items` or modifies
    given list in place.
    """
    if not hasattr(items, '__iter__') or isinstance(items, str):
        items = [items]

    if only_duplicates:
        result = []
        for item in original_list:
            if item not in items or item not in result:
                result.append(item)
    else:
        result = [item for item in original_list if item not in items]

    if inplace:
        original_list[:] = result
    else:
        return result

Docstring extension:

"""
Examples:
---------

    >>>li1 = [1, 2, 3, 4, 4, 5, 5]
    >>>removed(4, li1)
       [1, 2, 3, 5, 5]
    >>>removed((4,5), li1)
       [1, 2, 3]
    >>>removed((4,5), li1, only_duplicates=True)
       [1, 2, 3, 4, 5]

    # remove all duplicates by passing original_list also to `items`.:
    >>>removed(li1, li1, only_duplicates=True)
      [1, 2, 3, 4, 5]

    # inplace:
    >>>removed((4,5), li1, only_duplicates=True, inplace=True)
    >>>li1
        [1, 2, 3, 4, 5]

    >>>li2 =['abc', 'def', 'def', 'ghi', 'ghi']
    >>>removed(('def', 'ghi'), li2, only_duplicates=True, inplace=True)
    >>>li2
        ['abc', 'def', 'ghi']
"""

You should be clear about what you really want to do, modify an existing list, or make a new list with the specific items missing. It's important to make that distinction in case you have a second reference pointing to the existing list. If you have, for example...

li1 = [1, 2, 3, 4, 4, 5, 5]
li2 = li1
# then rebind li1 to the new list without the value 4
li1 = removed(4, li1)
# you end up with two separate lists where li2 is still pointing to the 
# original
li2
# [1, 2, 3, 4, 4, 5, 5]
li1
# [1, 2, 3, 5, 5]

This may or may not be the behaviour you want.

How do you subtract Dates in Java?

Well you can remove the third calendar instance.

GregorianCalendar c1 = new GregorianCalendar();
GregorianCalendar c2 = new GregorianCalendar();
c1.set(2000, 1, 1);
c2.set(2010,1, 1);
c2.add(GregorianCalendar.MILLISECOND, -1 * c1.getTimeInMillis());

Combining CSS Pseudo-elements, ":after" the ":last-child"

You can combine pseudo-elements! Sorry guys, I figured this one out myself shortly after posting the question. Maybe it's less commonly used because of compatibility issues.

li:last-child:before { content: "and "; }

li:last-child:after { content: "."; }

This works swimmingly. CSS is kind of amazing.

Why is a ConcurrentModificationException thrown and how to debug it

This is not a synchronization problem. This will occur if the underlying collection that is being iterated over is modified by anything other than the Iterator itself.

Iterator it = map.entrySet().iterator();
while (it.hasNext())
{
   Entry item = it.next();
   map.remove(item.getKey());
}

This will throw a ConcurrentModificationException when the it.hasNext() is called the second time.

The correct approach would be

   Iterator it = map.entrySet().iterator();
   while (it.hasNext())
   {
      Entry item = it.next();
      it.remove();
   }

Assuming this iterator supports the remove() operation.

How do I export html table data as .csv file?

The following solution can do it.

_x000D_
_x000D_
$(function() {_x000D_
  $("button").on('click', function() {_x000D_
    var data = "";_x000D_
    var tableData = [];_x000D_
    var rows = $("table tr");_x000D_
    rows.each(function(index, row) {_x000D_
      var rowData = [];_x000D_
      $(row).find("th, td").each(function(index, column) {_x000D_
        rowData.push(column.innerText);_x000D_
      });_x000D_
      tableData.push(rowData.join(","));_x000D_
    });_x000D_
    data += tableData.join("\n");_x000D_
    $(document.body).append('<a id="download-link" download="data.csv" href=' + URL.createObjectURL(new Blob([data], {_x000D_
      type: "text/csv"_x000D_
    })) + '/>');_x000D_
_x000D_
_x000D_
    $('#download-link')[0].click();_x000D_
    $('#download-link').remove();_x000D_
  });_x000D_
});
_x000D_
table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
td,_x000D_
th {_x000D_
  border: 1px solid #aaa;_x000D_
  padding: 0.5rem;_x000D_
  text-align: left;_x000D_
}_x000D_
_x000D_
td {_x000D_
  font-size: 0.875rem;_x000D_
}_x000D_
_x000D_
.btn-group {_x000D_
  padding: 1rem 0;_x000D_
}_x000D_
_x000D_
button {_x000D_
  background-color: #fff;_x000D_
  border: 1px solid #000;_x000D_
  margin-top: 0.5rem;_x000D_
  border-radius: 3px;_x000D_
  padding: 0.5rem 1rem;_x000D_
  font-size: 1rem;_x000D_
}_x000D_
_x000D_
button:hover {_x000D_
  cursor: pointer;_x000D_
  background-color: #000;_x000D_
  color: #fff;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Name</th>_x000D_
      <th>Author</th>_x000D_
      <th>Description</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>jQuery</td>_x000D_
      <td>John Resig</td>_x000D_
      <td>The Write Less, Do More, JavaScript Library.</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>React</td>_x000D_
      <td>Jordan Walke</td>_x000D_
      <td>React makes it painless to create interactive UIs.</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Vue.js</td>_x000D_
      <td>Yuxi You</td>_x000D_
      <td>The Progressive JavaScript Framework.</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>_x000D_
_x000D_
<div class="btn-group">_x000D_
  <button>csv</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Django error - matching query does not exist

You may try this way. just use a function to get your object

def get_object(self, id):
    try:
        return Comment.objects.get(pk=id)
    except Comment.DoesNotExist:
        return False

When are static variables initialized?

Starting with the code from the other question:

class MyClass {
  private static MyClass myClass = new MyClass();
  private static final Object obj = new Object();
  public MyClass() {
    System.out.println(obj); // will print null once
  }
}

A reference to this class will start initialization. First, the class will be marked as initialized. Then the first static field will be initialized with a new instance of MyClass(). Note that myClass is immediately given a reference to a blank MyClass instance. The space is there, but all values are null. The constructor is now executed and prints obj, which is null.

Now back to initializing the class: obj is made a reference to a new real object, and we're done.

If this was set off by a statement like: MyClass mc = new MyClass(); space for a new MyClass instance is again allocated (and the reference placed in mc). The constructor is again executed and again prints obj, which now is not null.

The real trick here is that when you use new, as in WhatEverItIs weii = new WhatEverItIs( p1, p2 ); weii is immediately given a reference to a bit of nulled memory. The JVM will then go on to initialize values and run the constructor. But if you somehow reference weii before it does so--by referencing it from another thread or or by referencing from the class initialization, for instance--you are looking at a class instance filled with null values.

How to capture a JFrame's close button click event?

This is what I put as a menu option where I made a button on a JFrame to display another JFrame. I wanted only the new frame to be visible, and not to destroy the one behind it. I initially hid the first JFrame, while the new one became visible. Upon closing of the new JFrame, I disposed of it followed by an action of making the old one visible again.

Note: The following code expands off of Ravinda's answer and ng is a JButton:

ng.addActionListener((ActionEvent e) -> {
    setVisible(false);
    JFrame j = new JFrame("NAME");
    j.setVisible(true);
    j.addWindowListener(new java.awt.event.WindowAdapter() {
        @Override
        public void windowClosing(java.awt.event.WindowEvent windowEvent) {
            setVisible(true);
        }
    });
});

How can I convert an Integer to localized month name in Java?

You need to use LLLL for stand-alone month names. this is documented in the SimpleDateFormat documentation, such as:

SimpleDateFormat dateFormat = new SimpleDateFormat( "LLLL", Locale.getDefault() );
dateFormat.format( date );

What is the correct way to create a single-instance WPF application?

From here.

A common use for a cross-process Mutex is to ensure that only instance of a program can run at a time. Here's how it's done:

class OneAtATimePlease {

  // Use a name unique to the application (eg include your company URL)
  static Mutex mutex = new Mutex (false, "oreilly.com OneAtATimeDemo");

  static void Main()
  {
    // Wait 5 seconds if contended – in case another instance
    // of the program is in the process of shutting down.
    if (!mutex.WaitOne(TimeSpan.FromSeconds (5), false))
    {
        Console.WriteLine("Another instance of the app is running. Bye!");
        return;
    }

    try
    {    
        Console.WriteLine("Running - press Enter to exit");
        Console.ReadLine();
    }
    finally
    {
        mutex.ReleaseMutex();
    }    
  }    
}

A good feature of Mutex is that if the application terminates without ReleaseMutex first being called, the CLR will release the Mutex automatically.

Can't subtract offset-naive and offset-aware datetimes

This is a very simple and clear solution
Two lines of code

# First we obtain de timezone info o some datatime variable    

tz_info = your_timezone_aware_variable.tzinfo

# Now we can subtract two variables using the same time zone info
# For instance
# Lets obtain the Now() datetime but for the tz_info we got before

diff = datetime.datetime.now(tz_info)-your_timezone_aware_variable

Conclusion: You must mange your datetime variables with the same time info

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

The canvas element provides a toDataURL method which returns a data: URL that includes the base64-encoded image data in a given format. For example:

var jpegUrl = canvas.toDataURL("image/jpeg");
var pngUrl = canvas.toDataURL(); // PNG is the default

Although the return value is not just the base64 encoded binary data, it's a simple matter to trim off the scheme and the file type to get just the data you want.

The toDataURL method will fail if the browser thinks you've drawn to the canvas any data that was loaded from a different origin, so this approach will only work if your image files are loaded from the same server as the HTML page whose script is performing this operation.

For more information see the MDN docs on the canvas API, which includes details on toDataURL, and the Wikipedia article on the data: URI scheme, which includes details on the format of the URI you'll receive from this call.

What is the correct JSON content type?

Always try to remember these three content types even though there are many content types. as you may have to use these more frequently.

  • Content-Type: application/json
  • Content-Type: application/xml
  • Content-Type: text/html

Python - add PYTHONPATH during command line module run

You may try this to execute a function inside your script

python -c "import sys; sys.path.append('/your/script/path'); import yourscript; yourscript.yourfunction()"

How to match, but not capture, part of a regex?

Update: Thanks to Germán Rodríguez Herrera!

In javascript try: /123-(apple(?=-)|banana(?=-)|(?!-))-?456/

Remember that the result is in group 1

Debuggex Demo

Test if numpy array contains only zeros

As another answer says, you can take advantage of truthy/falsy evaluations if you know that 0 is the only falsy element possibly in your array. All elements in an array are falsy iff there are not any truthy elements in it.*

>>> a = np.zeros(10)
>>> not np.any(a)
True

However, the answer claimed that any was faster than other options due partly to short-circuiting. As of 2018, Numpy's all and any do not short-circuit.

If you do this kind of thing often, it's very easy to make your own short-circuiting versions using numba:

import numba as nb

# short-circuiting replacement for np.any()
@nb.jit(nopython=True)
def sc_any(array):
    for x in array.flat:
        if x:
            return True
    return False

# short-circuiting replacement for np.all()
@nb.jit(nopython=True)
def sc_all(array):
    for x in array.flat:
        if not x:
            return False
    return True

These tend to be faster than Numpy's versions even when not short-circuiting. count_nonzero is the slowest.

Some input to check performance:

import numpy as np

n = 10**8
middle = n//2
all_0 = np.zeros(n, dtype=int)
all_1 = np.ones(n, dtype=int)
mid_0 = np.ones(n, dtype=int)
mid_1 = np.zeros(n, dtype=int)
np.put(mid_0, middle, 0)
np.put(mid_1, middle, 1)
# mid_0 = [1 1 1 ... 1 0 1 ... 1 1 1]
# mid_1 = [0 0 0 ... 0 1 0 ... 0 0 0]

Check:

## count_nonzero
%timeit np.count_nonzero(all_0) 
# 220 ms ± 8.73 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
%timeit np.count_nonzero(all_1)
# 150 ms ± 4.56 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

### all
# np.all
%timeit np.all(all_1)
%timeit np.all(mid_0)
%timeit np.all(all_0)
# 56.8 ms ± 3.41 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.4 ms ± 1.76 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 55.9 ms ± 2.13 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

# sc_all
%timeit sc_all(all_1)
%timeit sc_all(mid_0)
%timeit sc_all(all_0)
# 44.4 ms ± 2.49 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.7 ms ± 599 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 288 ns ± 6.36 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

### any
# np.any
%timeit np.any(all_0)
%timeit np.any(mid_1)
%timeit np.any(all_1)
# 60.7 ms ± 1.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 60 ms ± 287 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 57.7 ms ± 1.12 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

# sc_any
%timeit sc_any(all_0)
%timeit sc_any(mid_1)
%timeit sc_any(all_1)
# 41.7 ms ± 1.24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 22.4 ms ± 1.51 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# 287 ns ± 12.7 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

* Helpful all and any equivalences:

np.all(a) == np.logical_not(np.any(np.logical_not(a)))
np.any(a) == np.logical_not(np.all(np.logical_not(a)))
not np.all(a) == np.any(np.logical_not(a))
not np.any(a) == np.all(np.logical_not(a))

How to show first commit by 'git log'?

git log $(git log --pretty=format:%H|tail -1)

How to save a list as numpy array in python?

import numpy as np 

... ## other code

some list comprehension

t=[nodel[ nodenext[i][j] ] for j in idx]
            #for each link, find the node lables 
            #t is the list of node labels 

Convert the list to a numpy array using the array method specified in the numpy library.

t=np.array(t)

This may be helpful: https://numpy.org/devdocs/user/basics.creation.html

What is the difference between parseInt(string) and Number(string) in JavaScript?

parseInt(string) will convert a string containing non-numeric characters to a number, as long as the string begins with numeric characters

'10px' => 10

Number(string) will return NaN if the string contains any non-numeric characters

'10px' => NaN

Entity Framework vs LINQ to SQL

Here's some metrics guys... (QUANTIFYING THINGS!!!!)

I took this query where I was using Entity Framework

var result = (from metattachType in _dbContext.METATTACH_TYPE
                join lineItemMetattachType in _dbContext.LINE_ITEM_METATTACH_TYPE on metattachType.ID equals lineItemMetattachType.METATTACH_TYPE_ID
                where (lineItemMetattachType.LINE_ITEM_ID == lineItemId && lineItemMetattachType.IS_DELETED == false
                && metattachType.IS_DELETED == false)
                select new MetattachTypeDto()
                {
                    Id = metattachType.ID,
                    Name = metattachType.NAME
                }).ToList();

and changed it into this where I'm using the repository pattern Linq

            return await _attachmentTypeRepository.GetAll().Where(x => !x.IsDeleted)
                .Join(_lineItemAttachmentTypeRepository.GetAll().Where(x => x.LineItemId == lineItemId && !x.IsDeleted),
                attachmentType => attachmentType.Id,
                lineItemAttachmentType => lineItemAttachmentType.MetattachTypeId,
                (attachmentType, lineItemAttachmentType) => new AttachmentTypeDto
                {
                    Id = attachmentType.Id,
                    Name = attachmentType.Name
                }).ToListAsync().ConfigureAwait(false);

Linq-to-sql

            return (from attachmentType in _attachmentTypeRepository.GetAll()
                    join lineItemAttachmentType in _lineItemAttachmentTypeRepository.GetAll() on attachmentType.Id equals lineItemAttachmentType.MetattachTypeId
                    where (lineItemAttachmentType.LineItemId == lineItemId && !lineItemAttachmentType.IsDeleted && !attachmentType.IsDeleted)
                    select new AttachmentTypeDto()
                    {
                        Id = attachmentType.Id,
                        Name = attachmentType.Name
                    }).ToList();

Also, please know that Linq-to-Sql is 14x faster than Linq...

enter image description here

How to fix missing dependency warning when using useEffect React Hook?

./src/components/BusinessesList.js
Line 51:  React Hook useEffect has a missing dependency: 'fetchBusinesses'.
Either include it or remove the dependency array  react-hooks/exhaustive-deps

It's not JS/React error but eslint (eslint-plugin-react-hooks) warning.

It's telling you that hook depends on function fetchBusinesses, so you should pass it as dependency.

useEffect(() => {
  fetchBusinesses();
}, [fetchBusinesses]);

It could result in invoking function every render if function is declared in component like:

const Component = () => {
  /*...*/

  //new function declaration every render
  const fetchBusinesses = () => {
    fetch('/api/businesses/')
      .then(...)
  }

  useEffect(() => {
    fetchBusinesses();
  }, [fetchBusinesses]);

  /*...*/
}

because every time function is redeclared with new reference

Correct way of doing this stuff is:

const Component = () => {
  /*...*/

  // keep function reference
  const fetchBusinesses = useCallback(() => {
    fetch('/api/businesses/')
      .then(...)
  }, [/* additional dependencies */]) 

  useEffect(() => {
    fetchBusinesses();
  }, [fetchBusinesses]);

  /*...*/
}

or just defining function in useEffect

More: https://github.com/facebook/react/issues/14920

java : convert float to String and String to float

I believe the following code will help:

float f1 = 1.23f;
String f1Str = Float.toString(f1);      
float f2 = Float.parseFloat(f1Str);

How to create query parameters in Javascript?

This should do the job:

const createQueryParams = params => 
      Object.keys(params)
            .map(k => `${k}=${encodeURI(params[k])}`)
            .join('&');

Example:

const params = { name : 'John', postcode: 'W1 2DL'}
const queryParams = createQueryParams(params)

Result:

name=John&postcode=W1%202DL

Does Python have a string 'contains' substring method?

in Python strings and lists

Here are a few useful examples that speak for themselves concerning the in method:

"foo" in "foobar"
True

"foo" in "Foobar"
False

"foo" in "Foobar".lower()
True

"foo".capitalize() in "Foobar"
True

"foo" in ["bar", "foo", "foobar"]
True

"foo" in ["fo", "o", "foobar"]
False

["foo" in a for a in ["fo", "o", "foobar"]]
[False, False, True]

Caveat. Lists are iterables, and the in method acts on iterables, not just strings.

How can I make a multipart/form-data POST request using Java?

We have a pure java implementation of multipart-form submit without using any external dependencies or libraries outside jdk. Refer https://github.com/atulsm/https-multipart-purejava/blob/master/src/main/java/com/atul/MultipartPure.java

private static String body = "{\"key1\":\"val1\", \"key2\":\"val2\"}";
private static String subdata1 = "@@ -2,3 +2,4 @@\r\n";
private static String subdata2 = "<data>subdata2</data>";

public static void main(String[] args) throws Exception{        
    String url = "https://" + ip + ":" + port + "/dataupload";
    String token = "Basic "+ Base64.getEncoder().encodeToString((userName+":"+password).getBytes());

    MultipartBuilder multipart = new MultipartBuilder(url,token);       
    multipart.addFormField("entity", "main", "application/json",body);
    multipart.addFormField("attachment", "subdata1", "application/octet-stream",subdata1);
    multipart.addFormField("attachment", "subdata2", "application/octet-stream",subdata2);        
    List<String> response = multipart.finish();         
    for (String line : response) {
        System.out.println(line);
    }
}

What is the difference between "expose" and "publish" in Docker?

Most people use docker compose with networks. The documentation states:

The Docker network feature supports creating networks without the need to expose ports within the network, for detailed information see the overview of this feature).

Which means that if you use networks for communication between containers you don't need to worry about exposing ports.

how to set default method argument values?

You can overload the method with different parameters:

public int doSomething(int arg1, int arg2)
{
//some logic here
        return 0;
}

public int doSomething(
{
doSomething(0,0)
}

Compare 2 arrays which returns difference

The short version can be like this:

const diff = (a, b) => b.filter((i) => a.indexOf(i) === -1);

result:

diff(['a', 'b'], ['a', 'b', 'c', 'd']);

["c", "d"]

Iterating over every property of an object in javascript using Prototype?

You have to first convert your object literal to a Prototype Hash:

// Store your object literal
var obj = {foo: 1, bar: 2, barobj: {75: true, 76: false, 85: true}}

// Iterate like so.  The $H() construct creates a prototype-extended Hash.
$H(obj).each(function(pair){
  alert(pair.key);
  alert(pair.value);
});

How to sort strings in JavaScript

var str = ['v','a','da','c','k','l']
var b = str.join('').split('').sort().reverse().join('')
console.log(b)

How to use Javascript to read local text file and read line by line?

Using ES6 the javascript becomes a little cleaner

handleFiles(input) {

    const file = input.target.files[0];
    const reader = new FileReader();

    reader.onload = (event) => {
        const file = event.target.result;
        const allLines = file.split(/\r\n|\n/);
        // Reading line by line
        allLines.forEach((line) => {
            console.log(line);
        });
    };

    reader.onerror = (event) => {
        alert(event.target.error.name);
    };

    reader.readAsText(file);
}

Is background-color:none valid CSS?

So, I would like to explain the scenario where I had to make use of this solution. Basically, I wanted to undo the background-color attribute set by another CSS. The expected end result was to make it look as though the original CSS had never applied the background-color attribute . Setting background-color:transparent; made that effective.

Evaluate empty or null JSTL c tags

to also check blank string, I suggest following

<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<c:if test="${empty fn:trim(var1)}">

</c:if>

It also handles nulls

How to use the start command in a batch file?

An extra pair of rabbits' ears should do the trick.

start "" "C:\Program...

START regards the first quoted parameter as the window-title, unless it's the only parameter - and any switches up until the executable name are regarded as START switches.

mysql - move rows from one table to another

    INSERT INTO Persons_Table (person_id, person_name,person_email)
          SELECT person_id, customer_name, customer_email
          FROM customer_table
          WHERE "insert your where clause here";
    DELETE FROM customer_table
          WHERE "repeat your where clause here";

How to convert index of a pandas dataframe into a column?

either:

df['index1'] = df.index

or, .reset_index:

df.reset_index(level=0, inplace=True)

so, if you have a multi-index frame with 3 levels of index, like:

>>> df
                       val
tick       tag obs        
2016-02-26 C   2    0.0139
2016-02-27 A   2    0.5577
2016-02-28 C   6    0.0303

and you want to convert the 1st (tick) and 3rd (obs) levels in the index into columns, you would do:

>>> df.reset_index(level=['tick', 'obs'])
          tick  obs     val
tag                        
C   2016-02-26    2  0.0139
A   2016-02-27    2  0.5577
C   2016-02-28    6  0.0303

JQuery / JavaScript - trigger button click from another button click event

You mean this:

jQuery("input.first").click(function(){
   jQuery("input.second").trigger('click');
   return false;
});

When should one use a spinlock instead of mutex?

Using spinlocks on a single-core/single-CPU system makes usually no sense, since as long as the spinlock polling is blocking the only available CPU core, no other thread can run and since no other thread can run, the lock won't be unlocked either. IOW, a spinlock wastes only CPU time on those systems for no real benefit

This is wrong. There is no wastage of cpu cycles in using spinlocks on uni processor systems, because once a process takes a spin lock , preemption is disabled , so as such, there could be no one else spinning! It's just that using it doesn't make any sense! Hence, spinlocks on Uni systems are replaced by preempt_disable at compile time by the kernel!

CSS: Position loading indicator in the center of the screen

Worked for me in angular 4

by adding style="margin:0 auto;"

<mat-progress-spinner
  style="margin:0 auto;"
  *ngIf="isLoading"
  mode="indeterminate">
  </mat-progress-spinner>

Get top first record from duplicate records having no unique identity

Find all products that has been ordered 1 or more times... (kind of duplicate records)

SELECT DISTINCT * from [order_items] where productid in 
(SELECT productid 
  FROM [order_items]
  group by productid 
  having COUNT(*)>0)
order by productid 

To select the last inserted of those...

SELECT DISTINCT productid, MAX(id) OVER (PARTITION BY productid) AS LastRowId from [order_items] where productid in 
(SELECT productid 
  FROM [order_items]
  group by productid 
  having COUNT(*)>0)
order by productid 

JavaScript: How to pass object by value?

Using the spread operator like obj2 = { ...obj1 } Will have same values but different references

Google Forms file upload complete example

Update: Google Forms can now upload files. This answer was posted before Google Forms had the capability to upload files.

This solution does not use Google Forms. This is an example of using an Apps Script Web App, which is very different than a Google Form. A Web App is basically a website, but you can't get a domain name for it. This is not a modification of a Google Form, which can't be done to upload a file.

NOTE: I did have an example of both the UI Service and HTML Service, but have removed the UI Service example, because the UI Service is deprecated.

NOTE: The only sandbox setting available is now IFRAME. I you want to use an onsubmit attribute in the beginning form tag: <form onsubmit="myFunctionName()">, it may cause the form to disappear from the screen after the form submission.

If you were using NATIVE mode, your file upload Web App may no longer be working. With NATIVE mode, a form submission would not invoke the default behavior of the page disappearing from the screen. If you were using NATIVE mode, and your file upload form is no longer working, then you may be using a "submit" type button. I'm guessing that you may also be using the "google.script.run" client side API to send data to the server. If you want the page to disappear from the screen after a form submission, you could do that another way. But you may not care, or even prefer to have the page stay on the screen. Depending upon what you want, you'll need to configure the settings and code a certain way.

If you are using a "submit" type button, and want to continue to use it, you can try adding event.preventDefault(); to your code in the submit event handler function. Or you'll need to use the google.script.run client side API.


A custom form for uploading files from a users computer drive, to your Google Drive can be created with the Apps Script HTML Service. This example requires writing a program, but I've provide all the basic code here.

This example shows an upload form with Google Apps Script HTML Service.

What You Need

  • Google Account
  • Google Drive
  • Google Apps Script - also called Google Script

Google Apps Script

There are various ways to end up at the Google Apps Script code editor.

I mention this because if you are not aware of all the possibilities, it could be a little confusing. Google Apps Script can be embedded in a Google Site, Sheets, Docs or Forms, or used as a stand alone app.

Apps Script Overview

This example is a "Stand Alone" app with HTML Service.

HTML Service - Create a web app using HTML, CSS and Javascript

Google Apps Script only has two types of files inside of a Project:

  • Script
  • HTML

Script files have a .gs extension. The .gs code is a server side code written in JavaScript, and a combination of Google's own API.

  • Copy and Paste the following code

  • Save It

  • Create the first Named Version

  • Publish it

  • Set the Permissions

    and you can start using it.

Start by:

  • Create a new Blank Project in Apps Script
  • Copy and Paste in this code:

Upload a file with HTML Service:

Code.gs file (Created by Default)

//For this to work, you need a folder in your Google drive named:
// 'For Web Hosting'
// or change the hard coded folder name to the name of the folder
// you want the file written to

function doGet(e) {
  return HtmlService.createTemplateFromFile('Form')
    .evaluate() // evaluate MUST come before setting the Sandbox mode
    .setTitle('Name To Appear in Browser Tab')
    .setSandboxMode();//Defaults to IFRAME which is now the only mode available
}

function processForm(theForm) {
  var fileBlob = theForm.picToLoad;
  
  Logger.log("fileBlob Name: " + fileBlob.getName())
  Logger.log("fileBlob type: " + fileBlob.getContentType())
  Logger.log('fileBlob: ' + fileBlob);

  var fldrSssn = DriveApp.getFolderById(Your Folder ID);
    fldrSssn.createFile(fileBlob);
    
  return true;
}

Create an html file:

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body>
    <h1 id="main-heading">Main Heading</h1>
    <br/>
    <div id="formDiv">

      <form id="myForm">
    
        <input name="picToLoad" type="file" /><br/>
        <input type="button" value="Submit" onclick="picUploadJs(this.parentNode)" />
          
      </form>
    </div>


  <div id="status" style="display: none">
  <!-- div will be filled with innerHTML after form submission. -->
  Uploading. Please wait...
</div>

</body>
<script>

function picUploadJs(frmData) {

  document.getElementById('status').style.display = 'inline';

  google.script.run
    .withSuccessHandler(updateOutput)
    .processForm(frmData)
};
  // Javascript function called by "submit" button handler,
  // to show results.
  
  function updateOutput() {
  
    var outputDiv = document.getElementById('status');
    outputDiv.innerHTML = "The File was UPLOADED!";
  }

</script>
</html>

This is a full working example. It only has two buttons and one <div> element, so you won't see much on the screen. If the .gs script is successful, true is returned, and an onSuccess function runs. The onSuccess function (updateOutput) injects inner HTML into the div element with the message, "The File was UPLOADED!"

  • Save the file, give the project a name
  • Using the menu: File, Manage Version then Save the first Version
  • Publish, Deploy As Web App then Update

When you run the Script the first time, it will ask for permissions because it's saving files to your drive. After you grant permissions that first time, the Apps Script stops, and won't complete running. So, you need to run it again. The script won't ask for permissions again after the first time.

The Apps Script file will show up in your Google Drive. In Google Drive you can set permissions for who can access and use the script. The script is run by simply providing the link to the user. Use the link just as you would load a web page.

Another example of using the HTML Service can be seen at this link here on StackOverflow:

File Upload with HTML Service

NOTES about deprecated UI Service:

There is a difference between the UI Service, and the Ui getUi() method of the Spreadsheet Class (Or other class) The Apps Script UI Service was deprecated on Dec. 11, 2014. It will continue to work for some period of time, but you are encouraged to use the HTML Service.

Google Documentation - UI Service

Even though the UI Service is deprecated, there is a getUi() method of the spreadsheet class to add custom menus, which is NOT deprecated:

Spreadsheet Class - Get UI method

I mention this because it could be confusing because they both use the terminology UI.

The UI method returns a Ui return type.

You can add HTML to a UI Service, but you can't use a <button>, <input> or <script> tag in the HTML with the UI Service.

Here is a link to a shared Apps Script Web App file with an input form:

Shared File - Contact Form

How to get screen width and height

Try via context.getResources().getDisplayMetrics() if you have a context available.

splitting a number into the integer and decimal parts

If you don't mind using NumPy, then:

In [319]: real = np.array([1234.5678])

In [327]: integ, deci = int(np.floor(real)), np.asscalar(real % 1)

In [328]: integ, deci
Out[328]: (1234, 0.5678000000000338)

How to prevent Google Colab from disconnecting?

Using python selenium

from selenium.webdriver.common.keys import Keys
from selenium import webdriver
import time   

driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver')

notebook_url = ''
driver.get(notebook_url)

# run all cells
driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.F9)
time.sleep(5)

# click to stay connected
start_time = time.time()
current_time = time.time()
max_time = 11*59*60 #12hours

while (current_time - start_time) < max_time:
    webdriver.ActionChains(driver).send_keys(Keys.ESCAPE).perform()
    driver.find_element_by_xpath('//*[@id="top-toolbar"]/colab-connect-button').click()
    time.sleep(30)
    current_time = time.time()

What is *.o file?

Ink-Jet is right. More specifically, an .o (.obj) -- or object file is a single source file compiled in to machine code (I'm not sure if the "machine code" is the same or similar to an executable machine code). Ultimately, it's an intermediate between an executable program and plain-text source file.

The linker uses the o files to assemble the file executable.

Wikipedia may have more detailed information. I'm not sure how much info you'd like or need.

Python 2.7: %d, %s, and float()

See String Formatting Operations:

%d is the format code for an integer. %f is the format code for a float.

%s prints the str() of an object (What you see when you print(object)).

%r prints the repr() of an object (What you see when you print(repr(object)).

For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
        1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
      1.12

AngularJS multiple filter with custom filter function

Try this:

<tr ng-repeat="player in players | filter:{id: player_id, name:player_name} | filter:ageFilter">

$scope.ageFilter = function (player) {
    return (player.age > $scope.min_age && player.age < $scope.max_age);
}

How can I generate an MD5 hash?

try this:

public static String getHashMD5(String string) {
    try {
        MessageDigest md = MessageDigest.getInstance("MD5");
        BigInteger bi = new BigInteger(1, md.digest(string.getBytes()));
        return bi.toString(16);
    } catch (NoSuchAlgorithmException ex) {
        Logger.getLogger(MD5Utils.class
                .getName()).log(Level.SEVERE, null, ex);

        return "";
    }
}

How to find all duplicate from a List<string>?

If you are using LINQ, you can use the following query:

var duplicateItems = from x in list
                     group x by x into grouped
                     where grouped.Count() > 1
                     select grouped.Key;

or, if you prefer it without the syntactic sugar:

var duplicateItems = list.GroupBy(x => x).Where(x => x.Count() > 1).Select(x => x.Key);

This groups all elements that are the same, and then filters to only those groups with more than one element. Finally it selects just the key from those groups as you don't need the count.

If you're prefer not to use LINQ, you can use this extension method:

public void SomeMethod {
    var duplicateItems = list.GetDuplicates();
    …
}

public static IEnumerable<T> GetDuplicates<T>(this IEnumerable<T> source) {
    HashSet<T> itemsSeen = new HashSet<T>();
    HashSet<T> itemsYielded = new HashSet<T>();

    foreach (T item in source) {
        if (!itemsSeen.Add(item)) {
            if (itemsYielded.Add(item)) {
                yield return item;
            }
        }
    }
}

This keeps track of items it has seen and yielded. If it hasn't seen an item before, it adds it to the list of seen items, otherwise it ignores it. If it hasn't yielded an item before, it yields it, otherwise it ignores it.

iOS: Compare two dates

NSDate actually represents a time interval in seconds since a reference date (1st Jan 2000 UTC I think). Internally, a double precision floating point number is used so two arbitrary dates are highly unlikely to compare equal even if they are on the same day. If you want to see if a particular date falls on a particular day, you probably need to use NSDateComponents. e.g.

NSDateComponents* dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear: 2011];
[dateComponents setMonth: 5];
[dateComponents setDay: 24];
/*
 *  Construct two dates that bracket the day you are checking.  
 *  Use the user's current calendar.  I think this takes care of things like daylight saving time.
 */
NSCalendar* calendar = [NSCalendar currentCalendar];
NSDate* startOfDate = [calendar dateFromComponents: dateComponents];
NSDateComponents* oneDay = [[NSDateComponents alloc] init];
[oneDay setDay: 1];
NSDate* endOfDate = [calendar dateByAddingComponents: oneDay toDate: startOfDate options: 0];
/*
 *  Compare the date with the start of the day and the end of the day.
 */
NSComparisonResult startCompare = [startOfDate compare: myDate];
NSComparisonResult endCompare = [endOfDate compare: myDate];

if (startCompare != NSOrderedDescending && endCompare == NSOrderedDescending)
{
    // we are on the right date
} 

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

Simon's answer and Volcano's together explain what you're doing wrong, and Simon explains how you can fix it by redesigning your interface.

But if you really need to read 1 character, and then later read 1 line, you can do that. It's not trivial, and it's different on Windows vs. everything else.

There are actually three cases: a Unix tty, a Windows DOS prompt, or a regular file (redirected file/pipe) on either platform. And you have to handle them differently.

First, to check if stdin is a tty (both Windows and Unix varieties), you just call sys.stdin.isatty(). That part is cross-platform.

For the non-tty case, it's easy. It may actually just work. If it doesn't, you can just read from the unbuffered object underneath sys.stdin. In Python 3, this just means sys.stdin.buffer.raw.read(1) and sys.stdin.buffer.raw.readline(). However, this will get you encoded bytes, rather than strings, so you will need to call .decode(sys.stdin.decoding) on the results; you can wrap that all up in a function.

For the tty case on Windows, however, input will still be line buffered even on the raw buffer. The only way around this is to use the Console I/O functions instead of normal file I/O. So, instead of stdin.read(1), you do msvcrt.getwch().

For the tty case on Unix, you have to set the terminal to raw mode instead of the usual line-discipline mode. Once you do that, you can use the same sys.stdin.buffer.read(1), etc., and it will just work. If you're willing to do that permanently (until the end of your script), it's easy, with the tty.setraw function. If you want to return to line-discipline mode later, you'll need to use the termios module. This looks scary, but if you just stash the results of termios.tcgetattr(sys.stdin.fileno()) before calling setraw, then do termios.tcsetattr(sys.stdin.fileno(), TCSAFLUSH, stash), you don't have to learn what all those fiddly bits mean.

On both platforms, mixing console I/O and raw terminal mode is painful. You definitely can't use the sys.stdin buffer if you've ever done any console/raw reading; you can only use sys.stdin.buffer.raw. You could always replace readline by reading character by character until you get a newline… but if the user tries to edit his entry by using backspace, arrows, emacs-style command keys, etc., you're going to get all those as raw keypresses, which you don't want to deal with.

How does Tomcat locate the webapps directory?

Find server.xml at $CATALINA_BASE/conf/server.xml

Find appBase attribute in <Host> element

by default it will be something like : <Host name="localhost" appBase="webapps ...>

Change appBase to your required path. There are different way people put it, but I use

/c:/myfolder/newwebapps

Remember, no slash at the end, but at start. Also note it's direction as well.

Closing WebSocket correctly (HTML5, Javascript)

Very simple, you close it :)

var myWebSocket = new WebSocket("ws://example.org"); 
myWebSocket.send("Hello Web Sockets!"); 
myWebSocket.close();

Did you check also the following site And check the introduction article of Opera

How to set up datasource with Spring for HikariCP?

I have recently migrated from C3P0 to HikariCP in a Spring and Hibernate based project and it was not as easy as I had imagined and here I am sharing my findings.

For Spring Boot see my answer here

I have the following setup

  • Spring 4.3.8+
  • Hiberante 4.3.8+
  • Gradle 2.x
  • PostgreSQL 9.5

Some of the below configs are similar to some of the answers above but, there are differences.

Gradle stuff

In order to pull in the right jars, I needed to pull in the following jars

//latest driver because *brettw* see https://github.com/pgjdbc/pgjdbc/pull/849
compile 'org.postgresql:postgresql:42.2.0'
compile('com.zaxxer:HikariCP:2.7.6') {
    //they are pulled in separately elsewhere
    exclude group: 'org.hibernate', module: 'hibernate-core'
}

// Recommended to use HikariCPConnectionProvider by Hibernate in 4.3.6+    
compile('org.hibernate:hibernate-hikaricp:4.3.8.Final') {
        //they are pulled in separately elsewhere, to avoid version conflicts
        exclude group: 'org.hibernate', module: 'hibernate-core'
        exclude group: 'com.zaxxer', module: 'HikariCP'
}

// Needed for HikariCP logging if you use log4j
compile('org.slf4j:slf4j-simple:1.7.25')  
compile('org.slf4j:slf4j-log4j12:1.7.25') {
    //log4j pulled in separately, exclude to avoid version conflict
    exclude group: 'log4j', module: 'log4j'
}

Spring/Hibernate based configs

In order to get Spring & Hibernate to make use of Hikari Connection pool, you need to define the HikariDataSource and feed it into sessionFactory bean as shown below.

<!-- HikariCP Database bean -->
<bean id="dataSource" class="com.zaxxer.hikari.HikariDataSource" destroy-method="close">
    <constructor-arg ref="hikariConfig" />
</bean>

<!-- HikariConfig config that is fed to above dataSource -->
<bean id="hikariConfig" class="com.zaxxer.hikari.HikariConfig">
        <property name="poolName" value="SpringHikariPool" />
        <property name="dataSourceClassName" value="org.postgresql.ds.PGSimpleDataSource" />
        <property name="maximumPoolSize" value="20" />
        <property name="idleTimeout" value="30000" />

        <property name="dataSourceProperties">
            <props>
                <prop key="serverName">localhost</prop>
                <prop key="portNumber">5432</prop>
                <prop key="databaseName">dbname</prop>
                <prop key="user">dbuser</prop>
                <prop key="password">dbpassword</prop>
            </props>
        </property>
</bean>

<bean class="org.springframework.orm.hibernate4.LocalSessionFactoryBean" id="sessionFactory">
        <!-- Your Hikari dataSource below -->
        <property name="dataSource" ref="dataSource"/>
        <!-- your other configs go here -->
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.connection.provider_class">org.hibernate.hikaricp.internal.HikariCPConnectionProvider</prop>
                <!-- Remaining props goes here -->
            </props>
        </property>
 </bean>

Once the above are setup then, you need to add an entry to your log4j or logback and set the level to DEBUG to see Hikari Connection Pool start up.

Log4j1.2

<!-- Keep additivity=false to avoid duplicate lines -->
<logger additivity="false" name="com.zaxxer.hikari">
    <level value="debug"/>
    <!-- Your appenders goes here -->
</logger>

Logback

Via application.properties in Spring Boot

debug=true
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG 

Using logback.xml

<logger name="com.zaxxer.hikari" level="DEBUG" additivity="false">
    <appender-ref ref="STDOUT" />
</logger>

With the above you should be all good to go! Obviously you need to customize the HikariCP pool configs in order to get the performance that it promises.

Create a folder and sub folder in Excel VBA

Never tried with non Windows systems, but here's the one I have in my library, pretty easy to use. No special library reference required.

Function CreateFolder(ByVal sPath As String) As Boolean
'by Patrick Honorez - www.idevlop.com
'create full sPath at once, if required
'returns False if folder does not exist and could NOT be created, True otherwise
'sample usage: If CreateFolder("C:\toto\test\test") Then debug.print "OK"
'updated 20130422 to handle UNC paths correctly ("\\MyServer\MyShare\MyFolder")

    Dim fs As Object 
    Dim FolderArray
    Dim Folder As String, i As Integer, sShare As String

    If Right(sPath, 1) = "\" Then sPath = Left(sPath, Len(sPath) - 1)
    Set fs = CreateObject("Scripting.FileSystemObject")
    'UNC path ? change 3 "\" into 3 "@"
    If sPath Like "\\*\*" Then
        sPath = Replace(sPath, "\", "@", 1, 3)
    End If
    'now split
    FolderArray = Split(sPath, "\")
    'then set back the @ into \ in item 0 of array
    FolderArray(0) = Replace(FolderArray(0), "@", "\", 1, 3)
    On Error GoTo hell
    'start from root to end, creating what needs to be
    For i = 0 To UBound(FolderArray) Step 1
        Folder = Folder & FolderArray(i) & "\"
        If Not fs.FolderExists(Folder) Then
            fs.CreateFolder (Folder)
        End If
    Next
    CreateFolder = True
hell:
End Function

SQL Server 2008 - IF NOT EXISTS INSERT ELSE UPDATE

At first glance your original attempt seems pretty close. I'm assuming that clockDate is a DateTime fields so try this:

IF (NOT EXISTS(SELECT * FROM Clock WHERE cast(clockDate as date) = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE Cast(clockDate AS Date) = '08/10/2012' AND userName = 'test'
END 

Note that getdate gives you the current date. If you are trying to compare to a date (without the time) you need to cast or the time element will cause the compare to fail.


If clockDate is NOT datetime field (just date), then the SQL engine will do it for you - no need to cast on a set/insert statement.

IF (NOT EXISTS(SELECT * FROM Clock WHERE clockDate = '08/10/2012') 
    AND userName = 'test') 
BEGIN 
    INSERT INTO Clock(clockDate, userName, breakOut) 
    VALUES(GetDate(), 'test', GetDate()) 
END 
ELSE 
BEGIN 
    UPDATE Clock 
    SET breakOut = GetDate()
    WHERE clockDate = '08/10/2012' AND userName = 'test'
END 

As others have pointed out, the merge statement is another way to tackle this same logic. However, in some cases, especially with large data sets, the merge statement can be prohibitively slow, causing a lot of tran log activity. So knowing how to logic it out as shown above is still a valid technique.

Which browser has the best support for HTML 5 currently?

Seems that new browsers support most of the tags: <header>, <section> etc. For older browsers (IE, Fx2, Camino etc) then you can use this to allow styling of these tags:

document.createElement('header');

Would make these older browsers allow CSS styling of a header tag, instead of just ignoring it.

This means that you can now use the new tags without any loss of functionality, which is a good start!

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

I was facing the same issue. So, i created a stored Procedure and defined the size like @FromDate datetime, @ToDate datetime, @BL varchar(50)

After defining the size in @BL varchar(50), i did not face any problem. Now it is working fine

Why does .json() return a promise?

Also, what helped me understand this particular scenario that you described is the Promise API documentation, specifically where it explains how the promised returned by the then method will be resolved differently depending on what the handler fn returns:

if the handler function:

  • returns a value, the promise returned by then gets resolved with the returned value as its value;
  • throws an error, the promise returned by then gets rejected with the thrown error as its value;
  • returns an already resolved promise, the promise returned by then gets resolved with that promise's value as its value;
  • returns an already rejected promise, the promise returned by then gets rejected with that promise's value as its value.
  • returns another pending promise object, the resolution/rejection of the promise returned by then will be subsequent to the resolution/rejection of the promise returned by the handler. Also, the value of the promise returned by then will be the same as the value of the promise returned by the handler.

How do you setLayoutParams() for an ImageView?

An ImageView gets setLayoutParams from View which uses ViewGroup.LayoutParams. If you use that, it will crash in most cases so you should use getLayoutParams() which is in View.class. This will inherit the parent View of the ImageView and will work always. You can confirm this here: ImageView extends view

Assuming you have an ImageView defined as 'image_view' and the width/height int defined as 'thumb_size'

The best way to do this:

ViewGroup.LayoutParams iv_params_b = image_view.getLayoutParams();
iv_params_b.height = thumb_size;
iv_params_b.width = thumb_size;
image_view.setLayoutParams(iv_params_b);

PHP GuzzleHttp. How to make a post request with params?

Since Marco's answer is deprecated, you must use the following syntax (according jasonlfunk's comment) :

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
    'form_params' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ]
]);

Request with POST files

$response = $client->request('POST', 'http://www.example.com/files/post', [
    'multipart' => [
        [
            'name'     => 'file_name',
            'contents' => fopen('/path/to/file', 'r')
        ],
        [
            'name'     => 'csv_header',
            'contents' => 'First Name, Last Name, Username',
            'filename' => 'csv_header.csv'
        ]
    ]
]);

REST verbs usage with params

// PUT
$client->put('http://www.example.com/user/4', [
    'body' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ],
    'timeout' => 5
]);

// DELETE
$client->delete('http://www.example.com/user');

Async POST data

Usefull for long server operations.

$client = new \GuzzleHttp\Client();
$promise = $client->requestAsync('POST', 'http://www.example.com/user/create', [
    'form_params' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ]
]);
$promise->then(
    function (ResponseInterface $res) {
        echo $res->getStatusCode() . "\n";
    },
    function (RequestException $e) {
        echo $e->getMessage() . "\n";
        echo $e->getRequest()->getMethod();
    }
);

Set headers

According to documentation, you can set headers :

// Set various headers on a request
$client->request('GET', '/get', [
    'headers' => [
        'User-Agent' => 'testing/1.0',
        'Accept'     => 'application/json',
        'X-Foo'      => ['Bar', 'Baz']
    ]
]);

More information for debugging

If you want more details information, you can use debug option like this :

$client = new \GuzzleHttp\Client();
$response = $client->request('POST', 'http://www.example.com/user/create', [
    'form_params' => [
        'email' => '[email protected]',
        'name' => 'Test user',
        'password' => 'testpassword',
    ],
    // If you want more informations during request
    'debug' => true
]);

Documentation is more explicits about new possibilities.

Property 'value' does not exist on type 'Readonly<{}>'

interface MyProps {
  ...
}

interface MyState {
  value: string
}

class App extends React.Component<MyProps, MyState> {
  ...
}

// Or with hooks, something like

const App = ({}: MyProps) => {
  const [value, setValue] = useState<string>('');
  ...
};

type's are fine too like in @nitzan-tomer's answer, as long as you're consistent.

Python JSON encoding

So, simplejson.loads takes a json string and returns a data structure, which is why you are getting that type error there.

simplejson.dumps(data) comes back with

'[["apple", "cat"], ["banana", "dog"], ["pear", "fish"]]'

Which is a json array, which is what you want, since you gave this a python array.

If you want to get an "object" type syntax you would instead do

>>> data2 = {'apple':'cat', 'banana':'dog', 'pear':'fish'}
>>> simplejson.dumps(data2)
'{"pear": "fish", "apple": "cat", "banana": "dog"}'

which is javascript will come out as an object.

JWT refresh token flow

Below are the steps to do revoke your JWT access token:

  1. When you do log in, send 2 tokens (Access token, Refresh token) in response to the client.
  2. The access token will have less expiry time and Refresh will have long expiry time.
  3. The client (Front end) will store refresh token in his local storage and access token in cookies.
  4. The client will use an access token for calling APIs. But when it expires, pick the refresh token from local storage and call auth server API to get the new token.
  5. Your auth server will have an API exposed which will accept refresh token and checks for its validity and return a new access token.
  6. Once the refresh token is expired, the User will be logged out.

Please let me know if you need more details, I can share the code (Java + Spring boot) as well.

For your questions:

Q1: It's another JWT with fewer claims put in with long expiry time.

Q2: It won't be in a database. The backend will not store anywhere. They will just decrypt the token with private/public key and validate it with its expiry time also.

Q3: Yes, Correct

How does the Python's range function work?

The range function wil give you a list of numbers, while the for loop will iterate through the list and execute the given code for each of its items.

for i in range(5):
      print i

This simply executes print i five times, for i ranging from 0 to 4.

for i in range(5):
      a=i+1

This will execute a=i+1 five times. Since you are overwriting the value of a on each iteration, at the end you will only get the value for the last iteration, that is 4+1.

Useful links:
http://www.network-theory.co.uk/docs/pytut/rangeFunction.html
http://www.ibiblio.org/swaroopch/byteofpython/read/for-loop.html