text:
Q: How to filter lt of time I'm wondering how to filter many time variables.
ActiveSheet.Range("$F$4:$G$18").AutoFilter Field:=3, Criteria1:=Array("11:45:00 AM", "11:46:00 AM", "11:47:00 AM", "11:48:00 AM", "11:49:00 AM" _
, "11:50:00 AM", "11:51:00 AM", "11:52:00 AM", "11:53:00 AM", "11:54:00 AM", "11:55:00 AM", "11:56:00 AM", "11:57:00 AM", "11:58:00 AM", "11:59:00 AM", _
"12:00:00 PM", "12:01:00 PM", "12:02:00 PM", "12:03:00 PM", "12:04:00 PM", "12:05:00 PM"), Operator:=xlFilterValues

this is how I have been filtering time but I'm wondering if there is a better way to do it. like asking the user in a box to type the start time and the end time and it will automatically filter the time.

enter image description here

A: this is from a recorded macro, modified to fit yours
    ActiveSheet.Range("$F$4:$G$18").AutoFilter Field:=3, Criteria1:=">=11:45:00 AM", Operator:=xlAnd, Criteria2:="<=12:05:00 PM"


text:
Q: Spring CXF Conduit SSL Client pointing at Soap UI Mock Service I am currently working on a Web Service client which will connect to a third party web service  using SSL.
The Web Service client has been developed using Spring and Apache CXF.
I do not have access to the third party web service at the moment and so I am using Soap UI to provide Mock Services.
When I do not attempt to implement any security the client can happily send requests to the Mock Service.
My issue is when I try and secure the connection between the client and server(the server being the mock service) using SSL.
This is the first time I have tried to implement a secure connection of any kind so I apologise if I am missing something fundamental however I have spent hours searching around the subject to no avail.
In order to attempt to secure the connection I have created a private key, self-signed certificate and truststore for both the client and the server using the Java keytool utility:
keytool -genkey -alias clientKey -keyalg RSA -keypass changeit -storepass changeit -keystore clientKeyStore.jks

keytool -export -alias clientKey -storepass changeit -file client.cer -keystore clientKeyStore.jks

keytool -genkey -alias serverKey -keyalg RSA -keypass changeit -storepass changeit -keystore serverKeyStore.jks

keytool -export -alias serverKey -storepass changeit -file server.cer -keystore serverKeyStore.jks

I have added the certificates from both keys to both of the trust stores:
keytool -import -v -trustcacerts -alias clientKey -file client.cer -keystore serverCaCerts.jks -keypass changeit

keytool -import -v -trustcacerts -alias clientKey -file client.cer -keystore clientCaCerts.jks -keypass changeit

keytool -import -v -trustcacerts -alias serverKey -file server.cer -keystore serverCaCerts.jks -keypass changeit

keytool -import -v -trustcacerts -alias serverKey -file server.cer -keystore clientCaCerts.jks -keypass changeit

I have then configured the Mock Services in Soap UI to use SSL security
KeyStore: C:\javaSecurity\serverKeyStore.jks
KeyStore Password: changeit
Enable Mock SSL: True (enable SSL for Mock Services)
Mock Port: 8443
Mock KeyStore: C:\javaSecurity\serverKeyStore.jks
Mock Password: changeit
Mock Key Password: changeit
Mock TrustStore: C:\javaSecurity\serverCaCerts.jks
Mock TrustStore Password: changeit
Client Authentication: false(does not require client authentication)

I have then set up the following config in my applicationContext.xml of the client:
<http:conduit name="*.http-conduit">
    <http:tlsClientParameters secureSocketProtocol="SSL" disableCNCheck="true">
        <sec:keyManagers keyPassword="changeit">
            <sec:keyStore type="JKS" password="changeit"
                          file="C:\\javaSecurity\\clientKeyStore.jks"/>
        </sec:keyManagers>
        <sec:trustManagers>
            <sec:keyStore type="JKS" password="changeit"
                          file="C:\\javaSecurity\\clientCaCerts.jks"/>
        </sec:trustManagers>
    </http:tlsClientParameters>

    <http:client AutoRedirect="true" Connection="Keep-Alive"/>
</http:conduit>

