text:
Q: Check if website is live or not one by one with real time result using jquery I have a php code that checks if an url is live or not.
while(urls exist) {
check(each url);
}

Let's say that you input a list of urls on a form to check them, when I procced with the checker (using curl and a while loop) what the code does is check all of them one by one and then display all the result data at the same time. So if there are too many urls it takes a lot of time loading without showing results, and then BUM, all the results!!
What I want is implement jQuery or something to check the first url and inmediatly display result, then the next url and so on. Like this:
    Checking (2 of 200)
    Live!
    Live!
    Checking...

Can anyone help me with this or link to a tutorial, I couldn't find anything related, just how to submit forms with jQuery Ajax... Thanks!
Extra question: Any way to make this multithreading like:
Live!
Live!
Checking...
Checking...
Checking...

A: If you want to check a server is available from the browser, the best is to make HEAD requests (no content downloaded) :
$.ajax({
    type: "HEAD",
    url: 'https://www.google.com',
    success : function() {
       alert('my server is alive !');
    }, error: function() {
        alert('world is gone !');
    }
});

Of course, as those requests are asynchronous, they'll be automatically parallelized (the exact number of really parallel request is browser dependant).


text:
Q: Package listed under depends does not install when I rebuild a custom R Package I'm rebuilding a custom R package which has, among other libraries, RcppArmadillo in the Depends row of the DESCRIPTION file.
I am running R 3.5.1.  When I rebuild the package in RStudio, I get an error:
ERROR: dependency 'RcppArmadillo' is not available for package 'custom package name'

According to the R Packages book, packages under Depends/Imports must be installed when the package is rebuilt.

A: Solution
Use devtools::install() instead.
Explanation
According the RStudio website,

The Build and Reload command performs several steps in sequence to ensure a clean and correct result:
      1.Unloads any existing version of the package (including shared libraries ifnecessary).
      2.Builds and installs the package using R CMD INSTALL.
      3.Restarts the underlying R session to ensure a clean environment for re-loading the package.
      4.Reloads the package in the new R session by executing the library function.

While devtools::install() will install dependencies for you -- from help("install.packages"):

Uses R CMD INSTALL to install the package. Will also try to install
  dependencies of the package from CRAN, if they're not already
  installed.

(emphasis added) this is not the case for R CMD INSTALL alone (see ?INSTALL from R or R CMD INSTALL --help from the command line, etc. -- there is no mention of installing required dependencies).
So, it appears the language

In fact, any time your package is installed, those packages will, if
  not already present, be installed on your computer
  (devtools::load_all() also checks that the packages are installed).

from Hadley's R Packages is a little specific; it does not pertain to using R CMD INSTALL (which RStudio's build function apparently uses), but does work for devtools::install(). It's a matter of personal taste, but honestly I highly recommend using devtools in your package development workflow.
Example
I removed the package rbenchmark from my system via
remove.packages("rbenchmark")

then created a dummy package by
devtools::create("SOexample", rstudio = FALSE)

and edited the DESCRIPTION to put rbenchmark in Imports, so that SOexample depends on it. I added the following code in R/hello_world.R:
hello_world <- function() print("Hello, world!")

I tried R CMD INSTALL, but got the error

*installing to library '/home/duckmayr/R/x86_64-pc-linux-gnu-library/3.5'
  ERROR: dependency 'rbenchmark' is not available for package 'SOexample'
  *removing '/home/duckmayr/R/x86_64-pc-linux-gnu-library/3.5/SOexample'

But, if I try devtools::install():
> devtools::install("SOexample/")
Installing SOexample
trying URL 'https://cloud.r-project.org/src/contrib/rbenchmark_1.0.0.tar.gz'
Content type 'application/x-gzip' length 5093 bytes
==================================================
downloaded 5093 bytes

Installing rbenchmark
'/usr/lib/R/bin/R' --no-site-file --no-environ --no-save --no-restore --quiet  \
  CMD INSTALL '/tmp/RtmpA0NOMe/devtools723832018149/rbenchmark'  \
  --library='/home/duckmayr/R/x86_64-pc-linux-gnu-library/3.5' --install-tests

* installing *source* package 'rbenchmark' ...
** package 'rbenchmark' successfully unpacked and MD5 sums checked
** R
** demo
** byte-compile and prepare package for lazy loading
** help
*** installing help indices
** building package indices
** testing if installed package can be loaded
* DONE (rbenchmark)
'/usr/lib/R/bin/R' --no-site-file --no-environ --no-save --no-restore --quiet  \
  CMD INSTALL '/home/duckmayr/SOexample'  \
  --library='/home/duckmayr/R/x86_64-pc-linux-gnu-library/3.5' --install-tests

* installing *source* package 'SOexample' ...
** R
** byte-compile and prepare package for lazy loading
** help
No man pages found in package  'SOexample'
*** installing help indices
** building package indices
** testing if installed package can be loaded
* DONE (SOexample)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Simple MDX Calculated Member In my simple cube, I have a measure = \[Measure\].\[Salary\], I have also \[DimEmpployee\].\[EmployeeLastName\].\[Smith\]. I would like to create calculated measure, where I can display in Axis 0 two measures - \[Measure\].\[Salary\] and calculated measure \[Measure\].\[SmithsSalaries\], to compare difference between Smith's earnings vs Total Salary.

I would like to compare Measure.SmithSalaries with other measures accross all diemensions. Is it possible to create such a measure using SCOPE statement?
I was playing around SCOPE statements, but it was displaying results only if DimEmployee was selected. I am looking for something which is running in blocks to avoid performance issues.

A: I think you only need a simple calculated measure.
CREATE MEMBER CURRENTCUBE.[Measures].[SmithSalaries]
 AS ([DimEmployee].[EmployeeLastName].[Smith], [Measures].[Salary]),
VISIBLE = 1  ;

After that you can combine that with you total salary for example to get a ratio.
CREATE MEMBER CURRENTCUBE.[Measures].[SmithSalaries Ratio]
 AS DIVIDE(([DimEmployee].[EmployeeLastName].[Smith], [Measures].[Salary]),[Measures].[Salary])
VISIBLE = 1  ;

SCOPE allows you to have different behaviors when different combinations of Dimensions are into play, like returning a different calculation when the DimEmployee is selected but otherwise just return the normal calculation. Like a Very efficient IF condition to check what are in the Axis of this calculation.


text:
Q: How do I handle invalid URI in POCO I want to handle a invalid URI client request in createRequestHandler(HTTPServerRequest& request) function in subclassed HTTPRequestHandlerFactory.
I want to send response that the URI is invalid with error code

HTTP_NOT_FOUND ( 404 ).

RequestHandler * RequestHandlerFactory::createRequestHandler(const Poco::Net::HTTPServerRequest& request)
{
  // -- handleRequest --

  if ( request.getURI() != ExpectedURI )
  {
    // How do I send response to client that the URI is invalid?
    // Example I need to send HTTP_NOT_FOUND
  }
}

A: void sendErrorResponse(HTTPResponse::HTTPStatus status, const std::string& message)
{
    response().setStatusAndReason(status);
    std::string statusAndReason(NumberFormatter::format(static_cast<int>(response().getStatus())));
    statusAndReason += " - ";
    statusAndReason += response().getReason();
    std::string page("<TITLE>");
    page += statusAndReason;
    page += "</TITLE>
";
    page += statusAndReason;
    page += "
";
    page += "
";
    page += message;
    page += "
";
    response().sendBuffer(page.data(), page.size());
}

if (request.getURI() != ExpectedURI)
{
    sendErrorResponse(HTTPResponse::HTTP_NOT_FOUND, request.getURI());
}


text:
Q: Does Go support type casting/conversion for functions? I am writing a library named "GoRequest" which wraps around net/http package and is meant for making an easy http client.
Now, I am having a problem with function conversion which has similar types as its parameters. Here is my problem snippet.
type Request *http.Request
type Response *http.Response

func (s *SuperAgent) RedirectPolicy(policy func(req Request, via []Request) error) *SuperAgent {
   s.Client.CheckRedirect = policy
   return s
}

s.Client.CheckRedirect is a member in http.Client struct and should receive func(req *http.Request, via []*http.Request) error
As you might see, I want to convert func(req Request, via []Request) error --> func(req *http.Request, via []*http.Request) which has similar types of parameters.
But it returns me an error:
./main.go:142: cannot use policy (type func(Request, []Request) error) as type func(*http.Request, []*http.Request) error in assignment

I cannot find any document for this kind of conversion and if it's possible, please suggest.
If not, please suggest some other good way to do this. Thanks!

A: Can't you just wrap policy in an anonymous function that would do the conversion for you? Something like this:
func (s *SuperAgent) RedirectPolicy(policy func(req Request, via []Request) error) *SuperAgent {
   s.Client.CheckRedirect = func(r *http.Request, v []*http.Request) error {
       return policy(Request(r), []Request(v))
   }
   return s
}

I'm not actually sure you can convert the []*http.Request slice to a []Request, but if not, you could create a temporary slice and do the interface conversion one by one:
func (s *SuperAgent) RedirectPolicy(policy func(req Request, via []Request) error) *SuperAgent {
   s.Client.CheckRedirect = func(r *http.Request, v []*http.Request) error {
       vv := make([]Request, len(v))
       for i, r := range v {
           vv[i] = Request(r)
       }
       return policy(Request(r), vv)
   }
   return s
}

That should do it.


text:
Q: getting error message in terminal I have created script to check jar process is running or not, if not it will send mail. After executing it sends the mail if the process is not running.
#!/bin/sh

check_if_running()
{
   echo "Checking to make sure push processor is running"
   determine_push_pid
   if [ "$PID" != "" ]
   then
      echo "Found push processor running under process ID {$PID}"
   else
      echo "Can't determine process ID for push processor, "
    #   start_push_processor
      send_email "There is no process running on :-> $BOXNAME"
   fi
}

determine_push_pid()
{
   PID=`ps -ef | grep ams_services | grep java | grep -v DupdateProfiles | awk -F' ' ' { print $2 } '`
   if [ "$PID" != "" ]
   then
      echo "Process ID for push processor is {$PID}"
   fi
}

start_push_processor()
{
   echo "Starting push processor"
   nohup java -Dspring.profiles.active=dev -Xms2G -Xmx2G -jar #$JARFILE & 1>>$LOGFILE 2>>$echoFILE
   echo "Sleeping for $SLEEPSECONDS seconds"
   sleep $SLEEPSECONDS
   determine_push_pid
   if [ "$PID" == "" ]
   then
      echo "Can't determine new process ID for push processor, did it start?"
      send_email "Tried to start push processor, but couldn't on $BOXNAME"
   else
      echo "New PID for push processor is {$PID}"
   fi
}

send_email()
{
   DATA=$(cat <<EOF
   {
           "occurrenceTime":"$DATE",
           "systemIdentity":
                   {
                           "ip":"$IP"
                   },
           "eventType":"36c170f1-1338-4346-9d5b-737841a22166",
           "shortDesc":"Roster Alignment Alert !!",
           "properties":
                   {
                           "description":"$*",
                           "env":"$OPS_ENVIRONMENT",
                           "hostname":"$HOSTNAME"
                   }
   }
EOF
   )
     ### echo "$*"
   echo "$*" | mail -s "Roster Alignement Process Warning !!! " roster@mail.com
   echo "### Exiting with error after sending email"
   exit 1
}

SCRIPTNAME="Roster_Service.sh"
PROGNAME="ams_services"
IP=`/sbin/ifconfig  | grep 'inet addr:'| grep -v '127.0.0.1' | cut -d: -f2 | awk '{ print $1}'`
BOXNAME="$OPS_CI_NAME ($OPS_ENVIRONMENT) ($IP)"
ENV=$OPS_ENVIRONMENT
SLEEPSECONDS=5
ACTIVITYSECONDS=600
CURTIME=$(date +%s)
TIMEDIFF=$(expr $CURTIME - $FILETIME)
JARFILE=""
P='%'
SCRIPTPID=$$
PID=""
DATE=`date +%s`
HOSTNAME=`hostname`
check_if_running
exit 0

but after running the script getting below syntax error message in terminal.
expr: syntax error
### Starting Roster_Service.sh in dev
Checking to make sure push processor is running
Can't determine process ID for push processor,
### Exiting with error after sending email

Can anyone explain where and what thing am missing.


text:
Q: How Handle multiple customers in a single grails application with customised look and feel? My app needs to support multiple customers at run time. They will all be displaying the same data, using the same controllers, services but with different layouts, css and images.
My basic idea is as follows:
1) Have a filter to authenticate and set a config value in the session
2) My controller code will call something along these lines:
render(view:"/${session.userContext}/test/test")
So for customer1  we will render: views/customer1/test/test.gsp
Ideally I would like to have the all custom views and layouts in the /views/customer1/ directory but site mesh looks for layouts in the /views/layouts directory and I can't find a way around this. In this sense the solution is a wee bit clunky as I don't get the level of isolation I want.
What would be ideal is if I could set the root of the grails render method at runtime e.g. instead of starting at views, look in views/customer1 alas I have no idea how to do this but his seems like the smartest solution.
Any help would be massivly appreciated.
Cheers,
Gav

A: I would recommend to look into creating a subclass of GrailsLayoutDecoratorMapper.  Since you have access to the full HttpServletRequest, you can render a different view depending on how you differentiate one customer from another (domain, session variable, etc.).  If you can't determine a proper view/layout for the current request, you can simply delegate to GrailsLayoutDecoratorMapper to keep the default behavior.
To configure a custom DecoratorMapper, you need to modify /web-app/WEB-INF/sitemesh.xml and replace the default <mapper class="org.codehaus.groovy.grails.web.sitemesh.GrailsLayoutDecoratorMapper" />with your custom implementaion.

A: Checkout the Multi-Tenant plugin - It looks like it can help you through the rest of your app as well.
You'll have to handle specifying the layouts from the controller, by passing in the layout name ->  <meta name="layout" content="$layoutName">  I don't think You'd be able to get Grails to isolate your layouts without overriding the default Layout Decorator Mappings bean.


text:
Q: Except a modal from closing when click on a link Following these intructions does what I need but what if I want to except/prevend some of the modals from following this rule?
$(".modal a").click(function(){ $(this).closest(".modal").modal("hide");});

A: Give all the modals that you want to exclude a class, like class="noclose". Then add that to the selector.
$(".modal:not(.noclose) a").click(function(){
    $(this).closest(".modal").modal("hide");
});


text:
Q: Should there be a delay for close votes? This question was closed only five minutes after it was asked. Sure this was not a good quality question.
But there was not a real chance to put comments on it, the asker had not even a chance to fix his question.
So shouldn't there be a delay (say one hour) until the question can be closed?

A: There's no need for a delay; that's just delaying the inevitable.
Suppose there was a delay; the OP wouldn't know there was a problem until an extra hour later.
More to the point, with the recent changes to question closing, the first 5 days of a question being closed shows the question as "on hold", not closed.
The specific close reason chosen gives a detailed description of the problem, so the OP can improve their question.
In the case of the specific question you linked to, it's a prime example of a good question to close. It shows no effort to solve the problem, shows no code that's been tried, is extremely vague and unclear, and basically says "give me c0dez".
Also, when a question is closed, it isn't closed forever. There is always the opportunity to reopen it. Furthermore, after a question is closed, if the OP edits it, it automatically enters the Reopen review queue as a candidate to reopen.
Overall, I don't see any point in adding a delay.


text:
Q: Proving that the Grünwald–Letnikov differintegral is homomorphic: deriving single limit from repeated limit I'm trying to prove that the Grünwald–Letnikov differintegral is homomorphic over addition i.e. it composes as expected:
$${}^{GL}_{x_0}\mathbb{D}^a \circ {}^{GL}_{x_0}\mathbb{D}^{b} = {}^{GL}_{x_0}\mathbb{D}^{a+b}$$
Before we start, note that some sources seem to use an "indefinite" version of the operator:
$${}^{GL}\mathbb{D}^a = {}^{GL}_{-\infty}\mathbb{D}^a$$
The (incomplete) proof below still applies to this version of the operator, effectively replacing all instances of $\sum_{..}^{\lfloor .. \rfloor}$ with $\sum_{..}^{\infty}$.

Definition of the Grünwald–Letnikov differintegral:
\begin{align}
{}^{GL}_{x_0}\mathbb{D}^a_x f(x) & = \lim_{\varepsilon \to 0} \frac{1}{\varepsilon^a} \sum_{j=0}^{\lfloor \frac{x-x_0}{\varepsilon} \rfloor} (-1)^j {a \choose j} f(x-j\varepsilon) \\
\end{align}
The (incomplete) proof goes as follows:
\begin{align}
& \quad\,\, {}^{GL}_{x_0}\mathbb{D}^b_x {}^{GL}_{x_0}\mathbb{D}^a_x f(x) \\
& = \lim_{\delta \to 0} \frac{1}{\delta^b} \sum_{k=0}^{\lfloor \frac{x-x_0}{\delta} \rfloor} (-1)^k {b \choose k} {}^{GL}_{x_0}\mathbb{D}^a_x f(x-k\delta) & \text{expand ${}^{GL}_{x_0}\mathbb{D}^b_x$} \\
& = \lim_{\delta \to 0} \frac{1}{\delta^b} \sum_{k=0}^{\lfloor \frac{x-x_0}{\delta} \rfloor} (-1)^k {b \choose k} \lim_{\varepsilon \to 0} \frac{1}{\varepsilon^a} \sum_{j=0}^{\lfloor \frac{x-k\delta-x_0}{\varepsilon} \rfloor} (-1)^j {a \choose j} f(x-k\delta-j\varepsilon) & \text{expand ${}^{GL}_{x_0}\mathbb{D}^a_x$} \\
& = \lim_{\delta \to 0} \lim_{\varepsilon \to 0} \frac{1}{\delta^b} \frac{1}{\varepsilon^a} \sum_{k=0}^{\lfloor \frac{x-x_0}{\delta} \rfloor} \sum_{j=0}^{\lfloor \frac{x-k\delta-x_0}{\varepsilon} \rfloor} (-1)^k (-1)^j {b \choose k} {a \choose j} f(x-k\delta-j\varepsilon) & \text{push constants into $\lim$ and $\sum$} \\
& = \lim_{\varepsilon \to 0} \frac{1}{\varepsilon^{b+a}} \sum_{k=0}^{\lfloor \frac{x-x_0}{\varepsilon} \rfloor} \sum_{j=0}^{\lfloor \frac{x-x_0}{\varepsilon} \rfloor - k} (-1)^{k+j} {b \choose k} {a \choose j} f(x-(k+j)\varepsilon) & \text{(1), unify $\delta$ and $\varepsilon$} \\
& = \lim_{\varepsilon \to 0} \frac{1}{\varepsilon^{b+a}} \sum_{i=0}^{\lfloor \frac{x-x_0}{\varepsilon} \rfloor} \sum_{k=0}^{i} (-1)^i {b \choose k} {a \choose i-k} f(x-i\varepsilon) & \text{rearrange triangle-sum, over $i = k+j$} \\
& = \lim_{\varepsilon \to 0} \frac{1}{\varepsilon^{b+a}} \sum_{i=0}^{\lfloor \frac{x-x_0}{\varepsilon} \rfloor} (-1)^i {b+a \choose i} f(x-i\varepsilon) & \text{Vandermonde's identity} \\
& = {}^{GL}_{x_0}\mathbb{D}^{b+a}_x f(x)
\end{align}
The missing piece is to justify $(1)$. I never went very deep into analysis, but doing some more digging suggests an initial approach:
\begin{align}
& \quad\,\, \lim_{\delta \to 0} \lim_{\varepsilon \to 0} F(\delta,\varepsilon) \\
& = \lim_{(\delta,\varepsilon) \to (0,0)} F(\delta,\varepsilon) & \text{(2), Moore-Osgood Theorem} \\
& = \lim_{\varepsilon \to 0} F(\varepsilon,\varepsilon) & \text{uniqueness of limits}
\end{align}
$(2)$ applies under certain conditions for $F(\delta,\epsilon)$, but it's unclear if these are valid for our proof above. The definition of ${}^{GL}_{x_0}\mathbb{D}^a$, at the surface level, only assumes that the single limit ($\lim \sum f$) exists, and does not say anything explicit about the behaviour of the repeated limit ($\lim \lim \sum \sum f$), which is what the Moore-Osgood conditions relate to.
In order to complete the proof, my question is: is it possible to derive the conditions for applying Moore-Osgood in $(2)$ from the assumptions of ${}^{GL}_{x_0}\mathbb{D}^a$, or can we justify $(1)$ in some other way?


text:
Q: How to open IPython interpreter in emacs? In order to use IPython during Python development in Emacs, I have been opening up a terminal, and typing ipython. This doesn't seem like the right way to do it.
For one thing, my buffer lists this buffer as *ansi-term*, which is confusing, as I often end up with multiple terminals, one of which is dedicated to Python. I also see that I can open a python interpreter directly with M-x python-shell. It seems like there ought to be a similar option for IPython.
Is there a better way to use the IPython interpreter in Emacs?
I'm using Emacs 24 with Prelude.

A: UPD Detailed instructions for beginners:

*

*Copy this:
(defun ipython ()
    (interactive)
    (term "/usr/bin/ipython"))

*Try first launching Emacs as emacs -q from the terminal.
-q means don't load any customized code. It means that in this mode
your emacs will behave exactly like mine.

*You should now be at the welcome screen. Press q.

*You should now be in the *scratch* buffer. Press C-y to paste
the code you copied from the browser.

*Position your cursor at the very end of the code, right after the last parenthesis.

*Press C-j to evaluate the code. The name ipython pops up.

*Now you can execute this command as any other e.g. M-x ipython.

*If you want this change to become permanent, append the code to your ~/.emacs.

A: I don't know what Prelude is, but if you can install the latest Emacs (i.e, Emacs with Fabian's python-mode included), then you can use the following to let Python mode know your preferred choice of interpreter. Then you just need to call M-x run-python:
--
(when (executable-find "ipython")
  (setq python-shell-interpreter "ipython"))

--