When I attempt to send a message from the client I get the following error from the client:
2014-01-28 14:17:36,094 DEBUG [ServiceThread] (LogUtils.java:443) - The SSL_RSA_EXPORT_WITH_DES40_CBC_SHA cipher suite is included by the filter.
2014-01-28 14:17:36,098 DEBUG [ServiceThread] (LogUtils.java:443) - The SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA cipher suite is included by the filter.
2014-01-28 14:17:36,099 DEBUG [ServiceThread] (LogUtils.java:443) - The SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA cipher suite is included by the filter.
2014-01-28 14:17:36,099 DEBUG [ServiceThread] (LogUtils.java:443) - The TLS_EMPTY_RENEGOTIATION_INFO_SCSV cipher suite is included by the filter.
2014-01-28 14:17:36,099 DEBUG [ServiceThread] (LogUtils.java:443) - The SSL_RSA_WITH_NULL_MD5 cipher suite is excluded by the filter.
2014-01-28 14:17:36,099 DEBUG [ServiceThread] (LogUtils.java:443) - The SSL_RSA_WITH_NULL_SHA cipher suite is excluded by the filter.
2014-01-28 14:17:36,099 DEBUG [ServiceThread] (LogUtils.java:443) - The SSL_DH_anon_WITH_RC4_128_MD5 cipher suite is excluded by the filter.
2014-01-28 14:17:36,100 DEBUG [ServiceThread] (LogUtils.java:443) - The TLS_DH_anon_WITH_AES_128_CBC_SHA cipher suite is excluded by the filter.
2014-01-28 14:17:36,100 DEBUG [ServiceThread] (LogUtils.java:443) - The SSL_DH_anon_WITH_3DES_EDE_CBC_SHA cipher suite is excluded by the filter.
2014-01-28 14:17:36,100 DEBUG [ServiceThread] (LogUtils.java:443) - The SSL_DH_anon_WITH_DES_CBC_SHA cipher suite is excluded by the filter.
2014-01-28 14:17:36,100 DEBUG [ServiceThread] (LogUtils.java:443) - The SSL_DH_anon_EXPORT_WITH_RC4_40_MD5 cipher suite is excluded by the filter.
2014-01-28 14:17:36,101 DEBUG [ServiceThread] (LogUtils.java:443) - The SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA cipher suite is excluded by the filter.
2014-01-28 14:17:36,101 DEBUG [ServiceThread] (LogUtils.java:443) - The TLS_KRB5_WITH_RC4_128_SHA cipher suite is included by the filter.
2014-01-28 14:17:36,101 DEBUG [ServiceThread] (LogUtils.java:443) - The TLS_KRB5_WITH_RC4_128_MD5 cipher suite is included by the filter.
2014-01-28 14:17:36,101 DEBUG [ServiceThread] (LogUtils.java:443) - The TLS_KRB5_WITH_3DES_EDE_CBC_SHA cipher suite is included by the filter.
2014-01-28 14:17:36,102 DEBUG [ServiceThread] (LogUtils.java:443) - The TLS_KRB5_WITH_3DES_EDE_CBC_MD5 cipher suite is included by the filter.
2014-01-28 14:17:36,102 DEBUG [ServiceThread] (LogUtils.java:443) - The TLS_KRB5_WITH_DES_CBC_SHA cipher suite is included by the filter.
2014-01-28 14:17:36,102 DEBUG [ServiceThread] (LogUtils.java:443) - The TLS_KRB5_WITH_DES_CBC_MD5 cipher suite is included by the filter.
2014-01-28 14:17:36,103 DEBUG [ServiceThread] (LogUtils.java:443) - The TLS_KRB5_EXPORT_WITH_RC4_40_SHA cipher suite is included by the filter.
2014-01-28 14:17:36,104 DEBUG [ServiceThread] (LogUtils.java:443) - The TLS_KRB5_EXPORT_WITH_RC4_40_MD5 cipher suite is included by the filter.
2014-01-28 14:17:36,104 DEBUG [ServiceThread] (LogUtils.java:443) - The TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA cipher suite is included by the filter.
2014-01-28 14:17:36,104 DEBUG [ServiceThread] (LogUtils.java:443) - The TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5 cipher suite is included by the filter.
2014-01-28 14:17:36,104 DEBUG [ServiceThread] (LogUtils.java:443) - The enabled cipher suites have been filtered down to [SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_DES_CBC_SHA, SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, TLS_KRB5_WITH_RC4_128_SHA, TLS_KRB5_WITH_RC4_128_MD5, TLS_KRB5_WITH_3DES_EDE_CBC_SHA, TLS_KRB5_WITH_3DES_EDE_CBC_MD5, TLS_KRB5_WITH_DES_CBC_SHA, TLS_KRB5_WITH_DES_CBC_MD5, TLS_KRB5_EXPORT_WITH_RC4_40_SHA, TLS_KRB5_EXPORT_WITH_RC4_40_MD5, TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA, TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5].
2014-01-28 14:17:36,105 DEBUG [ServiceThread] (LogUtils.java:443) - The excluded cipher suites have been filtered down to [SSL_RSA_WITH_NULL_MD5, SSL_RSA_WITH_NULL_SHA, SSL_DH_anon_WITH_RC4_128_MD5, TLS_DH_anon_WITH_AES_128_CBC_SHA, SSL_DH_anon_WITH_3DES_EDE_CBC_SHA, SSL_DH_anon_WITH_DES_CBC_SHA, SSL_DH_anon_EXPORT_WITH_RC4_40_MD5, SSL_DH_anon_EXPORT_WITH_DES40_CBC_SHA].
2014-01-28 14:17:36,107 DEBUG [ServiceThread] (LogUtils.java:443) - The cipher suites have been set to SSL_RSA_WITH_RC4_128_MD5, SSL_RSA_WITH_RC4_128_SHA, TLS_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_RSA_WITH_AES_128_CBC_SHA, TLS_DHE_DSS_WITH_AES_128_CBC_SHA, SSL_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA, SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA, SSL_RSA_WITH_DES_CBC_SHA, SSL_DHE_RSA_WITH_DES_CBC_SHA, SSL_DHE_DSS_WITH_DES_CBC_SHA, SSL_RSA_EXPORT_WITH_RC4_40_MD5, SSL_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA, SSL_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA, TLS_EMPTY_RENEGOTIATION_INFO_SCSV, TLS_KRB5_WITH_RC4_128_SHA, TLS_KRB5_WITH_RC4_128_MD5, TLS_KRB5_WITH_3DES_EDE_CBC_SHA, TLS_KRB5_WITH_3DES_EDE_CBC_MD5, TLS_KRB5_WITH_DES_CBC_SHA, TLS_KRB5_WITH_DES_CBC_MD5, TLS_KRB5_EXPORT_WITH_RC4_40_SHA, TLS_KRB5_EXPORT_WITH_RC4_40_MD5, TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA, TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5.
2014-01-28 14:17:36,107 DEBUG [ServiceThread] (Headers.java:257) - Accept: */*
2014-01-28 14:17:36,107 DEBUG [ServiceThread] (HTTPConduit.java:1707) - No Trust Decider for Conduit '{http://cxf.apache.org}TransportURIResolver.http-conduit'. An afirmative Trust Decision is assumed.
2014-01-28 14:17:36,247 DEBUG [ServiceThread] (DefaultResourceManager.java:103) - resolving resource <https://pc-1049:8443/mockServiceSOAPBinding?WSDL> as stream
2014-01-28 14:17:36,248 DEBUG [ServiceThread] (DefaultResourceManager.java:103) - resolving resource <https://pc-1049:8443/mockServiceSOAPBinding?WSDL> type <class java.net.URL>
2014-01-28 14:17:36,248 DEBUG [ServiceThread] (HTTPConduit.java:895) - Conduit '{http://cxf.apache.org}TransportURIResolver.http-conduit' has been (re)configured for plain http.
2014-01-28 14:17:36,249 DEBUG [ServiceThread] (HTTPConduit.java:361) - No Trust Decider configured for Conduit '{http://cxf.apache.org}TransportURIResolver.http-conduit'
2014-01-28 14:17:36,249 DEBUG [ServiceThread] (HTTPConduit.java:374) - No Auth Supplier configured for Conduit '{http://cxf.apache.org}TransportURIResolver.http-conduit'
2014-01-28 14:17:36,249 DEBUG [ServiceThread] (HTTPConduit.java:393) - Conduit '{http://cxf.apache.org}TransportURIResolver.http-conduit' has been configured for plain http.
2014-01-28 14:17:36,249 DEBUG [ServiceThread] (AbstractObservable.java:46) - registering incoming observer: org.apache.cxf.transport.TransportURIResolver$1@76e1db

In the SOAP UI log I get the following error message:
javax.net.ssl.SSLHandshakeException: Received fatal alert: certificate_unknown
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.Alerts.getSSLException(Unknown Source)
at sun.security.ssl.SSLSocketImpl.recvAlert(Unknown Source)
at sun.security.ssl.SSLSocketImpl.readRecord(Unknown Source)
at sun.security.ssl.SSLSocketImpl.performInitialHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at sun.security.ssl.SSLSocketImpl.startHandshake(Unknown Source)
at org.mortbay.jetty.security.SslSocketConnector$SslConnection.run(SslSocketConnector.java:708)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)

Could anybody help me and point out what I may be missing?
As I mentioned earlier I do not have much experience in the area and so please do not think something is too fundamental to mention - if I've not mentioned it there is a good chance I've missed it!
Thankyou in advance to anyone who replies.

A: The cause of this issue turned out to be where I was defining my http:conduit settings.
I had included the http-conduit definition in my applicationContext.xml
It in fact needed to be defined in a separate cxf.xml file located on the classpath.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best design pattern for integrating third-party api or services I am integrating some outside APIs into a layered application. Like usual layered apps, it has three layers and I am hooking up those APIs into business layer. By "Thrid party API and services", I mean like payment gateways, postcode look ups, etc.
Currently, for each api, I create a service contract interface and api wrappers will inherit the interface class. And this interface will be injected into business classes' constructors and ioc container will resolve this at the entry point of application.
I would like to decouple those api layers with business layers and make them re-usable in other projects as well. My question is that, is there any better way or any design pattern to use with integrating outside services. I do appreciate any link to guides or code snippets.

A: If you want to make a pluggable framework for your third-party API services, you might want to look into MEF. This would enable you to create a more agnostic type of service provisioning, meaning that you can swap in/out services from the framework - which might make it easier to integrate current and future external services into your app without having to incur significant refactor costs.
http://msdn.microsoft.com/en-us/library/dd460648.aspx

A: For each third party API I would create an interface an put this in a separate project. Then I would create a new project for the implementation of each interface.
For example your project structure could look like
YourSolution
  ...
  -Company.Interfaces.ThridPartyAPi1
  -Company.Interfaces.ThridPartyAPi2
  -Company.Interfaces.ThridPartyAPi3

  -Company.Services.ThridPartyAPi1
  -Company.Services.ThridPartyAPi2
  -Company.Services.ThridPartyAPi3
  ...

This decouples your code from the API code and decouples the API interfaces from API code, which means that it can be easily mocked/stubbed out for testing.


text:
Q: (Un)docking of editors in an eclipse RCP application In an eclipse RCP application you can dock/undock views on default.
But it seems you can't do the same with editors.
Is there any chance to configure such an application to (un)dock editors?

A: In Eclipse 3.x it is not possible, but 4.1 definitely has this feature (I just tried it). You can get it here: http://download.eclipse.org/e4/sdk/

A: IMHO its not possible for Editors, its a known limitation of eclipse editors!

A: If you want the ability to view editors side by side there are a few alternative options.
You can drag an editor "to the side" of an existing editor, making eclipse split the workbench page in two (or more), this is natively supported in RCP apps as well.
Another option is to create a separate workbench window (see Window -> New Window in Eclipse IDE). Once that is done, you can drag the editors between the windows. This works especially well if you work with several monitors. I'm guessing it should be possible to reuse the "New Window" action to make this happen in an RCP app as well.
The "new" window feature might be tweaked to make it seem like you can just drag an editor "off workbench" but I think that solution will be more painful than helpful.
Eclipse 4.x is said to have this ability but it isn't planned to ship until summer 2012.
It may be possible using the e4-project plugins, but I haven't tested.


text:
Q: Counting question and cardinality A football league contains $6$ teams. During the season each team plays two matches against each other team. The result of each match is a draw or a win for one or other team. How many matches are played in the season? How many possibilities are there for full list of results for all matches played in the season?
My answer - total matches played is $\dfrac{6\times 10}{2}= 30$ or
How would I also calculate the different possibilities? Is it $6 \times 5$?

A: Each team plays 5 other teams twice each (one home, one away). So each team plays 10 matches. So there are 30 matches played in total (not 60, because otherwise you will double count each match).
The three possibilities for each match are a home win, an away win, or a draw.
The number of total possibilities for the full list of results $3^{30}.$


text:
Q: Replace a set of pattern matches with corresponding replacement strings in R The str_replace (and preg_replace) function in PHP replaces all occurrences of the search string with the replacement string. What interests me the most here, is that if search and replace args are arrays (in R we call that vectors), then str_replace takes a value from each array (vector) and uses them to search and replace on subject.
In other words, does R (or some R package) have a function to perform the following:
string <- "The quick brown fox jumped over the lazy dog."
patterns     <- c("quick", "brown", "fox")
replacements <- c("slow",  "black", "bear")
xxx_replace_xxx(string, patterns, replacements)          ## ???
## [1] "The slow black bear jumped over the lazy dog."

So I am seeking for something like chartr, but for search patterns and replacement strings of arbitrary number of characters. This cannot be done via one call to gsub() as its replacement argument can be a single string only, see ?gsub. So my current implementation is like:
xxx_replace_xxx <- function(string, patterns, replacements) {
   for (i in seq_along(patterns))
      string <- gsub(patterns[i], replacements[i], string, fixed=TRUE)
   string
}

However, I am looking for something much faster if length(patterns) is large - I have a lot of data to process and I'm dissatisfied with the current results.
Exemplary toy data for benchmarking:
string <- readLines("http://www.gutenberg.org/files/31536/31536-0.txt", encoding="UTF-8")
patterns <- c("jak", "to", "do", "z", "na", "i", "w", "za", "tu", "gdy",
   "po", "jest", "Tadeusz", "lub", "razem", "nas", "przy", "oczy", "czy",
   "sam", "u", "tylko", "bez", "ich", "Telimena", "Wojski", "jeszcze")
replacements <- paste0(patterns, rev(patterns))

A: If the patterns are fixed strings made of word characters as in the example then this works.  gsubfn is like gsub except the replacment argument can be a string, list, function or proto object.  If its a list, as here, it compares the matches to the regular expression with the names and for those that are found it replaces them with the corresponding values:
library(gsubfn)

gsubfn("\\b\\w+\\b", as.list(setNames(replacements, patterns)), string)
## [1] "The slow black bear jumped over the lazy dog."

A: This can be done with stringi >= 0.3-1 by using one of the stri_replace_*_all functions with the vectorize_all argument set to FALSE:
library("stringi")
string <- "The quicker brown fox jumped over the lazy dog."
patterns     <- c("quick", "brown", "fox")
replacements <- c("slow",  "black", "bear")
stri_replace_all_fixed(string, patterns, replacements, vectorize_all=FALSE)
## [1] "The slower black bear jumped over the lazy dog."
stri_replace_all_regex(string, "\\b" %s+% patterns %s+% "\\b", replacements, vectorize_all=FALSE)
## [1] "The quicker black bear jumped over the lazy dog."

Some benchmarks:
string <- readLines("http://www.gutenberg.org/files/31536/31536-0.txt", encoding="UTF-8")
patterns <- c("jak", "to", "do", "z", "na", "i", "w", "za", "tu", "gdy",
   "po", "jest", "Tadeusz", "lub", "razem", "nas", "przy", "oczy", "czy",
   "sam", "u", "tylko", "bez", "ich", "Telimena", "Wojski", "jeszcze")
replacements <- paste0(patterns, rev(patterns))
microbenchmark::microbenchmark(
   stri_replace_all_fixed(string, patterns, replacements, vectorize_all=FALSE),
   stri_replace_all_regex(string, "\\b" %s+% patterns %s+% "\\b", replacements, vectorize_all=FALSE),
   xxx_replace_xxx_pcre(string, "\\b" %s+% patterns %s+% "\\b", replacements),
   gsubfn("\\b\\w+\\b", as.list(setNames(replacements, patterns)), string),
   unit="relative",
   times=25
)
## Unit: relative
##                   expr       min        lq      mean    median        uq       max neval
## stri_replace_all_fixed  1.000000  1.000000  1.000000  1.000000  1.000000  1.000000    25
## stri_replace_all_regex  2.169701  2.248115  2.198638  2.267935  2.267635  1.753289    25
## xxx_replace_xxx_pcre    1.983135  1.967303  1.937021  1.961449  1.974422  1.469894    25
## gsubfn                 63.067835 69.870657 69.815031 71.178841 72.503020 57.019072    25

So, as far as matching only at word boundaries is concerned, the PCRE-based version is the fastest.

A: Using PCRE instead of fixed matching takes ~1/3 the time on my machine for your example.
xxx_replace_xxx_pcre <- function(string, patterns, replacements) {
   for (i in seq_along(patterns))
      string <- gsub(patterns[i], replacements[i], string, perl=TRUE)
   string
}
system.time(x <- xxx_replace_xxx(string, patterns, replacements))
#    user  system elapsed
#   0.491   0.000   0.491
system.time(p <- xxx_replace_xxx_pcre(string, patterns, replacements))
#    user  system elapsed
#   0.162   0.000   0.162
identical(x,p)
# [1] TRUE


text:
Q: Miniaturise all windows with AppleScript tell application "System Events"
    set mywindows to windows of (processes where background only is false)
    repeat with theItem in windows of (processes where background only is false)
        set miniaturized of theItem to true
    end repeat
end tell

I get
error "System Events got an error: Can't set miniaturized of UI element to any." number -10006 from miniaturized of UI element to any

A: I answered a similar question over on Stack Overflow, around the time I was still working mostly in High Sierra.  Testing it today, it still works on Catalina.
Here's the salient part of that answer:
tell application id "com.apple.systemevents" to set the value of ¬
        attribute "AXMinimized" of every window of every process ¬
        to true

Unfortunately, it's not going to minimise them all simultaneously, which would be lovely.  It does them one-by-one, not necessary starting with the one that's right in front of you.  Therefore, if you have many windows open, it can appear at first that it's not doing anything, but in fact it's minimising windows obscured by the frontmost one), and they'll minimise in turn, which is fun to see the first time, but irksome every other time when you just want it done now.
Another point that @user3439894 kindly reminded me of is that System Events is only aware of objects that exist on the currently active desktop.  Therefore, this method won't be to minimise windows that are on other desktops/spaces are off-screen.
However, if you aren't specifically looking to minimise windows, but rather just get them out of sight, then you can elect to hide the processes instead:
tell application id "com.apple.systemevents" to ¬
        set visible of every process to false

The major annoyance here is that Finder remains visible, and will need to have an extra line of code after to get rid of its windows, which I suggest should be:
tell application id "com.apple.Finder" to set ¬
        miniaturized of every window to true

The benefits, however, are that all the windows across all desktops/screens will be gone, not just the ones on your current desktop; and this takes place very quickly, almost instantaneously (apart from Finder).  Activating the application by clicking on its dock icon for example, makes the process visible again; typically, this means that the application and all of its windows that were previously visible will re-appear en masse.  Whether that's a positive or negative will depend on your needs.

The reason your code doesn't work is because miniaturised is not a property of the window object belonging to the processes suite of System Events' AppleScript dictionary.  It is a property of window objects belonging to the standard suite of any scriptable application's AppleScript dictionary (including SystemEvents, although it doesn't have any windows of its own); despite sharing a common name, these two window class objects are distinct and unrelated objects in AppleScript.


text:
Q: Apologize for misunderstanding My English not very good, especially if I have to comply some formal standards. I understand it pretty well, but when I have to construct a sentence I face some difficulties.
So I will try to explain the situation.
My boss and me changed some emails. I the last email-reply from him I received, it seems to me that he felt my writings somehow keen.

so it seems we got a conflict of views of some kind. Which happens sometimes; please don't interpret it as a pressure. OK, we all are under some pressure from the Clients :) which I can't deny and which affects our workflow.

And now I want to apologize if I sounded somehow keen or intending to assert my point of view over his. Some ideas come to my mind, but my gut-feelings are telling me they are not good.
I was thinking about:

I am sorry if I sounded as if I have problems with your advises

or

I wanted by no means to sound like I have some sort of conflict with you.

To me these ^^^ sound not good. Some help please.

A: You are well on the way. Since you ask I will add a few corrections.
To start I will say that you have Exchanged some emails with your boss. My basic advice is to say things as simply as you can. The more words you and your boss use the further they get from the goal.
I am sorry if I sounded as if I have problems with your advises [advice]
might be
I am sorry if I sounds like I have problems with your opinions.
or
I am sorry if it seems like I have problems with your opinions.
Best to make things in the present tense;
I wanted by no means to sound like I have some sort of conflict with you.
might be
I do not want to sound like I have some sort of conflict with you.
or
I would not want to sound like I have any conflict with you.


text:
Q: In C, is the condition : "if(a != NULL)" the same as the condition "if(a)"? Let's say a is a pointer, and after allocating memory for it, I want to check if the memory was allocated successfully, I've seen two ways doing this :
if(a != NULL)

if(a)

What is the difference between the first and second statements ?

A:
is the condition : if(a != NULL) the same as the condition if(a)?

They achieve the same purpose. The only real difference is in readability.

Their effect is the same, since they will result in the same thing.
NULL is a macro that is almost always 0, so:
if(a != NULL)

is equivalent to:
if(a != 0)

which is pretty similar to:
if(a)

since it will check if the expression a evaluates to true.
So, if a is a pointer, they will be the same. If it's not, then it will depend on how NULL is defined (which as I said is almost always 0).

A: According to c faq :

if(p) is equivalent to    if(p != 0)
and this is a comparison context, so
the compiler can tell that the (implicit) 0 is actually a null pointer
constant, and use the correct null pointer value. There is no trickery
involved here; compilers do work this way, and generate identical code
for both constructs. The internal representation of a null pointer
does not matter.

A: (a != NULL) return a boolean which is the same thing for (a).
An if statement return false if the content equals 0 and true otherwise.
NULL means 0 so if a == 0 the if return false.
So it's exactly the same thing for the compiler.
Hope it helps you !

A: There's no functional difference; they are equivalent and they both test for null pointer.
Any preference is purely subjective. Just use one you like or the what's followed by your fellow programmers in your project/organization.


text:
Q: Redis, Python message over network I am running a redis server and publisher one machine and a subscriber on another machine on the same network. Whenever I publish a message it does not get received on the other machine.
Here is Publisher:
import redis
import time
pub = redis.Redis(host='localhost', password="xxxxx", decode_responses=True)

pub.publish('chan:1', "test message")
time.sleep(20)

Here is subscriber
import redis
host='192.000.0.10'

sub = redis.Redis(host, password="xxxxxx", decode_responses=True)

s = sub.pubsub()
s.subscribe('chan:1')

s.get_message()
message = s.get_message() ['data']
print(message)

When I run all I get is
none
Interestingly if I change the last lines to:
for message in s.listen():
    print(message['data'])

I get the correct message
test message
Also, I cannot find any documentation on the "listen" command (other than a mention in another question)
Any ideas/comments on what is going on?


text:
Q: Storing push notifications locally on app Currently, I'm able to display, push notifications and able to display on Recycler View. However, whenever I close the app and reopen, the push notifications will be gone.
I read that using SharedPreferences will save but it doesn't save my notifications and I don't really know how to implement it into my codes. I want my notifications to be displayed when I open the app.
Another problem that I have just encountered with SharedPreferencecs is that each new push notification I send will replace the old notifications. For example, if I send a notification message "test" and the second notification message "test2", test2 will overwrite the test. I was able to successfully display all the notifications, but after implementing SharedPreferences, I get the overwritten values.

NotificationFragment.java
public class NotificationFragment extends Fragment {
    private TextView test;
    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;
    private List<Notification> notificationList;
    private BroadcastReceiver activityReceiver;
    private String MyPREFERENCES = "test";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_notification, container, false);

        mRecyclerView = (RecyclerView) v.findViewById(R.id.notificationRecyclerview);
        notificationList = new ArrayList<>();
        mAdapter = new NotificationAdapter(getContext(), notificationList);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setHasFixedSize(true);
        mLayoutManager = new LinearLayoutManager(getActivity());
        mRecyclerView.setLayoutManager(mLayoutManager);

        activityReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Bundle bundle = intent.getBundleExtra("msg");
                String body = bundle.getString("msgBody");
                SharedPreferences sharedpreferences = getContext().getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString("notification", body);
                editor.apply();
                Log.d("body", body);
                Notification obj = new Notification(body);
                prepareNotification(obj.getBody());

            }

        };

        if (activityReceiver != null) {
            IntentFilter intentFilter = new  IntentFilter("ACTION_STRING_ACTIVITY");
            getActivity().registerReceiver(activityReceiver, intentFilter);
        }

        return v;
    }

    private void prepareNotification(String body){
        Notification obj = new Notification(body);
        notificationList.add(obj);
        mAdapter = new NotificationAdapter(getContext(), notificationList);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.notifyDataSetChanged();
    }

}

NotificationAdapter.java
public class NotificationAdapter extends RecyclerView.Adapter<NotificationAdapter.NotificationHolder> {
    private List<Notification> notificationList;
    private Context mContext;
    private String MyPREFERENCES = "test";
    public SharedPreferences prefs;

    public NotificationAdapter(Context mContext, List<Notification> notificationList) {
        this.mContext = mContext;
        this.notificationList = notificationList;
        prefs = mContext.getSharedPreferences(MyPREFERENCES, MODE_PRIVATE);
    }

    @Override
    public NotificationHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View inflatedView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.list_item_notification, parent, false);
        return new NotificationHolder(inflatedView);
    }

    @Override
    public void onBindViewHolder(final NotificationHolder holder, int position) {
        Notification notification = notificationList.get(position);
//        String restoredText = prefs.getString("text", null);
//        holder.body.setText("Notification Message" + notification.getBody());
        holder.body.setText("Notification Message: " + prefs.getString("notification", "No notifcation"));

    }

    @Override
    public int getItemCount() {
        return notificationList.size();
    }

    public class NotificationHolder extends RecyclerView.ViewHolder {
        public TextView body;

        public NotificationHolder(View view) {
            super(view);
            body = (TextView) view.findViewById(R.id.bodyMsg);
        }
    }
}


text:
Q: Making a 4 digit pin in tkinker I'm working with tkinker python and trying to make a 4 digit pin lock screen. Im trying to draw white squares for each digit and I can not figure out how to manipulate the api in a way to get a perfect square. What am I doing wrong, how can I do this? Here is my code

from tkinter import *

class app(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        master.configure(background="#262626")
        master.wm_iconbitmap('moth.ico')
        master.title("Moth")
        master.geometry("800x600")
        self.widgets()
        self.pack()
    def widgets(self):
        backGroundCanvas = Canvas(self, bg='#262626', width=800, height=600)
        backGroundCanvas.focus_set()
        backGroundCanvas.pack()

        #create pin
        backGroundCanvas.create_rectangle(self, meme=1)

root = Tk()
app = app(master=root)
app.mainloop()

Cheers!

A: Create a square rectangle with white fill.  This is a good reference.  I removed the reference to an icon I don't have.
from tkinter import *

class app(Frame):
    def __init__(self, master=None):
        super().__init__(master)
        master.configure(background="#262626")
        master.title("Moth")
        master.geometry("800x600")
        self.widgets()
        self.pack()
    def widgets(self):
        backGroundCanvas = Canvas(self, bg='#262626', width=800, height=600)
        backGroundCanvas.focus_set()
        backGroundCanvas.pack()

        #create pin
        backGroundCanvas.create_rectangle(100, 100, 200, 200, fill='white')

root = Tk()
app = app(master=root)
app.mainloop()


text:
Q: What is the enum for - (minus/underscore) and = (equal/plus) key in Keys enumeration? I can't seem to find them here.
I'm trying to get them include in my hotkey selection dialog.

A: Would OemMinus and OemPlus work for you?

A: Checkout Oem*, from the link that you provided:
OemMinus    The OEM minus key on any country/region keyboard (Windows 2000 or later).
Oemplus     The OEM plus key on any country/region keyboard (Windows 2000 or later).

You can have something like:
if (keyData == (Keys.Control | Keys.OemMinus) ) ZoomOutOrSomething();//


text:
Q: DataContext name of WPFToolkit DataGrid shows in columns header background I've got a strange problem with WPFToolkit DataGrid - after disabling AutoGenerateColumns, after adding only 1, narrow column, in the background of column headers appears full name of DataContext. It doesn't behave like a column - I can't neither resize or disable it.
Previously I didn't know about this problem, because I had few wide enough columns, but know this is a serius problem.
This is my code:
<Window.DataContext>
    <model:ShowUnitViewModel/>
</Window.DataContext>
<StackPanel>
    <toolkit:DataGrid ItemsSource="{Binding Items}">
        <toolkit:DataGrid.Columns>
            <toolkit:DataGridTextColumn Header="{x:Static lang:Unit.Name}" Binding="{Binding Path=Name}"/>
        </toolkit:DataGrid.Columns>
    </toolkit:DataGrid>
</StackPanel>

A: Problem resolved.
The reason was wrong binding in DataGridColumnHeader template - I've created my own template with ContentPresenter without binding and works fine.
Previously was something like binding {Binding} in the content which caused the problem


text:
Q: Send POST parameters with MultipartFormData using Alamofire, in iOS Swift I am using Alamofire, very first time. I am using the latest version Alamofire 1.3.1. I want to send one image , one video and some POST parameters in one API call. I am using multipart form data. The mutipart module is working. I am facing a problem to send extra POST parametersparams . Below is my code. "params" is the dictionary which contains extra parameters? How can I append these POST parameters in the request. Please help
        var fullUrl :String = Constants.BASE_URL + "/api/CompleteChallenge"
         var params = [
        "authKey": Constants.AuthKey,
        "idUserChallenge": "16",
        "comment": "",
        "photo": imagePath,
        "video": videoPath,
        "latitude": "1",
        "longitude": "1",
        "location": "india"
    ]

    let imagePathUrl = NSURL(fileURLWithPath: imagePath!)
    let videoPathUrl = NSURL(fileURLWithPath: videoPath!)

        Alamofire.upload(
        .POST,
        URLString: fullUrl, // http://httpbin.org/post
        multipartFormData: { multipartFormData in
            multipartFormData.appendBodyPart(fileURL: imagePathUrl!, name: "photo")
            multipartFormData.appendBodyPart(fileURL: videoPathUrl!, name: "video")
        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { request, response, JSON, error in

                  }
                }
            case .Failure(let encodingError):

            }
        }
    )

A: Swift 3 / Alamofire 4.0 (Addendum to the accepted answer)
To append to multipartFormData in Swift 3 / Alamofire 4.0, use the following method of MultipartFormData:
public func append(_ data: Data, withName name: String) { /* ... */ }

And, to convert String to Data, the data(using:) method of String. E.g.,
multipartFormData.append("comment".data(using: .utf8)!, withName: "comment")

A: I found the solution :) finally.
We can append data in the request as multipartformdata.
Below is my code.
  Alamofire.upload(
        .POST,
        URLString: fullUrl, // http://httpbin.org/post
        multipartFormData: { multipartFormData in
            multipartFormData.appendBodyPart(fileURL: imagePathUrl!, name: "photo")
            multipartFormData.appendBodyPart(fileURL: videoPathUrl!, name: "video")
            multipartFormData.appendBodyPart(data: Constants.AuthKey.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"authKey")
            multipartFormData.appendBodyPart(data: "\(16)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"idUserChallenge")
            multipartFormData.appendBodyPart(data: "comment".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"comment")
            multipartFormData.appendBodyPart(data:"\(0.00)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"latitude")
            multipartFormData.appendBodyPart(data:"\(0.00)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"longitude")
            multipartFormData.appendBodyPart(data:"India".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"location")
        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { request, response, JSON, error in

                }
            case .Failure(let encodingError):

            }
        }
    )

EDIT 1: For those who are trying to send an array instead of float, int or string, They can convert their array or any kind of data-structure in Json String, pass this JSON string as a normal string. And parse this json string at backend to get original array

A: For Swift 4.2 / Alamofire 4.7.3
Alamofire.upload(multipartFormData: { multipart in
    multipart.append(fileData, withName: "payload", fileName: "someFile.jpg", mimeType: "image/jpeg")
    multipart.append("comment".data(using: .utf8)!, withName :"comment")
}, to: "endPointURL", method: .post, headers: nil) { encodingResult in
    switch encodingResult {
    case .success(let upload, _, _):
        upload.response { answer in
            print("statusCode: \(answer.response?.statusCode)")
        }
        upload.uploadProgress { progress in
            //call progress callback here if you need it
        }
    case .failure(let encodingError):
        print("multipart upload encodingError: \(encodingError)")
    }
}

Also you could take a look at CodyFire lib it makes API calls easier using Codable for everything.
Example for Multipart call using CodyFire
//Declare your multipart payload model
struct MyPayload: MultipartPayload {
    var attachment: Attachment //or you could use just Data instead
    var comment: String
}

// Prepare payload for request
let imageAttachment = Attachment(data: UIImage(named: "cat")!.jpeg(.high)!,
                                 fileName: "cat.jpg",
                                 mimeType: .jpg)
let payload = MyPayload(attachment: imageAttachment, comment: "Some text")

//Send request easily
APIRequest("endpoint", payload: payload)
    .method(.post)
    .desiredStatus(.created) //201 CREATED
    .onError { error in
        switch error.code {
        case .notFound: print("Not found")
        default: print("Another error: " + error.description)
        }
    }.onSuccess { result in
        print("here is your decoded result")
    }
//Btw normally it should be wrapped into an extension
//so it should look even easier API.some.upload(payload).onError{}.onSuccess{}

You could take a look at all the examples in lib's readme

A: Alamofire 5 and above
AF.upload(multipartFormData: { multipartFormData in
    multipartFormData.append(Data("one".utf8), withName: "one")
    multipartFormData.append(Data("two".utf8), withName: "two")
},
to: "https://httpbin.org/post").responseDecodable(of: MultipartResponse.self) { response in
        debugPrint(response)
}

documentation link: multipart upload

A: In Alamofire 4 it is important to add the body data before you add the file data!
let parameters = [String: String]()
[...]
self.manager.upload(
    multipartFormData: { multipartFormData in
        for (key, value) in parameters {
            multipartFormData.append(value.data(using: .utf8)!, withName: key)
        }
        multipartFormData.append(imageData, withName: "user", fileName: "user.jpg", mimeType: "image/jpeg")
    },
    to: path,
    [...]
)

A: Swift 5, update @Ankush's Alamofire Code to
     var fullUrl = "http://httpbin.org/post" // for example

           Alamofire.upload(multipartFormData: { (multipartFormData) in
                multipartFormData.append( imagePathUrl! , withName: "photo")
                multipartFormData.append( videoPathUrl!,  withName: "video")
                multipartFormData.append(Constants.AuthKey.data(using: .utf8, allowLossyConversion: false)!, withName: "authKey")
                multipartFormData.append("16".data(using: .utf8, allowLossyConversion: false)!, withName: "idUserChallenge")
                multipartFormData.append("111".data(using: .utf8, allowLossyConversion: false)!, withName: "authKey")
                multipartFormData.append("comment".data(using: .utf8, allowLossyConversion: false)!, withName: "comment")
                multipartFormData.append("0.00".data(using: .utf8, allowLossyConversion: false)!, withName: "latitude")
                multipartFormData.append("0.00".data(using: .utf8, allowLossyConversion: false)!, withName: "longitude")
                multipartFormData.append("India".data(using: .utf8, allowLossyConversion: false)!, withName: "location")

            }, to: fullUrl, method: .post) { (encodingResult) in
                switch encodingResult {
                case .success(request: let upload, streamingFromDisk: _, streamFileURL: _):
                    upload.responseJSON { (response) in   // do sth     }
                case .failure(let encodingError):
                    ()
                }
            }

A: As in Swift 3.x for upload image with parameter we can use below alamofire upload method-
static func uploadImageData(inputUrl:String,parameters:[String:Any],imageName: String,imageFile : UIImage,completion:@escaping(_:Any)->Void) {

        let imageData = UIImageJPEGRepresentation(imageFile , 0.5)

        Alamofire.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append(imageData!, withName: imageName, fileName: "swift_file\(arc4random_uniform(100)).jpeg", mimeType: "image/jpeg")

            for key in parameters.keys{
                let name = String(key)
                if let val = parameters[name!] as? String{
                    multipartFormData.append(val.data(using: .utf8)!, withName: name!)
                }
            }
        }, to:inputUrl)
        { (result) in
            switch result {
            case .success(let upload, _, _):

                upload.uploadProgress(closure: { (Progress) in
                })

                upload.responseJSON { response in

                    if let JSON = response.result.value {
                        completion(JSON)
                    }else{
                        completion(nilValue)
                    }
                }

            case .failure(let encodingError):
                completion(nilValue)
            }

        }

    }

Note: Additionally if our parameter is array of key-pairs then we can
  use

 var arrayOfKeyPairs = [[String:Any]]()
 let json = try? JSONSerialization.data(withJSONObject: arrayOfKeyPairs, options: [.prettyPrinted])
 let jsonPresentation = String(data: json!, encoding: .utf8)

A: Well, since Multipart Form Data is intended to be used for binary ( and not for text) data transmission, I believe it's bad practice to send data in encoded to String over it.
Another disadvantage is impossibility to send more complex parameters like JSON.
That said, a better option would be to send all data in binary form, that is as Data.
Say I need to send this data
let name = "Arthur"
let userIDs = [1,2,3]
let usedAge = 20

...alongside with user's picture:
let image = UIImage(named: "img")!

For that I would convert that text data to JSON and then to binary alongside with image:
//Convert image to binary
let data = UIImagePNGRepresentation(image)!

//Convert text data to binary
let dict: Dictionary<String, Any> = ["name": name, "userIDs": userIDs, "usedAge": usedAge]
userData = try? JSONSerialization.data(withJSONObject: dict)

And then, finally send it via Multipart Form Data request:
Alamofire.upload(multipartFormData: { (multiFoormData) in
        multiFoormData.append(userData, withName: "user")
        multiFoormData.append(data, withName: "picture", mimeType: "image/png")
    }, to: url) { (encodingResult) in
        ...
    }

A: This is how i solve my problem
let parameters = [
            "station_id" :        "1000",
            "title":      "Murat Akdeniz",
            "body":        "xxxxxx"]

let imgData = UIImageJPEGRepresentation(UIImage(named: "1.png")!,1)

    Alamofire.upload(
        multipartFormData: { MultipartFormData in
        //    multipartFormData.append(imageData, withName: "user", fileName: "user.jpg", mimeType: "image/jpeg")

            for (key, value) in parameters {
                MultipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
            }

        MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[1]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")
        MultipartFormData.append(UIImageJPEGRepresentation(UIImage(named: "1.png")!, 1)!, withName: "photos[2]", fileName: "swift_file.jpeg", mimeType: "image/jpeg")

    }, to: "http://platform.twitone.com/station/add-feedback") { (result) in

        switch result {
        case .success(let upload, _, _):

            upload.responseJSON { response in
                print(response.result.value)
            }

        case .failure(let encodingError): break
            print(encodingError)
        }

    }

A: for alamofire 4 use this ..
        Alamofire.upload(multipartFormData: { (multipartFormData) in

            multipartFormData.append(fileUrl, withName: "video")
       //fileUrl is your file path in iOS device and withName is parameter name

        }, to:"http://to_your_url_path")
        { (result) in
            switch result {
            case .success(let upload, _ , _):

                upload.uploadProgress(closure: { (progress) in

                    print("uploding")
                })

                upload.responseJSON { response in

                   print("done")

                }

            case .failure(let encodingError):
                print("failed")
                print(encodingError)

            }
        }

A: Found one more way of doing it
 if let parameters = route.parameters {

                    for (key, value) in parameters {
                         if value is String {
                            if let temp = value as? String {
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                        else if value is NSArray {
                            if let temp = value as? [Double]{
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                            else if let temp = value as? [Int]{
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                            else if let temp = value as? [String]{
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                        else if CFGetTypeID(value as CFTypeRef) == CFNumberGetTypeID() {
                            if let temp = value as? Int {
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                        else if CFGetTypeID(value as CFTypeRef) == CFBooleanGetTypeID(){
                            if let temp = value as? Bool {
                                multipartFormData.append(temp.description.data(using: .utf8)!, withName: key)
                            }
                        }
                    }
                }

                if let items: [MultipartData] = route.multipartData{
                    for item in items {
                        if let value = item.value{
                            multipartFormData.append(value, withName: item.key, fileName: item.fileName, mimeType: item.mimeType)
                        }
                    }
                }

A: Alamofire 5 with Array params
The issue for me was that my params could be any type. Converting to them to strings and then getting the data encoding worked for most, but I kept running into issues with arrays. For arrays you have to encode each element with a key denoting its index. This is how I ended up encoding my params so it would be dynamic for any type:
            let image = UIImage(named: "your image") // Change me
            let imageData = image.jpegData(compressionQuality: 1.0)!
            let imageKey = "image_key" // Change me
            let urlString = "https://yourserver.com/yourendpoint/" // Change me
            let params: [String: Any]? = [:] // Change me. Your POST params here
            let headers: HTTPHeaders = [
                // Change me. Your headers here.
            ]
            AF.upload(multipartFormData: { multiPart in
                for (key, value) in (params ?? [:]) {
                    if let arrayObj = value as? [Any] {
                        for index in 0..<arrayObj.count {
                            multiPart.append("\(arrayObj[index])".data(using: .utf8)!, withName: "\(key)[\(index)]")
                        }
                    } else {
                        multiPart.append("\(value)".data(using: .utf8)!, withName: key)
                    }
                }
                multiPart.append(imageData, withName: imageKey, fileName: "file.jpg", mimeType: "image/jpg")
            }, to: urlString, headers: headers).responseJSON { response in
                switch response.result {
                case .success(_):
                    if let dictionary = response.value as? [String:Any] {
                        print("success", dictionary)
                    } else {
                        print("error")
                    }
                case .failure(let error):
                    print("error", error.localizedDescription)
                }
            }

Also note that you have to append the image after appending all your params

A: func funcationname()
{

    var parameters = [String:String]()
    let apiToken = "Bearer \(UserDefaults.standard.string(forKey: "vAuthToken")!)"
    let headers = ["Vauthtoken":apiToken]
    let mobile = "\(ApiUtillity.sharedInstance.getUserData(key: "mobile"))"
    parameters = ["first_name":First_name,"last_name":last_name,"email":Email,"mobile_no":mobile]

    print(parameters)
    ApiUtillity.sharedInstance.showSVProgressHUD(text: "Loading...")
    let URL1 = ApiUtillity.sharedInstance.API(Join: "user/update_profile")
    let url = URL(string: URL1.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
    var urlRequest = URLRequest(url: url!)
    urlRequest.httpMethod = "POST"
    urlRequest.allHTTPHeaderFields = headers
    Alamofire.upload(multipartFormData: { (multipartFormData) in

        multipartFormData.append(self.imageData_pf_pic, withName: "profile_image", fileName: "image.jpg", mimeType: "image/jpg")

        for (key, value) in parameters {

            multipartFormData.append((value as AnyObject).data(using: String.Encoding.utf8.rawValue)!, withName: key)
        }

    }, with: urlRequest) { (encodingResult) in

        switch encodingResult {
        case .success(let upload, _, _):
            upload.responseJSON { response in
                if let JSON = response.result.value {
                    print("JSON: \(JSON)")
                    let status = (JSON as AnyObject).value(forKey: "status") as! Int
                    let sts = Int(status)
                    if sts == 200
                    {
                        ApiUtillity.sharedInstance.dismissSVProgressHUD()
                        let UserData = ((JSON as AnyObject).value(forKey: "data") as! NSDictionary)
                        ApiUtillity.sharedInstance.setUserData(data: UserData)

                    }
                    else
                    {
                        ApiUtillity.sharedInstance.dismissSVProgressHUD()

                        let ErrorDic:NSDictionary = (JSON as AnyObject).value(forKey: "message") as! NSDictionary

                        let Errormobile_no = ErrorDic.value(forKey: "mobile_no") as? String
                        let Erroremail = ErrorDic.value(forKey: "email") as? String

                        if Errormobile_no?.count == nil
                        {}
                        else
                        {
                            ApiUtillity.sharedInstance.dismissSVProgressHUDWithError(error: Errormobile_no!)
                        }
                        if Erroremail?.count == nil
                        {}
                        else
                        {
                            ApiUtillity.sharedInstance.dismissSVProgressHUDWithError(error: Erroremail!)
                        }
                    }

                }

            }

        case .failure(let encodingError):
            ApiUtillity.sharedInstance.dismissSVProgressHUD()
            print(encodingError)
        }

    }
}


text:
Q: How to convert JSON string to Python Object (Dictionary) I am having a weird issue. Running Django 3.0.1 and in my view I have a try statement.
For some reason I am not able to convert the JSON string to a Python Object (dict).
This is my code:
        try:
            message_to_clientsservice = {
                'id': id_id,
                'name': 'create-member-client-for-tenant-setup',
                'payload': {
                    'clientName': client_name,
                    'kbCorporationId': int(kb_corp_id),
                    'email': email,
                    'clientTypeId': client_type_id,
                    'address': {
                        'countryCode': country_code,
                    },
                    'phoneNumbers': []
                }
            }

            clientsservice_request_header = {
                'Content-Type': 'application/json',
                'ServiceAccessToken': service_access_token,
                'Ocp-Apim-Subscription-Key': ocp_apim_subscription_key,
                'Authorization': 'Bearer ' + bearer_token
            }

            # print(message_to_clientsservice)
            # print(type(message_to_clientsservice))
            # print(json.dumps(message_to_clientsservice))
            # print(type(clientsservice_request_header))
            # print(clientsservice_request_header)
            clients_service_response = requests.post(clientsservice_url,
                                                     headers=clientsservice_request_header,
                                                     data=json.dumps(message_to_clientsservice))
            print(clients_service_response.status_code)
            json_data_scrambledegg = clients_service_response.text
            for r in (('\\', ''), ('{\\', ''), ('\"\"}\"}', '\"\"}}'), ('\"payload\":\"', '\"payload\":')):
                json_data_scrambledegg = json_data_scrambledegg.replace(*r)
            print(type(json_data_scrambledegg))
            print(json_data_scrambledegg)
            data = json.loads(json_data_scrambledegg)
            print(data)
        except:
            print('Something went wrong! Try again or contact your Sysadmin!')
            messages.warning(request, 'Something went wrong! Try again or contact your Sysadmin!')
            return render(request, 'create_member_company/create_member_feedback.html')
        else:
            messages.success(request, 'Your Message was sent successfully!')
            return render(request, 'create_member_company/create_member_feedback.html')

and getting this output:

January 09, 2020 - 04:58:01
Django version 3.0.1, using settings 'erm_admin.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
200
<class 'str'>
{"id":"66995ab6-2962-465c-aa52-f68108f2ac97","name":"create-member-client-for-tenant-setup-response","correlationId":"025bb4aa-9396-4202-bcbc-fcbabfd498a8","payload":{"newlyCreatedClient":{"clientId":7270,"clientName":"Milk Man 1","corporationId":4520226,"corporationName":"Milk Man 1"},"suggestedExistingClients":null,"success":true,"errorMessage":""}}
Something went wrong! Try again or contact your Sysadmin!
[09/Jan/2020 04:58:07] "POST /create_member/ HTTP/1.1" 200 7885

The last 2 lines in my "try" are failing. Here they are (from the above try statement).
data = json.loads(json_data_scrambledegg)
print(data)

A: just call response.json() to get a dict:
try:
    ...
    clients_service_response = requests.post(clientsservice_url,
                                             headers=clientsservice_request_header,
                                             data=json.dumps(message_to_clientsservice))
    print(clients_service_response.status_code)
    data = clients_service_response.json() # this line!!
    print(data)
except:
    ...
else:
    ...

correct code
try:
    message_to_clients_service = {
        'id': id_id,
        'name': 'create-member-client-for-tenant-setup',
        'payload': {
            'clientName': client_name,
            'kbCorporationId': int(kb_corp_id),
            'email': email,
            'clientTypeId': client_type_id,
            'address': {
                'countryCode': country_code,
            },
            'phoneNumbers': []
        }
    }

    clients_service_request_header = {
        'Content-Type': 'application/json',
        'ServiceAccessToken': service_access_token,
        'Ocp-Apim-Subscription-Key': ocp_apim_subscription_key,
        'Authorization': 'Bearer ' + bearer_token
    }

    clients_service_response = requests.post(clientsservice_url,
                                             headers=clients_service_request_header,
                                             json=message_to_clients_service)
    print(clients_service_response.status_code)
    data = clients_service_response.json()  # this line!!
    print(data)
except Exception as e:
    print(e) # this line !!
    print('Something went wrong! Try again or contact your Sysadmin!')
    messages.warning(request, 'Something went wrong! Try again or contact your Sysadmin!')
    return render(request, 'create_member_company/create_member_feedback.html')
else:
    messages.success(request, 'Your Message was sent successfully!')
    return render(request, 'create_member_company/create_member_feedback.html')


text:
Q: Не обновляется кастомный ArrayAdapter Есть вот такой адаптер. делаю в активити
mAdapter.clear();
mAdapter.notifyDataSetChanged();

Просто ничего не происходит.
Код адаптера:
public class FilesAdapter extends ArrayAdapter<FilesInfo> {

private ArrayList<FilesInfo> mObjects;
private Context mContext;
private View mConvertView;
private ViewGroup mParent;

public FilesAdapter(Context _context, ArrayList<FilesInfo> _objects) {
    super(_context, R.layout.c_files_list_view);
    mContext = _context;
    mObjects = _objects;
}

@Override
public int getCount() {
    return mObjects.size();
}

@Override
public View getView(int _position, View _convertView, ViewGroup _parent) {
    LayoutInflater mInflater = (LayoutInflater) mContext
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    mConvertView = _convertView;
    mParent = _parent;
    if (mConvertView == null) {
        mConvertView = mInflater.inflate(R.layout.c_files_list_view, mParent, false);
    }

    ((ImageView) mConvertView.findViewById(R.id.list_icon)).setImageDrawable(mObjects.get(_position).getIcon());
    ((TextView) mConvertView.findViewById(R.id.list_name)).setText(mObjects.get(_position).getName());
    ((TextView) mConvertView.findViewById(R.id.list_size)).setText(Double.toString(mObjects.get(_position).getSize()));

    return mConvertView;
}

A: *

*лучше использовать BaseAdaper

*если не лучше, то надо понимать, что в ArrayAdapter лежит свой ArrayList, который и очищается при mAdapter.clear();

*хорошо бы еще не забывать про паттерн ViewHolder

A: Обязательно прочитайте Android Adapter Good Practices.


text:
Q: data.map is not a function typescript   list(): Observable<Recipe[]> {
    return this.http.get('url').pipe(
      map((data: any[]) =>
        data.map((item: any) =>
          new Recipe({
            name: item.recipeName
          })
        )
      )
    );
  }

I am getting an error saying "data.map is not a function" even though I clearly say that data is type of an array. If I do Object.values(data) it works fine. But why is data an Object? Shouldn't it be an Array? Or am I doing something wrong?


text:
Q: How to type dots whose slope is 1? We know how to typeset the commonly used diagonal dots, i.e., \ddots, whose slope is -1.
Now I want to produce dots with slope 1, which is perpendicular to \ddots.
Does anyone know how to do it?

A: How about using \iddots?
It requires the mathdots package though.
EDIT:
There is a discussion on your problem here

A: The MnSymbol package provides a \udots macro, which does exactly what you want. When you're looking for some symbol, consult the Comprehensive LaTeX Symbol List; you stand a good chance to find it in there.

\documentclass{article}

\usepackage{amsmath}
\usepackage{MnSymbol}

\begin{document}
\begin{tabular}{ll}
    diagonal dots ($\text{slope} = -1$) & $\ddots$ \\
    diagonal dots ($\text{slope} = 1$)  & $\udots$
\end{tabular}

\end{document}

A: It depends on tools. If the package graphicx is acceptable, the solution may be as follows
\documentclass{article}

\usepackage[demo]{graphicx}
\begin{document}

\[
A\ddots B \scalebox{-1}[1]{$\ddots$} C
\]

\end{document}


text:
Q: JArray adicionar valores Como adicionar um conjunto de valores JArray em um json já existente.
void adicionar(string name, string gamedir, string, lastVersionid, string javaArgs)
{
   /* adiciona ao json existente... */
}
Código json já existente...
{
  "profiles": {
    "nathan1302": {
      "name": "nathan1302",
      "lastVersionId": "1.8.8"
    },
    "Forge": {
      "name": "Forge",
      "lastVersionId": "1.7.10-Forge10.13.4.1566-1.7.10"
    },
    "OptiFine": {
      "name": "OptiFine",
      "lastVersionId": "1.8.8-OptiFine_HD_U_F5",
      "launcherVisibilityOnGameClose": "keep the launcher open"
    },
    "forge": {
      "name": "forge",
      "gameDir": "C:\\Users\\Nathan Ferreira\\AppData\\Roaming\\.minecraft\\222",
      "lastVersionId": "1.7.10-Forge10.13.4.1566-1.7.10",
      "javaArgs": "-Xmx5G -XX:+UseConcMarkSweepGC -XX:+CMSIncrementalMode -XX:-UseAdaptiveSizePolicy -Xmn128M",
      "launcherVisibilityOnGameClose": "keep the launcher open"
    },
    "RFMinecraft": {
      "name": "RFMinecraft",
      "lastVersionId": "1.7.10-LiteLoader1.7.10-1.7.10-Forge10.13.4.1566-1.7.10",
      "javaArgs": "-Xmx3G",
      "useHopperCrashService": false,
      "launcherVisibilityOnGameClose": "keep the launcher open"
    } // ADICIONAR DEPOIS DAQUI!
  },
  "selectedProfile": "forge",
  "selectedUser": "fa944578e6f04db3b10ac85e81cf134d",
  "launcherVersion": {
    "name": "1.6.48",
    "format": 17
  }
}

A: Se você tem o seu JSON em uma variável JObject (como você mencionou JArray, estou assumindo que você está usando a biblioteca Newtonsoft.Json, namespace Newtonsoft.Json.Linq), você pode usar um código similar ao abaixo:
void adicionar(string name, string gamedir, string, lastVersionid, string javaArgs)
{
    JObject jsonExistente = getJsonExistente();
    JObject profiles = jsonExistente["profiles"] as JObject;
    JObject newProfile = new JObject();
    newProfile.Add("name", name);
    if (gamedir != null) newProfile.Add("gameDir", gamedir);
    if (lastVersionid != null) newProfile.Add("lastVersionId", lastVersionid);
    if (javaArgs != null) newProfile.Add("javaArgs", javaArgs);
    profiles.Add(name, newProfile);
    // salva o JSON existente se precisar
}


text:
Q: Export to excel with browser localization - ASP.Net I have gridview and I am exporting to excel that gridview with below code.
Response.ClearContent()
Response.AddHeader("content-disposition", "attachment;
                       filename=ExcelShipments_" & DateTime.Now.Ticks & ".xls")
Response.ContentType = "application/excel"
Dim sWriter As New StringWriter()
Dim hTextWriter As New HtmlTextWriter(sWriter)
Dim hForm As New HtmlForm()
ucShipmentList.ShipmentGrid.Parent.Controls.Add(hForm)
hForm.Attributes("runat") = "server"
hForm.Controls.Add(ucShipmentList.ShipmentGrid)

hForm.RenderControl(hTextWriter)

Dim sBuilder As New StringBuilder()
sBuilder.Append(" <meta http-equiv=""Content-Type"" content=""text/html;charset=windows-1252""> ")
                sBuilder.Append(sWriter.ToString() & "")

Response.Write(sBuilder.ToString())
Response.End()

I have dutch language in page default set therefore grid displays on page is correct but while doing export to excel, It shows exported in English.
How can I preserve language while exporting to excel?

A: I would use the Open XML SDK and create a "real" Excel document.


text:
Q: on link select change every list image on link select I want to be able to change each of my list item images here to a specific image on link select.
here is the jquery im trying to use to change each of my list images on link select:

but if you look at this page here it doesn't seem to change the list images on link select
this is the code to my list items:

All

Mental

Physical

Social

Other

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam sit amet purus urna. Proin dictum fringilla enim, sit amet suscipit dolor dictum in. Maecenas porttitor, est et malesuada congue, ligula elit fermentum massa, sit amet porta odio est at velit. Sed nec turpis neque. Fusce at mi felis, sed interdum tortor. Nullam pretium, est at congue mattis, nibh eros pharetra lectus, nec posuere libero dui consectetur arcu. Quisque convallis facilisis fermentum. Nam tincidunt, diam nec dictum mattis, nunc dolor ultrices ipsum, in mattis justo turpis nec ligula. Curabitur a ante mauris. Integer placerat imperdiet diam, facilisis pretium elit mollis pretium. Sed lobortis, eros non egestas suscipit, dui dui euismod enim, ac ultricies arcu risus at tellus. Donec imperdiet congue ligula, quis vulputate mauris ultrices non. Aliquam rhoncus, arcu a bibendum congue, augue risus tincidunt massa, vel vehicula diam dolor eget felis.

Donec semper dictum sem, quis pretium sem malesuada non. Proin venenatis orci vel nisl porta sollicitudin. Pellentesque sit amet massa et orci malesuada facilisis vel vel lectus. Etiam tristique volutpat auctor. Morbi nec massa eget sem ultricies fermentum id ut ligula. Praesent aliquet adipiscing dictum. Suspendisse dignissim dui tortor. Integer faucibus interdum justo, mattis commodo elit tempor id. Quisque ut orci orci, sit amet mattis nulla. Suspendisse quam diam, feugiat at ullamcorper eget, sagittis sed eros. Proin tortor tellus, pulvinar at imperdiet in, egestas sed nisl. Aenean tempor neque ut felis dignissim ac congue felis viverra.

Duis egestas fermentum ipsum et commodo. Proin bibendum consectetur elit, hendrerit porta mi dictum eu. Vestibulum adipiscing euismod laoreet. Vivamus lobortis tortor a odio consectetur pulvinar. Proin blandit ornare eros dictum fermentum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur laoreet, ante aliquet molestie laoreet, lectus odio fringilla purus, id porttitor erat velit vitae mi. Nullam posuere nunc ut justo sollicitudin interdum. Donec suscipit eros nec leo condimentum fermentum. Nunc quis libero massa. Integer tempus laoreet lectus id interdum. Integer facilisis egestas dui at convallis. Praesent elementum nisl et erat iaculis a blandit ligula mollis. Vestibulum vitae risus dui, nec sagittis arcu. Nullam tortor enim, placerat quis eleifend in, viverra ac lacus. Ut aliquam sapien ut metus hendrerit auctor dapibus justo porta.

Duis egestas fermentum ipsum et commodo. Proin bibendum consectetur elit, hendrerit porta mi dictum eu. Vestibulum adipiscing euismod laoreet. Vivamus lobortis tortor a odio consectetur pulvinar. Proin blandit ornare eros dictum fermentum. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur laoreet, ante aliquet molestie laoreet, lectus odio fringilla purus, id porttitor erat velit vitae mi. Nullam posuere nunc ut justo sollicitudin interdum. Donec suscipit eros nec leo condimentum fermentum. Nunc quis libero massa. Integer tempus laoreet lectus id interdum. Integer facilisis egestas dui at convallis. Praesent elementum nisl et erat iaculis a blandit ligula mollis. Vestibulum vitae risus dui, nec sagittis arcu. Nullam tortor enim, placerat quis eleifend in, viverra ac lacus. Ut aliquam sapien ut metus hendrerit auctor dapibus justo porta.

Proin sollicitudin tincidunt quam, in egestas dui tincidunt non. Maecenas tempus condimentum mi, sed convallis tortor iaculis eu. Cras dui dui, tempor quis tempor vitae, ullamcorper in justo. Integer et lorem diam. Quisque consequat lectus eget urna molestie pharetra. Cras risus lectus, lobortis sit amet imperdiet sit amet, eleifend a erat. Suspendisse vel luctus lectus. Sed ac arcu nisi, sit amet ornare tellus. Pellentesque nec augue a nibh pharetra scelerisque quis sit amet felis. Nullam at enim at lacus pretium iaculis sit amet vel nunc. Praesent sapien felis, tincidunt vitae blandit ut, mattis at diam. Suspendisse ac sapien eget eros venenatis tempor quis id odio. Donec lacus leo, tincidunt eget molestie at, pharetra cursus odio.


text:
Q: Does clicking on a link  in symfony make a submit of the form? hello I have been reviewing this crud that is generated automatically and there are things that I do not understand. For example, when you click:
edit

Do you submit the form? I'm asking because I tried to remove the post method from the route (leaving only the get) and it gave me an error (No route found for "POST / people / 4 / edit": Method Not Allowed (Allow: GET)). It seems that it passes the id by get (that is, by url) but it does not work when i remove the POST method on the route of the edit function in the controller. This is the controller:
<?php

namespace App\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use App\Repository\MyClassRepository;
use App\Entity\Tablaform;
use App\Form\Formulario2Type;
/**
 * @Route("/personas")
 */

class ControladorFormularios2Controller extends AbstractController
{
    /**
     * @Route("/", name="personas_index", methods={"GET"})
     */
    public function index(MyClassRepository $myClassRepository): Response
    {
        return $this->render('controlador_formularios2/index.html.twig', [
            'personas' => $myClassRepository->findAll(),
        ]);
    }

    /**
     * @Route("/new", name="persona_new", methods={"GET","POST"})
     */

    public function new(Request $request): Response
    {
        $tablaForm = new Tablaform();
        $form = $this->createForm(Formulario2Type::class, $tablaForm);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($tablaForm);
            $entityManager->flush();

            return $this->redirectToRoute('personas_index');
        }

        return $this->render('controlador_formularios2/new.html.twig', [
            'tablaForm' => $tablaForm,
            'form' => $form->createView(),
        ]);
    }

    /**
     * @Route("/{id}/delete", name="personas_delete", methods={"GET","POST"})
     */

    public function delete(Request $request, Tablaform $tablaForm): Response
    {
        //if ($this->isCsrfTokenValid('delete'.$tablaForm->getId(), $request->request->get('_token')))
        {
            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->remove($tablaForm);
            $entityManager->flush();
        }

        return $this->redirectToRoute('personas_index');
    }

     /**
     * @Route("/{id}/edit", name="personas_edit", methods={"GET","POST"})
     */
    public function edit(Request $request, Tablaform $tablaForm): Response
    {
        $form = $this->createForm(Formulario2Type::class, $tablaForm);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $this->getDoctrine()->getManager()->flush();

            return $this->redirectToRoute('personas_index');
        }

        return $this->render('controlador_formularios2/edit.html.twig', [
            'tablaForm' => $tablaForm,
            'form' => $form->createView(),
        ]);
    }

and this is the view:
{% extends 'base.html.twig' %}

{% block title %}Listado{% endblock %}

{% block body %}

                Id
                Nombre
                Edad

        {% for persona in personas %}

                {{ persona.id }}
                {{ persona.nombre }}
                {{ persona.edad }}

                    {{ include('controlador_formularios2/_delete_form.html.twig') }}
                    edit

        {% else %}

                no records found

        {% endfor %}

     Create new
{% endblock %}


text:
Q: AngularJS - Define Data Models for Specific Objects I am 2 days new to AngularJS and covering online tutorials to learn more about this powerful framework. Yet one questions I still haven't found the answer to is how do I create a data structure that would handle specific transactions? E.g. for the user management controller, I would like to have a user data structure that has username, email, password, etc. so that I can create an instance of this structure and store data in it locally for transactions.
Any suggestions or help will be welcomed.
Thanks,


text:
Q: MySql and MongoDB configuration in springboot application I'm new to springboot and I need to connect to 2 different DBs (i.e. Mysql and MongoDb) in my SpringBoot Application. There are several ways, I came across to connect to different data sources. But I couldn't find any way to connect to MySql and Mongo DB with a same spring boot application. How can I achieve this ? What class level configuration I need to do ?
I have already went through following but didn't get any clarity:

*

*http://www.baeldung.com/spring-data-jpa-multiple-databases

*Spring Boot configure and use two data sources


text:
Q: Show Quartz Scheduler details in a web page My Requirement - Display list of scheduled jobs on a web page.
What I have accomplished so far-
1) I am initializing the scheduler using a servlet and making appropriate entries in web.xml.
Servlet
public class QuartzTest extends HttpServlet implements Job {
    public static Scheduler scheduler = null;
    public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
    // Get details from web form and schedule a job accordingly.
    }
}

2) I am successfully storing the job,trigger & schedule details in a Sybase database.
quartz.properties
org.quartz.scheduler.instanceName = MyJobScheduler
org.quartz.scheduler.instanceId = 1
org.quartz.scheduler.rmi.export = false
org.quartz.scheduler.rmi.proxy = false

org.quartz.threadPool.class = org.quartz.simpl.SimpleThreadPool
org.quartz.threadPool.threadCount = 5
########################################
########### SYBASE CONNECTION ##########
org.quartz.jobStore.class = org.quartz.impl.jdbcjobstore.JobStoreTX
org.quartz.jobStore.driverDelegateClass = org.quartz.impl.jdbcjobstore.SybaseDelegate
org.quartz.jobStore.dataSource = SybaseDS
org.quartz.jobStore.useProperties = true
org.quartz.dataSource.SybaseDS.driver = com.sybase.jdbc3.jdbc.SybDriver
.
.
.

My Problem I am trying to show the scheduler details on a web page. Below is the Java class I have written to do so, and I am trying to access this class from a JSP page, but I am getting NullPointerException-
My Class
public class JSPtest {
    // Method to get scheduler name
    public ArrayList<String> getSchedulerName() {
        ArrayList<String> jobList = new ArrayList<String>();
        String name = null;
        try{
            name = QuartzTest.scheduler.getSchedulerName();
            jobList.add(name);
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        return jobList;
    }
}

JSP
<%!
JSPtest jsp = new JSPtest();
ArrayList<String> jobList = new ArrayList<String>();
int count = 0;
%>
<%
jobList = jsp.getSchedulerName();
for(count = 0; count < jobList.size(); count++){
    out.println("<p>"+jobList.get(count)+"</p>");
}
%>

Error
java.lang.NullPointerException
    at com.globeop.quartztrials.JSPtest.getSchedulerName(JSPtest.java:32)
    at org.apache.jsp.viewSchedule_jsp._jspService(viewSchedule_jsp.java:72)
    at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)

So how do I display the scheduler details on a web page ?

A: Check out jwatch which has all you need to display jobs.


text:
Q: Help with error message There's an error message I can't understand since I don't see where my code calls it. It appears when using the User object with Google app engine with dev_appserver. Can you tell me what it means?
ERROR    2011-07-15 15:01:07,664 __init__.py:463] 'User' object has no attribute '_User__email'
Traceback (most recent call last):
  File "/media/Lexar/projects/google/appengine/ext/webapp/__init__.py", line 700, in __call__
    handler.get(*groups)
  File "/media/Lexar/projects/myproject/i18n.py", line 313, in get
    self.response.out.write(template.render(path, template_values))
  File "/media/Lexar/projects/google/appengine/ext/webapp/template.py", line 73, in render
    return t.render(Context(template_dict))
  File "/media/Lexar/projects/google/appengine/ext/webapp/template.py", line 115, in wrap_render
    return orig_render(context)
  File "/media/Lexar/projects/lib/django_1_2/django/template/__init__.py", line 173, in render
    return self._render(context)
  File "/media/Lexar/projects/lib/django_1_2/django/template/__init__.py", line 167, in _render
    return self.nodelist.render(context)
  File "/media/Lexar/projects/lib/django_1_2/django/template/__init__.py", line 796, in render
    bits.append(self.render_node(node, context))
  File "/media/Lexar/projects/lib/django_1_2/django/template/__init__.py", line 809, in render_node
    return node.render(context)
  File "/media/Lexar/projects/lib/django_1_2/django/template/loader_tags.py", line 139, in render
    return self.template.render(context)
  File "/media/Lexar/projects/lib/django_1_2/django/template/__init__.py", line 173, in render
    return self._render(context)
  File "/media/Lexar/projects/lib/django_1_2/django/template/__init__.py", line 167, in _render
    return self.nodelist.render(context)
  File "/media/Lexar/projects/lib/django_1_2/django/template/__init__.py", line 796, in render
    bits.append(self.render_node(node, context))
  File "/media/Lexar/projects/lib/django_1_2/django/template/__init__.py", line 809, in render_node
    return node.render(context)
  File "/media/Lexar/projects/lib/django_1_2/django/template/defaulttags.py", line 258, in render
    return self.nodelist_true.render(context)
  File "/media/Lexar/projects/lib/django_1_2/django/template/__init__.py", line 796, in render
    bits.append(self.render_node(node, context))
  File "/media/Lexar/projects/lib/django_1_2/django/template/__init__.py", line 809, in render_node
    return node.render(context)
  File "/media/Lexar/projects/lib/django_1_2/django/template/__init__.py", line 849, in render
    return _render_value_in_context(output, context)
  File "/media/Lexar/projects/lib/django_1_2/django/template/__init__.py", line 829, in _render_value_in_context
    value = force_unicode(value)
  File "/media/Lexar/projects/lib/django_1_2/django/utils/encoding.py", line 66, in force_unicode
    s = unicode(s)
  File "/media/Lexar/projects/google/appengine/api/users.py", line 188, in __unicode__
    return unicode(self.nickname())
  File "/media/Lexar/projects/google/appengine/api/users.py", line 152, in nickname
    if (self.__email and self.__auth_domain and
AttributeError: 'User' object has no attribute '_User__email'

EDIT: The error goes away when I remove this code:
'user_url': users.create_logout_url(self.request.uri) if users.get_current_user() else 'login','user' : users.get_current_user(),
So supposedly I'm making some mistake using the User object
UPDATE: It's seems to have something to do with a monkeypatch I applied. Removing this part removes the error so I'm wondering whether I still need this patch. It's reported in
def _user_init(self, email=None, _auth_domain=None,
             _user_id=None, federated_identity=None, federated_provider=None,
             _strict_mode=True):

  if not _auth_domain:
    _auth_domain = os.environ.get('AUTH_DOMAIN')
  assert _auth_domain

  if email is None and federated_identity is None:
    email = os.environ.get('USER_EMAIL', email)
    _user_id = os.environ.get('USER_ID', _user_id)
    federated_identity = os.environ.get('FEDERATED_IDENTITY',
                                        federated_identity)
    federated_provider = os.environ.get('FEDERATED_PROVIDER',
                                        federated_provider)

  if not email and not federated_identity and _strict_mode:
    raise UserNotFoundError

  self.__email = email
  self.__federated_identity = federated_identity
  self.__federated_provider = federated_provider
  self.__auth_domain = _auth_domain
  self.__user_id = _user_id or None

users.User.__init__ = _user_init

Related thread where the monkeypatch comes from
How do I apply a monkeypatch to GAE?

A: I would guess your error is at import-time of some module:
ERROR    2011-07-15 15:01:07,664 __init__.py:463] 'User' object has no attribute '_User__email'

__init__.py is the file that define a directory as being a package of modules.
You could either look for a line #463 with a User object on it, or selectively removing the imports for understanding which package is at fault.
I would guess that for fixing it, you need to make sure when the User object does have a _User__email (which is the mangled name of __email) attribute, but not knowing how you make the call that generate the mistake it's difficult to say...


text:
Q: Layer-Backed view no longer punches hole in transparent NSWindow I am trying to make a "hole" in an NSWindow using a CAShapeLayer or even just a CALayer.
When using regular NSViews or even layer-backed views, I can override drawRect: using code like this:
        [spotImage drawInRect:self.bounds fromRect:NSZeroRect operation:NSCompositeXOR fraction:1.0];

where spotImage is an NSImage with pure white content and some gradations, and the window has a black background with 0.5 alpha. The NSView subclass where this drawRect is defined has a clearColor background.
The end result is a grey window (It is a transparent window with a styleMask of NSBorderlessWindowMask as can be found in many samples.
If I turn the NSView into a layer-backed view, it calls the drawRect methods and works fine.
When I turn this into a layer-hosting view, and again use the same structure (NSWindow > contentView > CustomView) then, the drawInRect method just draws the image. It no longer punches a hole through it.
It is like the layer itself can no longer punch the hole when it is part of a layer-hosting hierarchy.
Here is some sample code:
The custom NSWindow subclass initializer:
- (id)initWithContentRect:(NSRect)contentRect styleMask:(NSUInteger)aStyle backing:(NSBackingStoreType)bufferingType defer:(BOOL)flag {

self = [super initWithContentRect:contentRect styleMask:NSBorderlessWindowMask backing:NSBackingStoreBuffered defer:NO];

if (self) {

   [self setBackgroundColor: [NSColor lightGrayColor]]; //[NSColor clearColor]];

    [self setAlphaValue:0.5];

    [self setOpaque:NO];
    [self setHasShadow: NO];

    [self useOptimizedDrawing:YES];
    [self setIgnoresMouseEvents:YES];
}
return self;

}
the code in my applicationDidFinishLaunching method:
PPContentView *thisView = [[PPContentView alloc]
                    initWithFrame:CGRectInset([self.window.contentView bounds], 50, 50)];

//[thisView setWantsLayer:YES]; enabling this makes things opaque again

[self.window.contentView addSubview:thisView];

thisView.layer.backgroundColor = [NSColor clearColor].CGColor;

//Create custom content
[thisView setNeedsDisplay:YES];

}
and my custom view's drawRect contains:
    [[NSImage imageNamed:@"spotFuzzy.png"] drawInRect:self.bounds fromRect:NSZeroRect operation:NSCompositeXOR fraction:1.0];


text:
Q: Cloudformation metadata commands I am trying to learn Cloudformation.
Can someone please explain to me why 1-install-roles is numbered with "1"?
What does this line do "if not \"None\" EQU \"",
Resource("WindowsServer") do
    Type("AWS::EC2::Instance")
    Metadata("AWS::CloudFormation::Init", {
  "config" => {
    "commands" => {
      "1-install-roles"    => {
        "command" => FnJoin("", [
  "if not \"None\" EQU \"",
  Ref("Roles"),
  "\" (powershell.exe add-windowsfeature ",
  Ref("Roles"),
  " -restart)"
])

A: The 1- is prepended for ordering to ensure the command gets executed first. It's executed in alphabetical order. The if not \"None\" EQU \" bit is windows batch scripting. EQU is a comparison operator and means "equal".
Let's assume that the reference to Roles returns the string "Something", the command executed will be:
if not "None" EQU "Something" "(powershell.exe add-windowsfeature Something -restart)"


text:
Q: How to remove an apostrophe ( ' ) from couple of columns of a .CSV file? I have a .CSV file with 7 fields, and the 3rd and 4th columns of the file has a number starting with an apostrophe ( ' ). Please see the example below.
col0,col1,col2,col3,col4,col5,col6,
1value0,1value1,'8972991766941,'8972991766941,1value4,1value5,1value6,
2value0,2value1,'8912988876583,'8912988876583,2value4,2value5,2value6,
3value,3value1,'8912981226981,'8912981226981,3value4,3value5,3value6,
2value0,4value1,'8912971783681,'8912971783681,4value4,4value5,4value6,

How do I get rid of the apostrophes in the 3rd and 4th columns only using either sed or awk?

A: You can use awk:
awk -F, '{for (i=3;i<=4;i++) sub("'\''", "", $i)}1' OFS=, file

A: If ' is not needed at all, remove it everywhere.
awk '{gsub("'\''","")}1' file

A: Press CTRL+H on Notepad, replace "'" with "" (Nothing)


text:
Q: Paginator (Migration from Cake 1.3 to 2.0) I am struggling with the paginator in Cakephp 2.0. While I am trying to migrate my application to 2.0 I cant find any solution to jump directly to the last page. In 1.3 it was quiet to do that from outside like this:
echo $this->Html->link(__('Flights'), array('controller' => 'flights',
    'action' => 'index','page' => 'last'));

but this little trick putting 'page:last' in does not work anymore in 2.0. Of course there is a Paginator function called last, but this would only help if I would be already inside the app. My Problem is to access from an outside link directly the last page of the paginator.

A: This is the simple way:
echo  $this->Paginator->last('Any text');

Other way to get the number of the last page is:
echo  $this->Paginator->counter(array('format' => '{:pages}'));

Then you can use it to generate your link.
For more info:
http://book.cakephp.org/2.0/en/core-libraries/helpers/paginator.html#PaginatorHelper::last

A: Shortly after creating a bounty for this question I found the solution to MY problem using CakePHP 2.2.4. I was trying to accomplish the same task but instead using version 2.2.4 instead instead of 2.0. Basically if I had a link that looked like http://www.domain.com/articles/page:last that the controller's pagination method would know what page to go to and display the correct results (articles) for that page. For example, if I have 110 articles and the pagination limit is set to 25, by going to that URL it would display page 5 of 5, showing records 101-110. I also wanted the same capability if I go to "page:first".
I needed to change my library file lib/Cake/Controller/Component/PaginatorComponent.php.
I changed
if (intval($page) < 1) {
    $page = 1;
}

To
if ((intval($page) < 1 && $page != "last") || $page == "first") {
    $page = 1;
}

I also added
if($page == "last"){
    $page = $pageCount;
}

After the line
$pageCount = intval(ceil($count / $limit));

Christian Waschke, with this solution, you can use the same link helper exactly how you wrote it in your question. For me, the link helper looked like this
<?php echo $this->Html->link('Go to Last Page', array('controller' => 'articles', 'action' => 'index', 'page' => 'last')); ?>

A: You can 'calculate' the last page yourself if 'last' is passed as the page number;
I would discourage making modifications in the CakePHP library files as this will make it hard to perform upgrades in the future.
Basically, the PaginatorHelper uses viewVars that are calculated and set by the PaginatorComponent, as seen here: https://github.com/cakephp/cakephp/blob/master/lib/Cake/Controller/Component/PaginatorComponent.php#L212
You can replicate this in your action; for example:
public function index()
{
    if (!empty($this->request->params['named']['page'])) {
        switch($this->request->params['named']['page']) {
           case 'first':
                // replace the 'last' with actual number of the first page
                $this->request->params['named']['page'] = 1;
                break;

           case 'last':
                // calculate the last page
                $limit = 10; // your limit here
                $count = $this->Flight->find('count');
                $pageCount = intval(ceil($count / $limit));

                // replace the 'last' with actual number of the last page
                $this->request->params['named']['page'] = $pageCount;
                break;
        }

    }

    // then, paginate as usual
    $this->set('data', $this->paginate('Flight'));
}

To improve this, this logic should be moved to a separate method, or to a behavior. However; as seen above, it is not required to make modifications in the PaginatorComponent!
Also note that the 'find(count)' in my example does not take additional conditions, they should be added if required
If you have a look in the CakePHP 1.3 source for paginate(), the code above is comparable; https://github.com/cakephp/cakephp/blob/1.3/cake/libs/controller/controller.php#L1204


text:
Q: Bitcask ok for simple and high performant file store? I am looking for a simple way to store and retrieve millions of xml files. Currently everything is done in a filesystem, which has some performance issues.
Our requirements are:

*

*Ability to store millions of xml-files in a batch-process. XML files may be up to a few megs large, most in the 100KB-range.

*Very fast random lookup by id (e.g. document URL)

*Accessible by both Java and Perl

*Available on the most important Linux-Distros and Windows

I did have a look at several NoSQL-Platforms (e.g. CouchDB, Riak and others), and while those systems look great, they seem almost like beeing overkill:

*

*No clustering required

*No daemon ("service") required

*No clever search functionality required

Having delved deeper into Riak, I have found Bitcask (see intro), which seems like exactly what I want. The basics described in the intro are really intriguing. But unfortunately there is no means to access a bitcask repo via java (or is there?)
Soo my question boils down to

*

*is the following assumption right: the Bitcask model (append-only writes, in-memory key management) is the right way to store/retrieve millions of documents

*are there any viable alternatives to Bitcask available via Java? (BerkleyDB comes to mind...)

*(for riak specialists) Is Riak much overhead implementation/management/resource wise compared to "naked" Bitcask?

A: I don't think that Bitcask is going to work well for your use-case.  It looks like the Bitcask model is designed for use-cases where the size of each value is relatively small.
The problem is in Bitcask's data file merging process.  This involves copying all of the live values from a number of "older data file" into the "merged data file".  If you've got millions of values in the region of 100Kb each, this is an insane amount of data copying.

Note the above assumes that the XML documents are updated relatively frequently.  If updates are rare and / or you can cope with a significant amount of space "waste", then merging may only need to be done rarely, or not at all.

A: Bitcask can be appropriate for this case (large values) depending on whether or not there is a great deal of overwriting.  In particular, there is not reason to merge files unless there is a great deal of wasted space, which only occurs when new values arrive with the same key as old values.
Bitcask is particularly good for this batch load case as it will sequentially write the incoming data stream straight to disk.  Lookups will take one seek in most cases, although the file cache will help you if there is any temporal locality.
I am not sure on the status of a Java version/wrapper.