A: Seems a bit late, however was also having similar problem, wanted to have ipython as default python interpreter for my emacs 24.x. The following worked like a magic -
(require 'python)
(setq python-shell-interpreter "ipython")
(setq python-shell-interpreter-args "--pylab")

thanks to http://www.flannaghan.com/2013/08/29/ipython-emacs for saving my day and hopefully yours.
PS: seems having anaconda preinstalled in your system helps...

A: I've tried abo-abo's approach to running ipython inside of emacs.  Its a pretty slick way of shortcutting shell functions within emacs.  However, you do lose emacs functionality when you are in the shell (e.g. can't M-x o out of the shell)
Instead, I personally think that using the Emacs builtin shell command (M-x shell) is much better.  You can run ipython within the Emacs builtin shell and still have all Emacs functionality that we all know and love.

A: Edit: Whoops, the project below is a fork, not the official Prelude project.  The second paragraph here still stands.  Or you could try the fork.
It looks like Prelude already sets up ipython integration.  Maybe your copy is out of date?
If M-x run-python doesn't launch ipython, try adding (setq python-shell-interpreter "ipython") to your init file (or just evaluating it) and running M-x run-python again.  After a quick test without Prelude that seems to be all that is necessary.

A: You can use my Emacs extension called emacs-ipython for this.
https://github.com/burakbayramli/emacs-ipython
In a LaTeX buffer (you can change this to be any buffer) between code blocks with one keystroke it sends the python code to ipython kernel and displays the results in a verbatim block underneath.


text:
Q: How can I modify BluetoothleGatt to enable BLE device scanning on Android 6.0? I am new to Android App developing and BLE, and I am learning these using the sample code BluetoothLeGatt [The one I imported from Android Studio]. The code works fine on my tablet (Android 5.0), but the scan activity does not return any BLE devices on Android 6.0. The error message I got is shown below.
07-19 12:41:39.615 7617-7642/? W/Binder: Caught a RuntimeException from the binder stub implementation.
                                     java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results
                                         at android.os.Parcel.readException(Parcel.java:1599)
                                         at android.os.Parcel.readException(Parcel.java:1552)
                                         at android.bluetooth.IBluetoothGatt$Stub$Proxy.startScan(IBluetoothGatt.java:772)
                                         at android.bluetooth.le.BluetoothLeScanner$BleScanCallbackWrapper.onClientRegistered(BluetoothLeScanner.java:331)
                                         at android.bluetooth.IBluetoothGattCallback$Stub.onTransact(IBluetoothGattCallback.java:56)
                                         at android.os.Binder.execTransact(Binder.java:458)

I looked at the post Bluetooth Low Energy startScan on Android 6.0 does not find devices and the official page Requesting Permissions at Run Time, but I still don't really know how to modify my code.
I did add the permissions of GPS, ACCESS_FINE_LOCATION and ACCESS_COARSE_LOCATION, and I turned on the Location Service on my tablet.
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-feature android:name="android.hardware.location.gps" />

But the App still cannot return any BLE devices. Then, when I try to add the following block of code to my App (from Requesting Permissions at Run Time ), there is always an error on checkSelfPermission [Cannot resolve symbol 'checkSelfPermission']. But I did import import android.support.v4.content.ContextCompat;
Can someone help me with this? Also, is there a simpler answer to the question how to make DeviceScanActivity work?  I don't really know where to put the blocks of the code from Requesting Permissions at Run Time to my code :(  I know this is a really stupid question, but I am really new to this field. Please help me!
// Here, thisActivity is the current activity
if (ContextCompat.checkSelfPermission(thisActivity,
            Manifest.permission.READ_CONTACTS)
    != PackageManager.PERMISSION_GRANTED) {

// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
        Manifest.permission.READ_CONTACTS)) {

    // Show an explanation to the user *asynchronously* -- don't block
    // this thread waiting for the user's response! After the user
    // sees the explanation, try again to request the permission.

} else {

    // No explanation needed, we can request the permission.

    ActivityCompat.requestPermissions(thisActivity,
            new String[]{Manifest.permission.READ_CONTACTS},
            MY_PERMISSIONS_REQUEST_READ_CONTACTS);

    // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an
    // app-defined int constant. The callback method gets the
    // result of the request.
}
}

EDIT
The following is my dependencies block.
dependencies {
compile "com.android.support:support-v4:25.3.1"
compile "com.android.support:support-v13:25.3.1"
compile "com.android.support:cardview-v7:25.3.1"
compile "com.android.support:appcompat-v7:25.3.1"
}

A: Thank you everyone for your responses and help! I've just solved my case!
What I did is that besides adding the permissions in AndroidManifest.xml, I added the following code to my onCreate method in DeviceScanActivity, and the reference I used is Requesting Permissions at Run Time. Also, I just randomly assigned a number to MY_PERMISSIONS_REQUEST_LOCATION.
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getActionBar().setTitle(R.string.title_devices);
        mHandler = new Handler();
    //Check for permissions
        int permissionCheck = ContextCompat.checkSelfPermission(this,
            Manifest.permission.WRITE_CALENDAR);
        Log.e(TAG, "Permission Status: " +permissionCheck );

    //***********************************************************
    //
        if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_COARSE_LOCATION)
            != PackageManager.PERMISSION_GRANTED)
        {

            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_COARSE_LOCATION))
            {

            // Show an explanation to the user *asynchronously* -- don't block
            // this thread waiting for the user's response! After the user
            // sees the explanation, try again to request the permission.

            }
            else
            {

            // No explanation needed, we can request the permission.

            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
                    MY_PERMISSIONS_REQUEST_LOCATION);
            }
        }

    ......//The rest of code
    }

When I first added the above code, there is a pop-up window coming up on my tablet asking me for permissions, and I clicked "allow."
Then, I am able to scan my ble devices.
BTW, it only asks for my permission once. When I clicked "Run Application" later (after slight modifications of my code), it didn't ask for my permission again.

A: Do you add those all permissions:
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>

It works fine on android 6.0


text:
Q: Get the value of a Swift variable from a constructed name I am stuck at a problem which i am trying to figure out in Swift 4.
Let say, i have the below variables
let var1 = "One"
let var2 = "Two"
let var3 = "Three"

var counter = 1

// Loop Start

let currentVariable = "var" + "\(counter)"

//Fetch the value of variable stored under currentVariable

counter += 1

//Loop end

I am trying to get the value based on variable name stored under currentVariable.

A: You can set up  dictionary, replacing your variable names with keys.
let letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
var myDictionary:[String:String] = ["var1":"One", "var2":"Two", "varA":"A", "varB":"B"]  // note, both sides can be different types than String

for x in 0...9 {
    let myKey = "var" + String(x)
    printValue(myKey)
}
for x in letters.characters {
    let myKey = "var" + String(x)
    printValue(myKey)
}

The simple function:
func printValue(_ key:String) {
    let myValue = myDictionary[key]
    if myValue != nil {
        print(myValue)
    }
}

I'm pretty sure you can make things a bit more elegant, but you get the idea. Also, keep in mind that a Dictionary is "unordered", as opposed to an array.

A: Use an array
let myArray = ["one", "two", "three"];
var counter = 1;
print(myArray[counter]);


text:
Q: Get real screen dimensions in API 24 I have a singleton class, to whom I pass the context to and which contains the following function:
public ScreenResolution getScreenResolution()
{
    ScreenResolution resolution = new ScreenResolution();

    Display display = ((WindowManager) this.context.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
    DisplayMetrics realMetrics = new DisplayMetrics();
    display.getRealMetrics(realMetrics);

    Log.d( "ScreenResolution", realMetrics.toString() );

    return resolution;
}

Logcat output:
DisplayMetrics{density=2.625, width=1080, height=1920, scaledDensity=2.625, xdpi=386.3655, ydpi=390.144}

I have Samsung Galaxy S6 Edge+ (running Android 7.0), which has a screen resolution of 1440x2560, but DisplayMetrics returns 1080x1920.
All the solutions I came across seem to be for older API's only (API 14/17). How can I read the true screen resolution for API 24 and why is it returning a wrong resoution in the first place?
Maybe it's more reliable to read Build.MODEL and cross reference it to a screen resolution table?


text:
Q: cannot get xml element value in visual basic i cannot select elements in visual basic because xml file is really complex. i am tring to select everything under item.
visual basic file:
       Dim node As XmlNode
        Dim nodelist As XmlNodeList
        Dim nsmgr As XmlNamespaceManager
        Dim xmlDoc As New XmlDocument()

    xmlDoc.Load("C:\Users\turin\Downloads\contactpersonen.xml")

    ' Namespace manager aanmaken
    nsmgr = New XmlNamespaceManager(xmlDoc.NameTable)
    nsmgr.AddNamespace("SOAP-ENV", "http://schemas.xmlsoap.org/soap/envelope/")

    ' selecteren van xml element
    nodelist = xmlDoc.SelectNodes("//SOAP-ENV:Body/ds_rl_contactpersonen_result/fields/item/rl_contactpersonen_relateregistratienr", nsmgr)

    Convert.ToString(nodelist)
    Console.WriteLine(nodelist)`

xml file:
<?xml version="1.0" encoding="UTF-8"?>
    <SOAP-ENV:Body
        xmlns:SOAP-SEC="http://schemas.xmlsoap.org/soap/security/2000-12" SOAP-SEC:id="Body">
        <ds_rl_contactpersonen_result
            xmlns="urn:EfDataService">
            <fields  xsi:type="ds_rl_contactpersonen_fieldsArray">
                <item id="bk101" xsi:type="ds_rl_contactpersonen_fields">
                    <rl_contactpersonen_relatieregistratienr xsi:type="xsd:int">2996657</rl_contactpersonen_relatieregistratienr>
                    <rl_contactpersonen_contactvolgnr xsi:type="xsd:int">1</rl_contactpersonen_contactvolgnr>
                    <rl_contactpersonen_contactpersoonsnr xsi:type="xsd:int">6149365</rl_contactpersonen_contactpersoonsnr>
                    <rl_contactpersonen_status xsi:type="xsd:int">26880</rl_contactpersonen_status>

it just returns in console:
System.Xml.XPathNodeList

A: SelectNodes return a XmlNodeList, not a single node. So you must initialize nodelist with the parent element 'item' and  enumerate it to get child nodes :
    nodelist = xmlDoc.SelectNodes("//SOAP-ENV:Body/ds_rl_contactpersonen_result/fields/item", nsmgr)

    for each childNode as XmlNode in nodeList 'enumerate childs

     'print some interesting properties
     Console.WriteLine childNode.Name
     Console.WriteLine childNode.innerXml
     Console.WriteLine childNode.innerText

    'get particular child
     if chilNode.Name="rl_contactpersonen_relatieregistratienr" then
      {----your stuff----}
     endif

    next

you can also get node directly with SelectSingleNode :
    dim childNode as XmlNode =  xmlDoc.SelectSingleNode("//SOAP-ENV:Body/ds_rl_contactpersonen_result/fields/item/rl_contactpersonen_relateregistratienr", nsmgr)
   'childNode.innerText will return '2996657'


text:
Q: ASP.NET Core modified URL-endpoints only work hardcoded without tag-helpers I've got an ASP.NET Core MVC web application (running on .NET 5). with the default 'individual authentication' template.
In the startup.cs I changed the standard URL to:
app.UseEndpoints(endpoints =>
  {
    endpoints.MapControllerRoute(
       name: "default",
       pattern: "{project}/{controller=Home}/{action=Index}/{id?}");
       endpoints.MapRazorPages();
  });

I added 'project' in front.
This works fine when navigating between the home, privacy, and every other page I created.
Privacy // This hyperlink works fine.
// Returns: www.mydomain.com/myUniqueProjectName/Home/Privacy

The problem is when navigating to 'Log in' or 'Register' page (provided by the identity template) that part of the URL just gets deleted.
Login // This hyperlink doesn't work
//becomes: www.mydomain.com/Identity/Account/Login 'myUniqueProjectName' is removed.

Now I solved it (kinda) but it's all hardcoded and doesn't make use of the asp-action and asp-controller tag-helpers.
The way I've done it now is like this:
// This is in the _Layout.cshtml (in the navigation)
Register

// This is in the Register.cshtml (scaffolder template from asp.net core)
@page "/{project}/Account/Register"

The problem is, 1st it's hardcoded 2nd, I have to do all my pages hard coded like this because otherwise I can't navigate back to the pages I've created myself (the page refreshes but stays on the Register page). I think this is because it doesn't recognize the 'myUniqueProjectName' part in the URL.
Is there any better solution than to do all my routing hardcoded like this?

A: First of all , you can implement it in a view then inherit from that view or use a partial view for this, then you don't need a piece of code in every page.
Secondly, you can get those attribute from your element using javascript and make your url and navigate.
However you can dig documents of this to see what's the proper way of implemnting this,you need to see if it worthed to put time on this or not


text:
Q: String matching algorithms in python I am looking for some suggestions on the algorithms which could be used for string matching which also supports non-english languages too.
Previously tried algorithm:
I have tried Levenshtein distance (Fuzzy matching) with token_sort_ratio algorithm. This algorithm works pretty well for most of my uses case and even for non-english languages. I considered two strings to be a match if the ratio is above 90%. The problem I am currently facing with this algorithm is, in the below example, 19th century and 18th century are not the same and I do not want them to be considered as a match.
Str1 = "19th Century"
Str2 = "18th Century"
fuzz.token_sort_ratio(Str1,Str2)
>> 92%

If I change the ratio to be greater than 95% then, I would miss below example as a match. But these two strings are a match
Str1 = "Robert Jones"
Str2 = "Robert F. Jones"
fuzz.token_sort_ratio(Str1,Str2)
>> 92%

A: why not try to use a range function instead. you could just write the range of the percent you want and loop it. The code might take a while but it should work.


text:
Q: Token in permissions dissapears using documentdb and xamarin forms I am trying to send permissions for documentdb for a specific user from my azure server to my client app, which are xamarin forms.
On server side everything looks good and I can see users specific permissions and token.

But when permissions are received in the client, the token is stripped away, why?
I am new with documentdb so hopefully it is just me.

I am using an Azure Mobile App service as backend.
My backend controller returns an object holding properties for documentdb database including a list of permissions for the user.
    public class DbConfig
{
    public string DatabaseName { get; set; }
    public string CollectionId { get; set; }
    public string EndpointUri { get; set; }
    public IList<Permission> Permissions { get; set; }

}

I create a permission for a user for the entire collection if not already created.
        public async Task<Permission> CreatePermissionAsync(string resourceLink, string userLink, PermissionMode mode, string resourcePartitionKey = null)
    {
        try
        {

            Permission permission = new Permission
            {
                Id = Guid.NewGuid().ToString("N"),
                PermissionMode = mode,
                ResourceLink = resourceLink
            };

            if (resourcePartitionKey != null)
            {
                permission.ResourcePartitionKey = new PartitionKey(resourcePartitionKey);
            }

            var result = await client.CreatePermissionAsync(userLink, permission);
            DbConfig.Permissions.Add(result);
            return result;
        }
        catch (Exception e)
        {
            Trace.WriteLine($"##### Exception: {e}");
            throw;
        }
    }

I retrieve permissions for a user with this method.
        public List<Permission> GetPermissionsForUserPermissionLink(User user)
    {
        var permFeed = client.CreatePermissionQuery(user.PermissionsLink);
        List<Permission> permList = new List<Permission>();

        foreach (Permission perm in permFeed)
        {
            permList.Add(perm);
            DbConfig.Permissions.Add(perm);
        }

        return permList;
    }

On the client side in my Xamarin forms app i use this call to my custom controller in the backend.
var parameters = new Dictionary<string, string> { { "userid", Settings.AzureUserId } };
dbConfig = await client.InvokeApiAsync<DbConfig>("Settings", HttpMethod.Get, parameters);

When i look at the permissionlist in the dbConfig object the token for a permission is null. My thought was that I could instantiate a documentdb client based on the permissionslist but it fails.
        public void CreateDocumentDbClient(DbConfig config)
    {
        client = new DocumentClient(new Uri(config.EndPointUri), config.Permissions);
        collectionLink = UriFactory.CreateDocumentCollectionUri(config.DatabaseName, config.CollectionId);
        IsInitialized = true;
    }

EDITS MADE FROM ANSWER
Just for finish up upon question.
I created a custom class holding both Permission and Token
    public class PermissionCustom
{
    public Permission  Permission { get; set; }
    public string Token { get; set; }
}

This makes it possible to create a documentdb client like this:
client = new DocumentClient(new Uri(config.EndPointUri), config.Permissions[0].Token);

So far so good :-) but it doesn't makes it easier to secure your database considering users could have many permissions for different resources. Even though it is properly to make it more secure, the token is readonly in the first place.

A: According to your code, I have checked this issue and found I could encounter the same issue. When you invoke client.InvokeApiAsync<DbConfig>("Settings", HttpMethod.Get, parameters);, you would send request with the following link:
https://{your-app-name}.azurewebsites.net/api/settings?userid={Settings.AzureUserId}
By using fiddler you could find that the token has been sent to your mobile client as follows:

But when deserialize it to Permission, the token has not been initialized correctly. I found that the token property is read only as follows:

In summary, I recommend that you need to define your custom Permission class and refer to the Permission class provided by DocumentDB client SDK for defining the properties you need within your custom permission class in your mobile client.


text:
Q: Return undefined JS I'm working on a JS exercise and I'm trying to return undefined when the given array contains a string, but instead it's returning NaN. What would be the best way for it to return undefined? Any help is appreciated!
function cubeOdd(arr) {
    var count = 0;
    for(var i = 0; i < arr.length; i++) {
      if(arr[i]==="") {
          return undefined;
      }
      else if(arr[i] % 2 !== 0) {
          count += Math.pow(arr[i],3);
      }
  }
  return count;
}
cubeOdd([2,3,4,'g']);

A: Because 'g' !== '' Use typeof For example typeof arr[i] !== 'number' or typeof arr[i] === 'string'

function cubeOdd(arr) {
    var count = 0;
    for(var i = 0; i < arr.length; i++) {
      if(typeof arr[i] !== 'number') {
          return undefined;
      }
      else if(arr[i] % 2 !== 0) {
          count += Math.pow(arr[i],3);
      }
  }
  return count;
}
console.log(cubeOdd([2,3,4,'g']), cubeOdd([2,3,4]));

A:
arr[i]===""

That tests to see if it is an empty string, not any string.
To test for that:
typeof arr[i] === "string"

A: You can check if the variable is a string using typeof myVariable.
You were using arr[i]==="" which check if arr[i] is an empty string

function cubeOdd(arr) {
    var count = 0;
    for(var i = 0; i < arr.length; i++) {
      if(typeof arr[i] === 'string')
        return undefined;
      else if(arr[i] % 2 !== 0)
          count += Math.pow(arr[i],3);
  }
  return count;
}

console.log(cubeOdd([2,3,4,'g']));

A: Simply replace the following line with
 if(arr[i]==="") {

if(typeof arr[i] === 'string') {

Currently, you are only checking if the value of the array is an empty string, but you want to check its type to make sure its a string.

A: I think you should use the prototype like type checking. It will work cross browser. Below is your updated code and I am assuming that array will return undefined if value is not Number
function cubeOdd(arr) {
    var count = 0;
    for(var i = 0; i < arr.length; i++) {
      if(Object.prototype.toString.call(arr[i])!=="[object Number]") {
          return undefined;
      }
      else if(arr[i] % 2 !== 0) {
          count += Math.pow(arr[i],3);
      }
  }
  return count;
}
cubeOdd([2,3,4,'g']);

A: Issue is with your if condition. You're checking for an empty string. simply use

isNaN()

    function cubeOdd(arr) {
    var count = 0;
    for(var i = 0; i < arr.length; i++) {
      if(isNaN(arr[i])) {
          return undefined;
      }
      else if(arr[i] % 2 !== 0) {
          count += Math.pow(arr[i],3);
      }
  }
  return count;
}
cubeOdd([2,3,4,'g']);

isNaN is a global javascript function which checks whether a given value is not a number.
Reference : isNaN() API
PS : Only the condition of your code snippet has been changed.


text:
Q: Sum harmonic and sum frequency generation Can two collinear beams of two different wavelengths generate the sum frequency or they need to pass each other at a certain angle. For a monochromatic light how does the sum harmonic gets generated while for two different beams a certain angle is necessary?

A: Sum frequency generation can be done with colinear beams with different wavelengths.
 here is a practical example of SFG:

for any frequency generation process, we need two conditions:
frequency match:
$$\omega_1+\omega_2=\omega_3$$
phase matching:
$$k_1+k_2=k_3$$
for more information see this:
Saleh_Fundamentals of Photonics_2007, chapter 21

A: As long as we deal with linear medium and linear sensors, mixing two sine waves with different frequencies would not produce new frequencies (sums, harmonics, etc.), regardless of the angle between the beams, i.e., the spectrum of the combined wave would consist of two spectrum lines, corresponding to the two original waves .


text:
Q: Grunt Jasmine "Cannot call method "join" of undefined" Just upgraded to grunt-contrib-jasmine 0.6.0 with grunt 0.4.1.
The tests used to work but now I'm getting:
Running "jasmine:app2JsTests" (jasmine) task
Warning: Cannot call method 'join' of undefined Use --force to continue.

A: It turns out that grunt-template-jasmine-requirejs is incompatible with the newest version of grunt-contrib-jasmine as they have documented here.


text:
Q: How to measure average value of qubits? Recently I have been studying quantum mechanics in The Theoretical Minimum by Susskind. In his experiment, when the apparatus rotated by an arbitrary angle within the $x{–}z$ plane, the average measurement result is $\hat{n}\cdot\hat{m}$. He explains as below:
Classically, if $\sigma$ were a vector, we would expect the result of the experiment to be the component of $\sigma$ along the $\hat n$ axis. If $\hat n$ lies at an angle $\theta$ with respect to $z$, the classical answer would be $\sigma=\cos\theta$. But as you might guess, each time we do the experiment we get $σ = \pm1$. However, the result is statistically biased so that the average value is $\cos\theta$.
My question is: if we get $\pm1$ randomly in a qubit, how do we get a statistically biased average value of $\cos\theta$?

A: The way to express an arbitrary Pure Qubit is:
$$|n \rangle = \cos{\frac{\theta}{2}} |0 \rangle + e^{i\phi}\sin{\frac{\theta}{2}} |1 \rangle$$
Where $n$ is the Bloch Vector with angle $\theta$ with respect to the positive $z\text{ -axis}$ and angle $\phi$ with respect to the positive $x\text{ -axis}$ on the $xy\text{ -plane}$
And if we are measuring some $| \psi \rangle$ along the axis $| n \rangle$, then the probability we obtain $+\frac{\hbar}{2}$ is $|\langle n | \psi \rangle|^2$ and ofcourse the probability we obtain $-\frac{\hbar}{2}$ is $|\langle -n | \psi \rangle|^2$, where $|-n \rangle$ is simply the vector in the opposite direction of $|n \rangle$, because obviously those are the only two eigenstates we can obtain measuring along that axis.
From here you should be able to find expected values and other statistical attributes which would depend on the angles at hand.
Bellow is a Bloch Sphere, which is a very useful visual aid for seeing Rotations of Single Qubits and how that effects observed probabilities.


text:
Q: Cycling Power Envelope in R Cyclists are recording pedalling power over time and analyse a curve1 derived from this that plots for every given time interval the amount of power at least produced: for 20 continuous minutes, you maintained 248W or more. I'd like to compute this in R starting from small time intervals dt and corresponding power pwr:
df <- data.frame(dt = rnorm(15,2,1), pwr = rnorm(15,250,50))

A simple but inaccurate way is this:
library(ggplot2)

df <- data.frame(dt = rnorm(15,2,1), pwr = rnorm(15,250,50))
df <- df[with(df, order(-pwr)),]
df$s <- cumsum(df$dt)

p <- ggplot(df,aes(s,pwr)) + geom_line()
ggsave("pwr.png",p)

          dt      pwr          s
10 0.9955972 323.3430  0.9955972
7  2.5057756 295.2261  3.5013728
2  0.5074293 293.4071  4.0088021
15 1.1912498 285.6561  5.2000519
8  3.3259203 281.7460  8.5259722
13 1.4008969 266.2108  9.9268691
1  4.2681574 265.4673 14.1950265
12 0.1884451 258.5368 14.3834716
6  2.0126561 247.0550 16.3961277
11 4.3295127 242.8312 20.7256404
5  1.9477712 237.8359 22.6734115
4  1.1545416 213.1518 23.8279531
3  0.9062592 191.6465 24.7342123
9  0.8966972 184.8294 25.6309095
14 0.3863399 183.8604 26.0172494

The graph tells that I was able to maintain about 270W or more for 10s or about 240W or more for 20s.
The problem with that approach is: assuming I maintain 10min of 250W or more, drop below 250W and maintain 5min of 250W or more again this will be summed to 15min of maintaining 250W or more - but I only maintained only 250W or more continuously for 10min. So for any given power I need to find the maximum length of time I was able to maintain it continuously rather the total amount of time I maintained 250W or more.

*

*Is the desired summary a well known function? It is defined for any continuous function and similar to a probability density function. It is always a strictly decreasing function.

*How can this be done in R accurately and efficiently?

A: There are more efficient calculations that could be done with base rle or data.table, but this tidyverse approach is legible to me and should be adequate for data that isn't extremely large. In my testing, the code below for 100,000 observations took about 5 seconds to run.
My approach is to make a function that finds the cumulative min for any given window size (using slider::slide_index so that the window is defined by time, not a fixed number of observations), and then output the max of these. Then I iteratively feed a range of window sizes into purrr::map_dbl to get the max_min for that size.
set.seed(0)
# This gets too sluggish for my taste for 1M+ observations, but
#  seems fine for me for 100k.
df <- data.frame(dt = runif(1E5,min = 0.01, 5), pwr = rnorm(1E5,250,50))

library(tidyverse); library(slider)
select_max_min <- function(df = df, window_size) {
  df %>%
    mutate(time = cumsum(dt)) %>%
    mutate(cuml_min = slide_index_dbl(pwr, time, min, .before = window_size)) %>%
    summarize(max_min = max(cuml_min)) %>%
    pull(max_min)
}

data.frame(window = seq(1, 30, length.out = 100)) %>%
  mutate(max_min = map_dbl(window, ~select_max_min(df, .x))) %>%
  ggplot(aes(window, max_min)) +
    geom_line()


text:
Q: Why does my Eclipse Helios debugging hand when stepping over Path.register(WatchService, Kind>...)? I have code like this in a Junit 4 class:
Path dir = Paths.get("/tmp/testDir");
dir.toFile().mkdir();
WatchService watchService = FileSystems.getDefault().newWatchService();
dir.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
    StandardWatchEventKinds.ENTRY_DELETE);

When I try to step over the last statement in the Eclipse Helios debugging perspective, the relevant thread indicates that it's "Stepping" and never returns. Why?
The same behavior (hanging on the Path.register() call) apparently also occurs when I try the Maven command "mvn test" to execute the Junit class (at least that hypothesis is consistent with the failure of the class that I see).
Here's my JVM:
$ $JAVA_HOME/bin/java -version
java version "1.7.0_02"
Java(TM) SE Runtime Environment (build 1.7.0_02-b13)
Java HotSpot(TM) 64-Bit Server VM (build 22.0-b10, mixed mode)

A: At the risk of answering my own question, I've learned the following things about the Path.register() method: 1) it apparently won't return if all other threads in the JUnit test are suspended; and 2) it doesn't execute quickly enough to catch the first file that the JUnit test creates. Consequently, the Eclipse debugging hung and the Maven test failed at exactly the same point -- but for different reasons.


text: Q: Android ~ detection any other application/service I know there are methods to find the running applications, services.. in Android. But is there any event to detect if any other application/service installed or unistalled?


text:
Q: Multiple constructors with the same number of parameters exception while transforming data in spark using scala Below is the code
    def findUniqueGroupInMetadata(sc: SparkContext): Unit = {
    val merchantGroup = sc.cassandraTable("local_pb",     "merchant_metadata").select("group_name")

try {
  val filterByWithGroup = merchantGroup.filter {
    row =>
      row.getStringOption("group_name") match {
        case Some(s: String) if (s != null) => true
        case None => false
      }
  }.map(row => row.getStringOption("group_name").get.capitalize)

  //filterByWithGroup.take(15).foreach(data => println("merchantGroup => " + data))
  filterByWithGroup.saveToCassandra("local_pb", "merchant_group", SomeColumns("group_name"))
} catch {
  case e: Exception => println(e.printStackTrace())

}

}
Exception =>
java.lang.IllegalArgumentException: Multiple constructors with the same number of parameters not allowed.
    at com.datastax.spark.connector.util.Reflect$.methodSymbol(Reflect.scala:16)
    at com.datastax.spark.connector.util.ReflectionUtil$.constructorParams(ReflectionUtil.scala:63)
    at com.datastax.spark.connector.mapper.DefaultColumnMapper.<init>(DefaultColumnMapper.scala:45)
    at com.datastax.spark.connector.mapper.LowPriorityColumnMapper$class.defaultColumnMapper(ColumnMapper.scala:47)
    at com.datastax.spark.connector.mapper.ColumnMapper$.defaultColumnMapper(ColumnMapper.scala:51)

A: I found the answer after looking into some blogs.
When I converted the RDD[String] to RDD[Tuple1[String]] everything went smooth. So basically in order to save data to Cassandra, data needs to be of type RDD[TupleX[String]] here x can be 1,2,3... or data can be RDD[SomeCaseClass]


text:
Q: unable to install jd-gui on ubuntu 16.04,64 bit machine Getting following error:
error while loading shared libraries: libgtk-x11-2.0.so.0: cannot open shared object file: No such file or directory
Already tried installing using below cmd:
sudo apt-get install ia32-libs-gtk
Getting error for this too:E: Unable to locate package ia32-libs-gtk

A: Seems you need to install x86 version:
sudo apt-get install libgtk2.0-0:i386


text:
Q: How to relationalize JSON containing arrays I am using AWS Glue to read data file containing JSON (on S3). This one is a JSON with data contained in array. I have tried using relationalize() function but it doesn't work on array. It does work on nested JSON but this is not the data format of input.
Is there a way to relationalize JSON with arrays in it?
Input data:
{
    "ID":"1234",
    "territory":"US",
    "imgList":[
        {
            "type":"box"
            "locale":"en-US"
            "url":"boxart/url.jpg"
        },
        {
            "type":"square"
            "locale":"en-US"
            "url":"square/url.jpg"
        }
    ]
}

Code:
dfc = Relationalize.apply(frame = datasource0, staging_path = glue_temp_storage, name = "root", transformation_ctx = "dfc")
dfc.select('root').toDF().show()

Output:
+----+----------+--------+
|ID  |territory |imgList |
+----+----------+--------+
|1234|       US |       1|
+----+----------+--------+

Desired output:
+----+----------+-------------+---------------+---------------+
|ID  |territory |imgList.type |imgList.locale |imgList.url    |
+----+----------+-------------+---------------+---------------+
|1234|       US |       box   |         en-US |boxart/url.jpg |
+----+----------+-------------+---------------+---------------+
|1234|       US |       square|         en-US |square/url.jpg |
+----+----------+-------------+---------------+---------------+

A: Relationalize creates DynamicFrames for each arrays in the JSON document. So you just need to get it and join with the root table:
dfc = Relationalize.apply(frame = datasource0, staging_path = glue_temp_storage, name = "root", transformation_ctx = "dfc")
root_df = dfc.select('root')
imgList_df = dfc.select('root_imgList')

df = Join.apply(root_df, imgList_df, 'imgList', 'id')
df.toDF().show()


text:
Q: "If + would" conditional in present perfect tense Is it allowed to use the "if + would" conditional when speculating about a polite request that could have taken place in past? I know that the would structure can be used to make a polite request, but can it be used for making one in the past as well?

If he would have told me what he wanted for lunch, I would have cooked it for him.

Also, may I use this construction in the past perfect tense?
Example: If he "would had told" me what he wanted for lunch, I would have cooked it for him.

A: "will" and "would" can be used in conditional clauses when a polite request is implied (the examples are taken from here):

*

*If you 'll just fill in this form before you go, you can hand it in to reception.

*If you would take a seat, the doctor will see you in five minutes.
However, strictly speaking, this cannot be the case with a counterfactual conditional sentence in which both the condition and the result are set in the past.
In the Cambridge Dictionary, we find this reference:
We use would have + -ed in the main clause, not in the conditional clause:
If he had stayed in the same room as Dave, it would have been a disaster.
Not: If he would have stayed … it would have been a disaster.
People do sometimes use the form with "would have" in informal speaking, but many speakers consider it incorrect.

A: There is nothing wrong with this:

✔ If he would have told me what he wanted for lunch, I would have cooked it for him.

However, it's a bit more common for it to be phrased this way:

✔  If he had told me what he wanted for lunch, I would have cooked it for him.

On the other hand, the combination of both would and had does not work:

✘ If he would had told me what he wanted for lunch, I would have cooked it for him.

A: If he would had told me is considered grammatically incorrect. The first example you showed is right.

A: First example:
✔ Correct
Second example:
✖ Incorrect
Either having had without would, or having have with would are both correct,
Can't mix those to up!


text:
Q: Proper use of IdUDPClient.ReceiveBuffer Thank you for your help.
I am converting an older version of Delphi to XE5 and I am getting stuck with the Indy compnent.  Need to use IdUDPClient.ReceiveBuffer
Here is my code:
while not Terminated do
begin
  try
    lenUDP:= IdUDPClient.ReceiveBuffer(myBuf, buffLength, -1 );
    if lenUDP<> 0 then
      Synchronize(ReceivedLine);
  except
    Terminate;
  end;
end;

where,
myBuf = packed array [0 .. buffLength -1] of char;
All help is greatly appreciated.
Thank you,
Mike

A: As I told you in comments to your previous question:

You have to use a TIdBytes for that as well. Use SetLength() to pre-allocate it to the desired size, then call ReceiveBuffer() with it, and then you can copy out data from it as needed, either directly or with BytesToRaw().

For example:
private
  myBuf: TIdBytes;
...

while not Terminated do
begin
  try
    SetLength(myBuf, buffLength);
    lenUDP := IdUDPClient.ReceiveBuffer(myBuf, -1);
    if lenUDP > 0 then
    begin
      SetLength(myBuf, lenUDP);
      Synchronize(ReceivedLine);
    end;
  except
    Terminate;
  end;
end;

Since your original buffer was an array of Char, and your processing function is named ReceivedLine(), I am assuming your data is textual in nature.  If that is true, you can use BytesToString() or (T|I)IdTextEncoding.GetString() to convert a TIdBytes to a String, if that is what ReceivedLine() uses myBuf for, eg:
S := BytesToString(myBuf{, en8bit});

S := BytesToString(myBuf, 0, lenUDP{, en8bit});

S := IndyTextEncoding_8bit.GetString(myBuf);

S := IndyTextEncoding_8bit.GetString(myBuf, 0, lenUDP);

You can use any charset encoding that Indy supports, either via the various en...(), Indy...Encoding(), or IndyTextEncoding...() functions in the IdGlobal unit, or the CharsetToEncoding() function in the IdGlobalProtocols unit.
UPDATE: since your buffer is part of a record with a union in it, you will have to use a local TIdBytes variable instead:
type
  myRecord = record
    ...
    myBuf: array[0..buffLength-1] of Byte;
    ...
  end;

...

private
  myRec: myRecord;

...

var
  udpBuf: TIdBytes;
...
SetLength(udpBuf, buffLength);
while not Terminated do
begin
  try
    lenUDP := IdUDPClient.ReceiveBuffer(udpBuf, -1);
    if lenUDP > 0 then
    begin
      BytesToRaw(udpBuf, myRec.myBuf[0], lenUDP);
      Synchronize(ReceivedLine);
    end;
  except
    Terminate;
  end;
end;


text:
Q: Error message for empty table for DT::renderDataTable in R I have a requirement to show data coming from table on UI screen. I am currently using DT::renderDataTable.
Inside renderDataTable, the code will return data that is getting returned from a table. Incase there is no Data available in the table, blank is displayed on screen.
I need to add some custome error message when there is no data in the table, can you please help.

A: There are different ways about it.
Show a notification
library(DT)
library(shiny)

ui <- fluidPage(
    actionButton("load", "Load/unload data"),
    DTOutput("table")
)

server <- function(input, output, session) {
    df <- eventReactive(input$load, {
        if(input$load %% 2 == 0){
            return(cars)
        } else {
            shiny::showNotification("No data", type = "error")
            NULL
        }
    })

    output$table <- renderDT(df())
}

shinyApp(ui, server)

Show error
library(DT)
library(shiny)

ui <- fluidPage(
    actionButton("load", "Load/unload data"),
    DTOutput("table")
)

server <- function(input, output, session) {
    df <- reactive({
        if(input$load %% 2 == 0){
            dat <- cars
        } else {
            dat <- NULL
        }

        validate(
            need(!is.null(dat), "No data")
        )

        return(dat)
    })

    output$table <- renderDT(df())
}

shinyApp(ui, server)

You could also show a modal with showModal.

A: I know this question is quite stale, but thought I would put this answer up here for other people searching for a solution.
Add the following to the call to Datatable or renderDataTable
options = list(language = list(emptyTable = 'My Custom No Data Message'))

Also, pass a zero row data frame to the renderDataTable so it knows how to setup the columns.  You can get a zero row data frame in the following way:
If you dont have an existing data frame:
data.frame(ColOne=numeric(), ColTwo=character(), ColThree=numeric, stringsAsFactors=FALSE)

If you do have an existing data frame:
myexistingdf[NULL,]


text:
Q: Using websockets (socket.io) for sails 0.10.x I am developing a node app on sails, my app needs to do regular exchange of data between server and client
The SailsCast video demonstrates the process for sails 0.9.x, and the mentioned files are not present in Sails 0.10.x
Also the sails doc says we should be using sails.socket instead of sails.io as the later will be deprecated in coming versions
Can any one help me in exchanging data between server and client through sockets. I have done it through node but with Sails MVC, i am not sure how to put the pieces together.
Any reference link or suggestion will be of great help
Thanks

A: I had the same trouble. You may want to check SailsSocket doc.
If you are loading sails.io.js in your page and haven't changed the default
io.sails.autoConnect to false, then a WebSocket should be created for you.
You can access it via io.socket
Create e.g. assets/js/dependencies/app.io.js with:
io.socket.on('connect', function socketConnected() {
  console.debug("This is from the connect: ", io.socket);
  console.debug("WebSocket is connected:", io.socket.isConnected());
});

Make sure to load this file after sails.io.js (See pipeline.js).
Open you browser console and double check.
Also check SailsSocket methods
Hope this help you get started


text:
Q: How do I use NodeJS on Asustor AS-302T NAS I have recently bought a Asustor AS-302T NAS, which is an absolutely brilliant solution for the home. One of it's most impressive features is that you can install apps which extends the ordinary behavior of a NAS. And if you are a developer you can also create your own apps.
While apps are fun, I have more interest in using my NAS as a kitchen-sink for my personal nodejs projects. In short I want to run nodejs application that I can then call from various other machines around the house. My own mini-cloud for IOT experiments.
Installing, one click only
Having installed NodeJS through App-Central I am at a loss how exactly to start using NodeJS on my NAS. The whole installation is essentially an on/off switch with no options or visible settings at all. I can find no documentation on practical tasks like uploading a nodejs application, deal with access rights or even execute it.

Under Windows or OS-X I would use npm via the command-line or shell, but Asustor is a purely html based interface (with the exception of XBMC through HDMI).
Why offer to users the option of installing NodeJS -if it's impossible to actually use it?
So my question has three aspects to it:

*

*How do i get access to npm on my Asustor NAS

*How do i get my NodeJS application running

*Is it possible to run my application as a service (executed when the NAS boots)?

A: From the ASUSTOR Developer's Guide: apps are installed into
/usr/local/AppCentral/$APP_NAME.
NodeJS executables will be at path /usr/local/AppCentral/nodejs/bin/node and /usr/local/AppCentral/nodejs/bin/npm.
You can login to NAS via SSH and add them to PATH variable, or create symlinks...
I'm also searching for solution how to run them as a service (daemon), maybe an /etc/init.d script might help.


text:
Q: Como centrar un div completamente? html, css Estoy creando una tabla que quiero que vaya en el centro de la pagina a la hora de mostrar la informacion,pero por alguna razon no se centra, esta asi:

en la esquina de la pagina y no se mueve,
aqui les muestro el codigo html:

{{message}}

                    Actual products in making.

 {{i.room}}

                                    Name:
                                    {{i.name}}

                                    LOT:
                                    {{i.lot}}

                                    Quantity to be package:
                                    {{i.quantity_to_package}}

                                    Quantity of pallets:
                                    {{i.pallets}}

                                    Progress:
                                    {{i.progress}}

                                    {{i.finished_pallets}} pallets of {{i.pallets}} pallets
                                    <button @click="addPallet(i.room)">Add Pallet</button>

Completed

                                    <button @click="finish(i.room)">Finish procedure</button>

el id see_actual_products lo uso solamente para Vuejs, el contenedor que estoy usando para centrar completamente es el section "see_actual_products_section", pero como dije anteriormente no me lo centra, aqui el codigo css:
* {
margin: 0;
padding: 0;
box-sizing: border-box;}

.see_actual_products_section{
margin: auto;
padding: 20px;
border-radius: 4px;}

he buscado y dicen de usar text-aling:center pero solo centra los textos dentro de section, float, igual, gracias :)

A: Utiliza flexbox en un div padre y luego centralo de forma vertical u horizontal, por ejemplo aqui te muestro como centro un cuadro rojo sobre un cuadro negro.

.padre {
  height: 100px;
  width: 100px;
  background: black;
  /* Codigo para centrar*/
  display: flex;
  justify-content: center;
  align-items: center;
  /* Fin del codigo para centrar*/
}

.hijo {
  height: 10px;
  width: 10px;
  background: red;
}


text:
Q: In the spark mllib, how to set L2 regular param in LogisticRegressionWithLBFGS I want to use L2 regularizers and set L2 regular param in LogisticRegressionWithLBFGS, but there is no example in mllib's programming guides.So anyone please tell me how to use L2 regularizers in LogisticRegressionWithLBFGS ?

A: Spark's LogisticRegressionWithLBFGS returns a regularized model estimate.
Standard feature scaling and L2 regularization are used by default in LogisticRegressionWithLBFGS.
It is answered for similar question here.

A: Today, my colleagues told me how to solve this problem. I show the answer and maybe help some people with the same problems I encountered.
val paramL2: Double = 0.05  //  L2 regularization coefficient
val logisticRegressionWithLBFGS = new LogisticRegressionWithLBFGS()
logisticRegressionWithLBFGS.optimizer.setRegParam(paramL2)  // set L2 regularization coefficient
logisticRegressionWithLBFGS.setIntercept(true).setNumClasses(15)
val model = logisticRegressionWithLBFGS.run(trainingSamples)  // train model use some training samples

If you encounter a similar problem, we'd better look at the mllib source code and you can find answer. Just some suggestions. :)


text:
Q: How can I pass the userID from PHP to Android(Shared Preferences) I am making an app that shares the same database as my website. I maintain the login session throughout the activities and I can get the username, but how can I get the User ID(PK) from the user who is logging in? I've got all the tables well created and I can communicate with the database with the app and the website. Please help me
//PHP FILE

if($_SERVER['REQUEST_METHOD']=='POST'){
    //Getting values
    $email = $_POST['email'];
    $password = $_POST['password'];

    //Creating sql query
    $sql = "SELECT * FROM Utilizadores WHERE email='$email' AND password='$password'";

    //importing dbConnect.php script
    require_once('connection.php');

    //executing query
    $result = mysqli_query($con,$sql);

    //fetching result
    $check = mysqli_fetch_array($result);

    //if we got some result
    if(isset($check)){

        //displaying success
        echo "success";
    }else{
        //displaying failure
        echo "failure";
    }
    mysqli_close($con);
}

//Android File
public class Config {

    //URL to our login.php file
    public static final String LOGIN_URL = "http://192.168.1.43/Teste/login.php";

    //Keys for email and password as defined in our $_POST['key'] in login.php
    public static final String KEY_EMAIL = "email";
    public static final String KEY_PASSWORD = "password";
    public static final String KEY_ID = "id_utilizador";

    //If server response is equal to this that means login is successful
    public static final String LOGIN_SUCCESS = "success";

    //Keys for Sharedpreferences
    //This would be the name of our shared preferences
    public static final String SHARED_PREF_NAME = "myloginapp";

    //This would be used to store the email of current logged in user
    public static final String EMAIL_SHARED_PREF = "email";

    //This would be used to store the id of current logged in user
    public static final String ID_SHARED_PREF = "id_utilizador";

    //We will use this to store the boolean in sharedpreference to track user is loggedin or not
    public static final String LOGGEDIN_SHARED_PREF = "loggedin";
}

A: As far as I understand, you want to retrieve a server-side variable (the userID).
You can make your server to output that variable if login was successful, then parse the server response from your Android app.


text:
Q: I want to get a distinct list of values for three variables that add up to 1 in increments of 0.05 What I want is to find a distinct list of decimals that add to 1 given that I'm using three variables and each variable can increase by 0.05.
The table of values would look something like this:
Var1   Var2   Var3   Total
 0.0    0.05   0.95   1
 0.20   0.40   0.40   1
 0.15   0.75   0.10   1
 0.50   0.25   0.25   1
 0.80   0.20   0.00   1

And so on... I think you get the idea.

A: The first thing to realize is that since they all sum to 1, var3 is a function of var2 + var1. So you really have two variables here.
You can brute force this by just looping var1 and var2 blindly and keeping the values:
List<int[]> sets = new ArrayList<>();

for(int var1 = 0; var1 <= 100; var1 += 5) {
    for(int var2 = 0; var2 <= 100; var2 += 5) {
        int var3 = 100 - (var1 + var2);
        if(var1 + var2 + var3 == 100 && (var1 != var2) && (var1 != var3) && (var2 != var3)) {
             int[] set = new int[] { var1, var2, var3 };
             sets.add(set);
        }
    }
}

Now this is riddled with inefficiencies that hopefully you can spot and optimize, but this should be an effective way to do it. Note that I used integers so we didn't end up with weird floating point rounding errors. Modify your output accordingly.


text:
Q: Matlab - Two Subplots, single color scale and colorbar consider the following code
x = [-1:0.1:1];
subplot(2,2,1)
imagesc(x,x,abs(x)/100)
colorbar
subplot(2,2,2)
imagesc(x,x,abs(x))
colorbar

What I want to happen Is that both images will be on the same color scale, and the same color bar I.e., that the left will be mostly blue, while the right one will show the full scale.

A: EDIT: Made the range fit both.
x = [-1:0.1:1];

subplot(1,2,2)
imagesc(x,x,abs(x))
colorbar
c2 = caxis;

subplot(1,2,1)
imagesc(x,x,abs(x)/100)
colorbar
c1 = caxis;
c3 = [min([c1 c2]), max([c1 c2])];
caxis(c3)

subplot(1,2,2)
colorbar off


text:
Q: Don't re-add mapview after is loaded in viewdidload I have created function caricamappa() to loading map view with my mapbox map, and into Custompointannotation there is a control for add and remove annotation with Bool control, with a button i want to caricamappa() add and remove annotation with force Bool and its work but i don't want to re-add subview(mapview) into my app, is it possible to refresh a view without adding another and hide/show annotation? thanks
func carica_mappa() {
    // Fill in the next line with your style URL from Mapbox Studio.
    let styleURL = NSURL(string: "mapbox:***")
    let mapView = MGLMapView(frame: view.bounds,
                             styleURL: styleURL as URL?)
    mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    // Set the map's center coordinate and zoom level.
    mapView.setCenter(CLLocationCoordinate2D(latitude: 44.370417,
                                             longitude: 7.411713),
                      zoomLevel: 13, animated: false)
    view.addSubview(mapView)

    mapView.userTrackingMode = .followWithHeading
    // Set the delegate property of our map view to `self` after instantiating it.
    mapView.delegate = self

    let uno = CustomPointAnnotation(coordinate: CLLocationCoordinate2DMake(44.376362, 7.396907),
                                    title: "**",
                                    subtitle: "**",
                                    controllo: visible)
    // Set the custom `image` and `reuseIdentifier` properties, later used in the `mapView:imageForAnnotation:` delegate method.
    uno.reuseIdentifier = "montagna"
    uno.image = UIImage(named: "montagna")
    if uno.controllo == true {
        mapView.addAnnotation(uno)

    }
    else {
        mapView.removeAnnotation(uno)
    }
}
    func mapView(_ mapView: MGLMapView, imageFor annotation: MGLAnnotation) -> MGLAnnotationImage? {
        if let point = annotation as? CustomPointAnnotation,
            let image = point.image,
            let reuseIdentifier = point.reuseIdentifier {

            if let annotationImage = mapView.dequeueReusableAnnotationImage(withIdentifier: reuseIdentifier) {
                // The annotatation image has already been cached, just reuse it.
                return annotationImage
            } else {
                // Create a new annotation image.
                return MGLAnnotationImage(image: image, reuseIdentifier: reuseIdentifier)
            }
        }

        // Fallback to the default marker image.
        return nil
    }

    func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
        // Always allow callouts to popup when annotations are tapped.
        return true
    }

override func viewDidLoad() {
    super.viewDidLoad()
    carica_mappa()
  }

A: My advice is to split the code to setup the map and the one to add the CustomAnnotationView. CaricaMappa() should only be used to add the map to its superview and called in viewDidLoad(). The code to setup the CustomAnnotation should be in its own method and you can call it on button tap. So you would have something like:
func carica_mappa() {
    // Fill in the next line with your style URL from Mapbox Studio.
    let styleURL = NSURL(string: "mapbox:***")
    let mapView = MGLMapView(frame: view.bounds,
                             styleURL: styleURL as URL?)
    mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]

    // Set the map's center coordinate and zoom level.
    mapView.setCenter(CLLocationCoordinate2D(latitude: 44.370417,
                                             longitude: 7.411713),
                      zoomLevel: 13, animated: false)
    view.addSubview(mapView)

    mapView.userTrackingMode = .followWithHeading
    // Set the delegate property of our map view to `self` after instantiating it.
    mapView.delegate = self
}

    @IBaction func didPressButton(sender: UIButton) {

          let uno = CustomPointAnnotation(coordinate: CLLocationCoordinate2DMake(44.376362, 7.396907),
                                        title: "**",
                                        subtitle: "**",
                                        controllo: visible)
        // Set the custom `image` and `reuseIdentifier` properties, later used in the `mapView:imageForAnnotation:` delegate method.
        uno.reuseIdentifier = "montagna"
        uno.image = UIImage(named: "montagna")
        if uno.controllo == true {
            mapView.addAnnotation(uno)

        }
        else {
//You might want to check if the annotation exist in the map first.
            mapView.removeAnnotation(uno)
        }
    }


text:
Q: Index.php/index.html files daily getting injected with include code My site got hacked, updated from Drupal 7.3 to 7.59 after the issue occured for the security updates, but the issues are still coming up. Also I reverted the server to a state before the attack.
The server has had index files created daily, in weird places like css/js folders, but also in existing index.php/index.html, and these index files have this code in them:
<?PHP
 @include "\157\157\157\157\157\157\157\157\157\157\157\157";

I put the string (not this specific string) and the path is pointing to an ico file, but the ico file if you change from .ico to .php or .html or .txt, has a huge array
/*79026*/
<?PHP
   @include some-folder-name/.81abc878.ico;

/*79026*/

I don't really understand the 79026, it's the same number on index.
The include path is a string of numbers/letters that I had to use https://www.unphp.net/ to decode due to it's format. My theory is that it's just intercepting post data and it's injecting that data into the .ico file which is actually a php script. I don't have access to that file, but if I do find it again I'll be sure to post an update.
Any help or guidance in fixing this would be great.

A: If I recall, the security issue was a remote code execution. That means they could have installed scripts on your server, and even modified your sshd to give them remote access.
Setup a new server, restore only drupal'd database, and reinstall drupal fresh, and with the already updated version. Then fix whatever's wrong with your website taking care not to copy files from the old server (other than media/images).
Hopefully that gets you in a clean state.


text:
Q: Multiple Invocations of Spring Scheduled Task So I am having a bit of a problem with some scheduled tasks I have declared using Spring's @Scheduled annotation. First off here is my app-config:
<beans <!--Namespaces-->>
    <!-- Search for annotated beans -->
    <context:component-scan  base-package="com.my.package.task"/>

    <task:annotation-driven executor="myExecutor" scheduler="myScheduler"/>

    <task:executor id="myExecutor" pool-size="5"/>

    <task:scheduler id="myScheduler" pool-size="10"/>

    <tx:annotation-driven/>
</beans>

I also have a AppConfig class:
@Configuration
@ImportResource("classpath:/config/app-config.xml")
public class AppConfig {
     //Bean declarations but NO references to the Scheduled tasks or their classes
}

And here are the scheduled tasks I have declared:
public abstract class ScheduledTask {
     private ApplicationContext appContext;

     abstract void doSomething();

     protected getAppContext() {
          if(appContext == null) {
               appContext = new AnnotationConfigApplicationContext(AppConfig.class);
          }

          return appContext;
     }
     //Other common methods
}

@Service
public class Task1 extends ScheduledTask {
     @Scheduled(cron="0 0 9 * * MON-FRI")
     public void doSomething() {
        System.out.println("Task1 -- Thread ID: " + Thread.currentThread().getId() + " Thread Name: " + Thread.currentThread().getName());
         //Update the database with new values
     }
}

@Service
public class Task2 extends Scheduledtask {
     @Scheduled(cron="0 0 10 * * MON-FRI")
     public void doSomething() {
          System.out.println("Task2 -- Thread ID: " + Thread.currentThread().getId() + " Thread Name: " + Thread.currentThread().getName());
          //Get some data from database and send email with data from DB
     }
}

Now the problem I am getting is that when these tasks are run, I get multiple emails sent (see Task2). I added in the print statements to see if the methods were being called multiple times and Task2 is executed twice by 2 different threads. I would hope that Spring would only invoke a scheduled task once. Here is the output I get:
Task1 -- Thread ID: 10 Thread Name: myScheduler-1
Task2 -- Thread ID: 23 Thread Name: myScheduler-2
Task2 -- Thread ID: 11 Thread Name: myScheduler-2

And if I run it at night and set the cron jobs to be like 4hrs apart I start to get even more emails sent (thought I havent had a chance to see if this is due to multiple threads / method calls).
Does anyone have any ideas what could be causing the multiple invocations of the second task?  I looked at the Spring Documentation and under the 'Note' it mentions that you can get multiple invocation if you initialize multiple instances of the @Scheduled class at runtime. Could that be happening here with my AppConfig and app-config.xml?


text:
Q: Who owns the process / main thread? I created new WPF Application witn two windows.

*

*MainWindow.xaml

*Window1.xaml

Added one button in MainWindow.xaml and wrote the following code in the click event of the button:
Window1 w = new Window1();
w.Show();

I clicked that button 2-3 times and it opened multiple instances of Window1.
Everything fine till here.
Now, I closed MainWindow and it did not close the instances of Windows1.
I was thinking that since MainWindow is the one that owns the Process and if it closes, rest of the child windows will close automatically.
I did the same project in WinForms application and the result was completely different. On closing the MainWindow, it did close rest of the windows.
Am i not understanding the concept clearly? Can someone tell me who owns the process or the main thread in WPF?

A: The other windows are not child windows of your MainWindow unless you set window.Owner = mainWindow;
Further there is the Application.MainWindow property which sets which window actually is treated as "the" main window. This affects the Application.ShutdownMode if set to OnMainWindowClose.

Excerpt from the Window.Owner reference:

When a child window is opened by a parent window by calling ShowDialog, an implicit
  relationship is established between both parent and child window. This relationship enforces certain behaviors, including with respect to minimizing, maximizing, and restoring.
When a child window is created by a
  parent window by calling Show,
  however, the child window does not
  have a relationship with the parent
  window. This means that:

*

*The child window does not have a reference to the parent window.

*The behavior of the child window is not dependent on the behavior of
  the parent window; either window can
  cover the other, or be minimized,
  maximized, and restored independently
  of the other.
To allow you to create a relationship
  between a child window and a parent
  window, Window supports the notion of
  ownership. Ownership is established
  when the Owner property of a window
  (the owned window) is set with a
  reference to another window (the owner
  window).

The application root class: System.Windows.Application
WPF Threading Model


text:
Q: Endless/Infinite Scrolling not working for gridview? My app tries to get various information from an api call using Retrofit and Gson. This information needs to be displayed as a gridview and the gridview needs to repopulate on scrolling. As of now, I can get the first 10 items, and thats it. How to add the endless scrolling feature to this.
public class ProductListing extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.product_listing_act);
    init();
}

public void productListingApiCall() {

    RestAdapter restAdapter = new RestAdapter.Builder().setEndpoint(base_url).setLogLevel(RestAdapter.LogLevel.FULL).build();
    final ProductListingApi productListingApi =
            restAdapter.create(ProductListingApi.class);
    productListingApi.getFeed(file, operation_condition, search_string_condition, minprice_condition, maxprice_condition, mincusratings_condition,
            maxcusratings_condition, discount_condition, catids_condition, brands_condition, affids_condition, start_row_condition, limit_condition,
            orderby_condition, sortby_condition, new Callback<ProductListingPojo>() {

                @Override
                public void success(ProductListingPojo productListingPojo, Response response) {
                    final ProductListingPojo product = productListingPojo;
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            product_key = Arrays.copyOf(product.getProductkey(),
                                    product.getProductkey().length);
                            cs_category_id = Arrays.copyOf(product.getCsCategoryid(),
                                    product.getCsCategoryid().length);
                            title = Arrays.copyOf(product.getTitle(),
                                    product.getTitle().length);
                            price = Arrays.copyOf(product.getSellingprice(),
                                    product.getSellingprice().length);
                            mrp = Arrays.copyOf(product.getMrp(),
                                    product.getMrp().length);
                            discount = Arrays.copyOf(product.getDiscountpercent(),
                                    product.getDiscountpercent().length);
                            image = Arrays.copyOf(product.getProductimageSmall1(),
                                    product.getProductimageSmall1().length);
                            cus_agg_num = Arrays.copyOf(product.getCustratingAggNum(),
                                    product.getCustratingAggNum().length);

                        }
                    }).run();

                    setAdapter();
                }

                @Override
                public void failure(RetrofitError error) {
                    tv_title_header.setText(error.getMessage());
                    Log.e("error", error.getMessage());
                }
            });
}

void setAdapter() {
    adapter = new ProductListingGridAdapter(this, title, image, price, mrp, discount);
    gv_product_listing_act.setAdapter(adapter);
}

}

The init() in OnCreate() will initialise all the view and call the productListingApiCall() for the first time. The way the api works is that, i will request for the first 10 items (start_row_condition: 0 and limit: 10), then on reaching the bottom after scrolling it should add the next 10, hence i need to call the api with (start_row_condition: 10 and limit:10). How can i implement this.


text:
Q: openSSL key block access function? I am stuck to retrieve the Key_block generated after the SSL handshake. I implemented a simple Client.cpp/Server.cpp program that is working well for exchanging encrypted data.
I would like to retrieve the key_block because I want to re-use it and perform my own encryption in another communication, but without having another handshake again.
I tried :
ssl->s3->tmp.key_block

but it retrieves an empty string (?!) and of course
ssl->s3->tmp.key_block_length

retrieves 0 value.
I call these methods just after SSL_accept(ssl) succeeds.
Once I've been able to catch this key_block, I'll need to find the encryption function used by SSL_write(...)
Hope you hear me, because the openSSL doc seems encrypted to my eyes.. =)

A: XY problem. You don't need this. Just open another SSL connection to the same target and it should re-use the same SSL session and therefore the same session master secret. Maybe even the same session key, but what do you care, as long as it's secure? You seem to be just trying to avoid a second full SSL handshake, but you can do that by suitable configuration at the client.


text:
Q: Magento tries to load resources from non existing folder pub/static/version1562677664/ I copied a working magento installation 1:1 from one server to another, but many important files can't get loaded and the site is broken.
I only deleted the folder pub/static and executed php bin/magento setup:static-content:deploy on the clone after copying the clone to the new server.

I get this in my log (snippet):
Refused to apply style from 'http://entwicklung.m2/pub/static/version1562677664/frontend/Magento/luma/de_DE/css/styles-m.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.

GET http://entwicklung.m2/pub/static/version1562677664/frontend/Magento/luma/de_DE/requirejs/require.js net::ERR_ABORTED 404 (Not Found)

...

(index):44 Uncaught TypeError: require.config is not a function
at (index):44

A: Can you please do with code
INSERT INTO `core_config_data`(`path`, `value`) VALUES ('dev/static/sign', 0) ON DUPLICATE KEY UPDATE `value`=0

than update your .htaccess file
    <IfModule mod_rewrite.c>
    RewriteEngine On

    RewriteBase /pub/static
    # Remove signature of the static files that is used to overcome the browser cache
    RewriteRule ^version.+?/(.+)$ $1 [L]

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-l

    RewriteRule .* ../static.php?resource=$0 [L]
</IfModule>

then execute next command to clear a configuration cache:
bin/magento cache:clean config

I hope its work for you.


text:
Q: Android - Moving Cursor position from Motion Sensor Input I'm working in Eclipse, using the Libgdx game framework to develop an Android application, where I'm attempting to move a 2D cursor based on the general movements of the Android device. As I've read from countless sources already, this is a much harder task than it sounds, due to the wide margin of error that appears during calculation.
What I've done so far is pretty primitive; pass across a composite "linear acceleration sensor" from Android, use the acceleration values to calculate velocity, use velocity to calculate displacement, add that onto my cursor's x,y coordinates, and lastly make sure the cursor does not exceed the screen's dimensions. I don't think it really needs a code example, but here's a watered down version of the core code;
//class attributes
Vector2 accel, prevAccel;
Vector2 velocity;
Vector2 cursorPos;
IMyLinearAccelerationSensor las;

//update code
accel = new Vector2(las.getAccelXY); //returns a Vector2 with the x and y acceleration values
velocity.x = (accel.x + prevAccel.x) /2 * deltaTime;
velocity.y = (accel.y + prevAccel.y) /2 * deltaTime;
cursorPos.x += tempAccel.x * deltaTime;
cursorPos.y += tempAccel.y * deltaTime;

prevAccel = accel; //update the "previous acceleration"

if (cursorPos.x < 0)
   cursorPos.x = 0;
if (cursorPos.y < 0)
   cursorPos.y = 0; //etc.

The main issues I'm encountering are drift, and the fact that the sensor appears to be more sensitive to movements in the positive directions of x, and y (I think). In other words, the cursor accelerates/ drifts off, gets stuck in the top left corner of the screen, and the respective velocities for x and y never really fall back to 0. Even when moving the device in the opposite direction, the velocity only decreases slightly.
Given all of this information, I just wanted to ask some questions, and for some advice. Firstly, is this is normal behavior, or are there any glaring problems with my code?
If not, are there any steps that can be taken with my current setup, to resolve these problems with drift, and remove some margin of error? e.g. applying different filters to remove noise, applying a resistive force to the velocity, etc.
I don't need the movement of the cursor to follow the device's movements too accurately; so long as it moves when the device moves, and stops generally when the device stops, I don't mind if there's some small drifting, or lag.
I was considering to at some point implement more interfaces to get the raw data from the Android hardware sensors (compass, gyroscope, and accelerometer), to generate more accurate results, but even if I do go ahead with this, would this improve much? Knowing that this is a complex problem, I'd rather not spend too much time on it without good reason. (sensor fusion from scratch definitely seems hard...)
Lastly, I'm sorry about the lengthy post, and also sorry if this is considered a repeat question. I've done research, and have seen plenty of other people with similar issues, but I'm not quite sure how their solutions might be applied to my own problem. Given my limited knowledge/ experience, I'd appreciate any helpful insight that can be offered.


text:
Q: Google Cloud CLOUD NATURAL LANGUAGE API I am trying to use Google Cloud CLOUD NATURAL LANGUAGE API.
I already have Google cloud running Account.
I enabled CLOUD NATURAL LANGUAGE API service and generated Service account keys and downloaded locally.
I ham using Goggle default program
LanguageServiceClient language = LanguageServiceClient.create();

// The text to analyze
String text = "My stay at this hotel was not so good";
Document doc = Document.newBuilder().setContent(text).setType(Type.PLAIN_TEXT).build();

// Detects the sentiment of the text
Sentiment sentiment = language.analyzeSentiment(doc).getDocumentSentiment();

System.out.printf("Text: %s%n", text);
System.out.printf("Sentiment: %s, %s%n", sentiment.getScore(), sentiment.getMagnitude());

I am using Eclipse as IDE on Mac
When I run application I got error
java.io.IOException: The Application Default Credentials are not available. They are available if running in Google Compute E
ngine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs
/application-default-credentials for more information.

I even added GOOGLE_APPLICATION_CREDENTIALS as export in Terminal and on using "printenv" it shows the Path like this
GOOGLE_APPLICATION_CREDENTIALS=/Users/temp/Downloads/Sentiment-0e556940c1d8.json

Still it wasn't working with some hit and trial method I found out that in eclipse we can configure run.
There I have added environment variable and after that when I run program it works fine.
Now MY problem is I am implementing that code inside J2EE project and that ear file is to  deploy in Wildfly.
I am again getting same error. Now I dont know where to set enviromnet variable in Wildfly or where???

A: Finally I found a way to set up GOOGLE_APPLICATION_CREDENTIALS as environment variable inside Wildfly

*

*If you are running server through Eclipse

*

*Open Wildfly Server setting by double clicking your server inside
Server Tab

*Click "Open Launch Configuration"

*Move to "Environment" tab and add new variable as key value pair

eg
GOOGLE_APPLICATION_CREDENTIALS  /Users/temp/Downloads/Sentiment-0e556940c1d8.json

*If you are running server using terminal
By default Wildfly looks for additional setting inside standalone.conf file.
just open wildfly/bin/standalone.conf file and add following line
GOOGLE_APPLICATION_CREDENTIALS=/Users/temp/Downloads/Sentiment-0e556940c1d8.json
Thats it. You are good to go.....


text:
Q: Create Gtk toolbar with buttons and text in PyGobject I found a couple of tutorials (PyGTK) that use this code:
    from gi.repository import Gtk

    [...]

    self.toolbar = Gtk.Toolbar()
    self.toolbar.set_style(Gtk.TOOLBAR_BOTH)

    [...]

but using Python3 and GTK3 (PyGobject) I get the message:
AttributeError: 'gi.repository.Gtk' object has no attribute 'TOOLBAR_BOTH'
Does anyone know how to handle this in PyGobject?

A: Most likely Gtk.ToolbarStyle.BOTH; to convert a C constant to Python like GTK_TOOLBAR_BOTH which is a member of the GtkToolbarStyle enum, it's (module name).(enum name without module name).(constant name without enum prefix).