text:
Q: Unable to connect Kibana to Elasticsearch I've installed ES 7.5 and Kibana 7.5 on RHEL7, but after starting Kibana and checking the UI, I'm seeing the error, "Kibana server is not ready yet."
Checking the Kibana log, I see that it is not properly connecting to ES. Any help is appreciated!
Here is the output of journalctl --unit kibana:
Dec 11 10:03:05 mcjca033031 systemd[1]: kibana.service holdoff time over, scheduling restart.
Dec 11 10:03:05 mcjca033031 systemd[1]: Started Kibana.
Dec 11 10:03:05 mcjca033031 systemd[1]: Starting Kibana...
Dec 11 10:03:08 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:08Z","tags":["info","plugins-system"],"pid":5320,"message":"Setting up [15] plugins: [security,licensing,code,timelion,features,spaces,translation
Dec 11 10:03:08 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:08Z","tags":["info","plugins","security"],"pid":5320,"message":"Setting up plugin"}
Dec 11 10:03:08 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:08Z","tags":["warning","plugins","security","config"],"pid":5320,"message":"Generating a random key for xpack.security.encryptionKey. To prevent s
Dec 11 10:03:08 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:08Z","tags":["warning","plugins","security","config"],"pid":5320,"message":"Session cookies will be transmitted over insecure connections. This is
Dec 11 10:03:08 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:08Z","tags":["info","plugins","licensing"],"pid":5320,"message":"Setting up plugin"}
Dec 11 10:03:08 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:08Z","tags":["info","plugins","code"],"pid":5320,"message":"Setting up plugin"}
Dec 11 10:03:08 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:08Z","tags":["info","plugins","timelion"],"pid":5320,"message":"Setting up plugin"}
Dec 11 10:03:08 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:08Z","tags":["info","plugins","features"],"pid":5320,"message":"Setting up plugin"}
Dec 11 10:03:08 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:08Z","tags":["info","plugins","spaces"],"pid":5320,"message":"Setting up plugin"}
Dec 11 10:03:08 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:08Z","tags":["info","plugins","translations"],"pid":5320,"message":"Setting up plugin"}
Dec 11 10:03:08 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:08Z","tags":["info","plugins","data"],"pid":5320,"message":"Setting up plugin"}
Dec 11 10:03:13 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:13Z","tags":["warning","legacy-plugins"],"pid":5320,"path":"/usr/share/kibana/src/legacy/core_plugins/visualizations","message":"Skipping non-plug
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["warning","plugins","licensing"],"pid":5320,"message":"License information could not be obtained from Elasticsearch for the [data] cl
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["info","plugins-system"],"pid":5320,"message":"Starting [8] plugins: [security,licensing,code,timelion,features,spaces,translations,d
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["info","migrations"],"pid":5320,"message":"Creating index .kibana_task_manager_1."}
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["info","migrations"],"pid":5320,"message":"Creating index .kibana_1."}
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["warning","migrations"],"pid":5320,"message":"Unable to connect to Elasticsearch. Error: [mapper_parsing_exception] No handler for ty
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["fatal","root"],"pid":5320,"message":"{ Error: [mapper_parsing_exception] No handler for type [flattened] declared on field [state]\n
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["info","plugins-system"],"pid":5320,"message":"Stopping all plugins."}
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["info","plugins","data"],"pid":5320,"message":"Stopping plugin"}
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["info","plugins","translations"],"pid":5320,"message":"Stopping plugin"}
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["info","plugins","spaces"],"pid":5320,"message":"Stopping plugin"}
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["info","plugins","features"],"pid":5320,"message":"Stopping plugin"}
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["info","plugins","timelion"],"pid":5320,"message":"Stopping plugin"}
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["info","plugins","code"],"pid":5320,"message":"Stopping plugin"}
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["info","plugins","licensing"],"pid":5320,"message":"Stopping plugin"}
Dec 11 10:03:14 mcjca033031 kibana[5320]: {"type":"log","@timestamp":"2019-12-11T15:03:14Z","tags":["info","plugins","security"],"pid":5320,"message":"Stopping plugin"}
Dec 11 10:03:14 mcjca033031 kibana[5320]: FATAL  [mapper_parsing_exception] No handler for type [flattened] declared on field [state] :: {"path":"/.kibana_1","query":{},"body":"{\"mappings\":{\"dynamic\":\"strict\",\"properties\":{\"
Dec 11 10:03:14 mcjca033031 kibana[5320]: \":{\"type\":\"geo_shape\"},\"mapStateJSON\":{\"type\":\"text\"},\"layerListJSON\":{\"type\":\"text\"},\"uiStateJSON\":{\"type\":\"text\"}}},\"maps-telemetry\":{\"properties\":{\"mapsTotalCou
Dec 11 10:03:14 mcjca033031 kibana[5320]: \":\"keyword\"},\"color\":{\"type\":\"keyword\"},\"label\":{\"type\":\"keyword\"}}},\"limit\":{\"type\":\"integer\"},\"groupBy\":{\"type\":\"keyword\"},\"filterQuery\":{\"type\":\"keyword\"},
Dec 11 10:03:14 mcjca033031 kibana[5320]: displayValue\":{\"type\":\"text\"},\"operator\":{\"type\":\"text\"}}},\"and\":{\"properties\":{\"id\":{\"type\":\"keyword\"},\"name\":{\"type\":\"text\"},\"enabled\":{\"type\":\"boolean\"},\"
Dec 11 10:03:14 mcjca033031 kibana[5320]: \":\"long\",\"null_value\":0},\"cluster\":{\"type\":\"long\",\"null_value\":0},\"indices\":{\"type\":\"long\",\"null_value\":0}}},\"ui_reindex\":{\"properties\":{\"close\":{\"type\":\"long\",
Dec 11 10:03:14 mcjca033031 kibana[5320]: t\"},\"hits\":{\"type\":\"integer\"},\"kibanaSavedObjectMeta\":{\"properties\":{\"searchSourceJSON\":{\"type\":\"text\"}}},\"sort\":{\"type\":\"keyword\"},\"title\":{\"type\":\"text\"},\"vers
Dec 11 10:03:14 mcjca033031 kibana[5320]: },\"timelion_sheet\":{\"type\":\"text\"},\"title\":{\"type\":\"text\"},\"version\":{\"type\":\"integer\"}}},\"ui-metric\":{\"properties\":{\"count\":{\"type\":\"integer\"}}}},\"_meta\":{\"mig
Dec 11 10:03:14 mcjca033031 kibana[5320]: ",\"sample-data-telemetry\":\"7d3cfeb915303c9641c59681967ffeb4\",\"telemetry\":\"358ffaa88ba34a97d55af0933a117de4\",\"timelion-sheet\":\"9a2a2748877c7a7b582fef201ab1d4cf\",\"ui-metric\":\"0d4
Dec 11 10:03:15 mcjca033031 systemd[1]: kibana.service: main process exited, code=exited, status=1/FAILURE
Dec 11 10:03:15 mcjca033031 systemd[1]: Unit kibana.service entered failed state.
Dec 11 10:03:15 mcjca033031 systemd[1]: kibana.service failed.

Elasticsearch.yml
# ======================== Elasticsearch Configuration =========================
#
# NOTE: Elasticsearch comes with reasonable defaults for most settings.
#       Before you set out to tweak and tune the configuration, make sure you
#       understand what are you trying to accomplish and the consequences.
#
# The primary way of configuring a node is via this file. This template lists
# the most important settings you may want to configure for a production cluster.
#
# Please consult the documentation for further information on configuration options:
# https://www.elastic.co/guide/en/elasticsearch/reference/index.html
#
# ---------------------------------- Cluster -----------------------------------
#
# Use a descriptive name for your cluster:
#
cluster.name: elasticsearchcluster
#
# ------------------------------------ Node ------------------------------------
#
# Use a descriptive name for the node:
#
node.name: mcjca033078
#
# Add custom attributes to the node:
#
#node.attr.rack: r1
#
# ----------------------------------- Paths ------------------------------------
#
# Path to directory where to store the data (separate multiple locations by comma):
#
path.data: /var/lib/elasticsearch
#
# Path to log files:
#
path.logs: /var/log/elasticsearch
#
# ----------------------------------- Memory -----------------------------------
#
# Lock the memory on startup:
#
#bootstrap.memory_lock: true
#
# Make sure that the heap size is set to about half the memory available
# on the system and that the owner of the process is allowed to use this
# limit.
#
# Elasticsearch performs poorly when the system is swapping the memory.
#
# ---------------------------------- Network -----------------------------------
#
# Set the bind address to a specific IP (IPv4 or IPv6):
#
network.host: 11.208.33.78
#
# Set a custom port for HTTP:
#
http.port: 9200
#
# For more information, consult the network module documentation.
#
# --------------------------------- Discovery ----------------------------------
#
# Pass an initial list of hosts to perform discovery when this node is started:
# The default list of hosts is ["127.0.0.1", "[::1]"]
#
discovery.seed_hosts: ["mcjca033078", "mcjca032215", "mcjca032254"]
#
# Bootstrap the cluster using an initial set of master-eligible nodes:
#
cluster.initial_master_nodes: ["mcjca033078", "mcjca032215", "mcjca032254"]

#
# For more information, consult the discovery and cluster formation module documentation.
#
# ---------------------------------- Gateway -----------------------------------
#
# Block initial recovery after a full cluster restart until N nodes are started:
#
#gateway.recover_after_nodes: 3
#
# For more information, consult the gateway module documentation.
#
# ---------------------------------- Various -----------------------------------
#
# Require explicit names when deleting indices:
#
#action.destructive_requires_name: true

Kibana.yml
# Kibana is served by a back end server. This setting specifies the port to use.
server.port: 5601

# Specifies the address to which the Kibana server will bind. IP addresses and host names are both valid values.
# The default is 'localhost', which usually means remote machines will not be able to connect.
# To allow connections from remote users, set this parameter to a non-loopback address.
server.host: "mcjca033031"

# Enables you to specify a path to mount Kibana at if you are running behind a proxy.
# Use the `server.rewriteBasePath` setting to tell Kibana if it should remove the basePath
# from requests it receives, and to prevent a deprecation warning at startup.
# This setting cannot end in a slash.
#server.basePath: ""

# Specifies whether Kibana should rewrite requests that are prefixed with
# `server.basePath` or require that they are rewritten by your reverse proxy.
# This setting was effectively always `false` before Kibana 6.3 and will
# default to `true` starting in Kibana 7.0.
#server.rewriteBasePath: false

# The maximum payload size in bytes for incoming server requests.
#server.maxPayloadBytes: 1048576

# The Kibana server's name.  This is used for display purposes.
server.name: "mcjca033031"

# The URLs of the Elasticsearch instances to use for all your queries.
elasticsearch.hosts: ["http://mcjca033078:9200", "http://mcjca032215:9200", "http://mcjca032254:9200"]

# When this setting's value is true Kibana uses the hostname specified in the server.host
# setting. When the value of this setting is false, Kibana uses the hostname of the host
# that connects to this Kibana instance.
#elasticsearch.preserveHost: true

# Kibana uses an index in Elasticsearch to store saved searches, visualizations and
# dashboards. Kibana creates a new index if the index doesn't already exist.
#kibana.index: ".kibana"

# The default application to load.
#kibana.defaultAppId: "home"

# If your Elasticsearch is protected with basic authentication, these settings provide
# the username and password that the Kibana server uses to perform maintenance on the Kibana
# index at startup. Your Kibana users still need to authenticate with Elasticsearch, which
# is proxied through the Kibana server.
#elasticsearch.username: "kibana"
#elasticsearch.password: "pass"

# Enables SSL and paths to the PEM-format SSL certificate and SSL key files, respectively.
# These settings enable SSL for outgoing requests from the Kibana server to the browser.
#server.ssl.enabled: false
#server.ssl.certificate: /path/to/your/server.crt
#server.ssl.key: /path/to/your/server.key

# Optional settings that provide the paths to the PEM-format SSL certificate and key files.
# These files validate that your Elasticsearch backend uses the same key files.
#elasticsearch.ssl.certificate: /path/to/your/client.crt
#elasticsearch.ssl.key: /path/to/your/client.key

# Optional setting that enables you to specify a path to the PEM file for the certificate
# authority for your Elasticsearch instance.
#elasticsearch.ssl.certificateAuthorities: [ "/path/to/your/CA.pem" ]

# To disregard the validity of SSL certificates, change this setting's value to 'none'.
#elasticsearch.ssl.verificationMode: full

# Time in milliseconds to wait for Elasticsearch to respond to pings. Defaults to the value of
# the elasticsearch.requestTimeout setting.
#elasticsearch.pingTimeout: 1500

# Time in milliseconds to wait for responses from the back end or Elasticsearch. This value
# must be a positive integer.
#elasticsearch.requestTimeout: 30000

# List of Kibana client-side headers to send to Elasticsearch. To send *no* client-side
# headers, set this value to [] (an empty list).
#elasticsearch.requestHeadersWhitelist: [ authorization ]

# Header names and values that are sent to Elasticsearch. Any custom headers cannot be overwritten
# by client-side headers, regardless of the elasticsearch.requestHeadersWhitelist configuration.
#elasticsearch.customHeaders: {}

# Time in milliseconds for Elasticsearch to wait for responses from shards. Set to 0 to disable.
#elasticsearch.shardTimeout: 30000

# Time in milliseconds to wait for Elasticsearch at Kibana startup before retrying.
#elasticsearch.startupTimeout: 5000

# Logs queries sent to Elasticsearch. Requires logging.verbose set to true.
#elasticsearch.logQueries: false

# Specifies the path where Kibana creates the process ID file.
#pid.file: /var/run/kibana.pid

# Enables you specify a file where Kibana stores log output.
#logging.dest: stdout

# Set the value of this setting to true to suppress all logging output.
#logging.silent: false

# Set the value of this setting to true to suppress all logging output other than error messages.
#logging.quiet: false

# Set the value of this setting to true to log all events, including system usage information
# and all requests.
#logging.verbose: false

# Set the interval in milliseconds to sample system and process performance
# metrics. Minimum is 100ms. Defaults to 5000.
#ops.interval: 5000

# Specifies locale to be used for all localizable strings, dates and number formats.
# Supported languages are the following: English - en , by default , Chinese - zh-CN .
#i18n.locale: "en"

Also, when I run ss -tunlp | grep 5601 during Kibana startup, I am seeing Kibana service is listening on 5601. However, in between multiple automatic attempts to connect to ES, it stops listening on 5601 and ss -tunlp | grep 5601 returns nothing.

A:
FATAL  [mapper_parsing_exception] No handler for type [flattened]

Use Elastic non-OSS v7.3+ or Kibana OSS.
The Kibana 7.5 non-OSS (basic) uses the flattened type available in the OSS version of Elasticsearch 7.3+.
The OSS version contains only features that are available under the Apache 2.0 license - https://www.elastic.co/subscriptions
You can check it using GET _nodes:
{
  "name" : "flattened",
  "version" : "7.5.0",
  "elasticsearch_version" : "7.5.0",
  "java_version" : "1.8",
  "description" : "Module for the flattened field type, which allows JSON objects to be flattened into a single field.",
  "classname" : "org.elasticsearch.xpack.flattened.FlattenedMapperPlugin",
  "extended_plugins" : [
    "x-pack-core"
  ],
  "has_native_controller" : false
},

*

*Kibana OSS: https://artifacts.elastic.co/downloads/kibana/kibana-oss-${VERSION}-linux-x86_64.tar.gz

*Kibana non-OSS: https://artifacts.elastic.co/downloads/kibana/kibana-${VERSION}-linux-x86_64.tar.gz

*Elastic OSS: https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-oss-${VERSION}-no-jdk-linux-x86_64.tar.gz

*Elastic non-OSS: https://artifacts.elastic.co/downloads/elasticsearch/elasticsearch-${VERSION}-no-jdk-linux-x86_64.tar.gz


text:
Q: How to modify JSON to custom structure Im trying to change my JSON that is read from a dataTable

[{"englishText":"dog","languageText":"hund"},
    {"englishText":"cat","languageText":"katt"},
    {"englishText":"house","languageText":"hus"}]

to look like this

{
   "dog": "hund",
   "cat" : "katt",
    "house" : "hus"
  }

so that i can use it with i18n in React

A: You can use Array.reduce as follows:

const source = [{"englishText":"dog","languageText":"hund"}, {"englishText":"cat","languageText":"katt"}, {"englishText":"house","languageText":"hus"}]

const target = source.reduce((obj, o) => {
  obj[o.englishText] = o.languageText;
  return obj;
}, {});

console.log(target);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can someone give a clear-cut idea of $E(X|XIf $X$ and $Y$ be two i.i.d. random variables, then what should $E(X|X<Y)$ essentially look like?
P.S.-Is the denominator equal to $\frac12$?
(the two r.v.'s being iid serving as the motivation behind this.)

A: The i.i.d requirement creates useful symmetries, so indeed there is a factor of $1/2$ in some formulas.  The following is one attempt to interpret "looks like" in a useful and intuitive fashion.

The possibilities for $(X,Y)$ partition into three events: $X\lt Y,$ $X\gt Y,$ and $X=Y.$
Therefore, assuming all expectations exist,
$$\mathbb{E}(X+Y) = \mathbb{E}(X+Y\ |\ X\lt Y) \Pr(X\lt Y) + \mathbb{E}(X+Y\ |\ X\gt Y) \Pr(X\gt Y) \\+  \mathbb{E}(X+Y\ |\ X= Y) \Pr(X= Y).$$
Writing $p_0$ for $\Pr(X=Y)$, the symmetry $X\to Y, Y\to X$ shows that the remaining probability of $1-p_0$ is equally split over the events $X\lt Y$ and $X\gt Y$:
$$\Pr(X\lt Y) = \Pr(Y\lt X) = \Pr(X \gt Y) = \frac{1-p_0}{2}.$$
The same symmetry shows the first two conditional expectations are equal while the third reduces to
$$\mathbb{E}(X+Y\ |\ X= Y) \Pr(X=Y) = 2\mathbb{E}(X | X=Y)p_0.$$
Write
$$\mu_0 = \mathbb{E}(X | X=Y).$$
Solving for the conditional expectation yields
$$\mathbb{E}(X+Y\ |\ X \lt Y) = 2 \frac{\mu - \mu_0p_0}{1-p_0}.$$
Similar (but slightly easier) manipulations show that
$$\mathbb{E}(Y - X \ |\ X \lt Y) = \frac{\mathbb{E}(|Y-X|)}{1-p_0}.$$
Because $X = \frac{1}{2}\left((X+Y) - (Y-X)\right),$
$$\mathbb{E}(X \ |\ X \lt Y) = \frac{\mu - \mu_0p_0 - \mathbb{E}(|Y-X|)/2}{1-p_0}.$$
To begin understanding this, suppose the common distribution of $X$ and $Y$ is continuous: this implies $p_0=0$.  The foregoing expression reduces to
$$\mathbb{E}(X \ |\ X \lt Y) = \mu - \mathbb{E}(|Y-X|)/2,$$
(wherein the expected factor of $1/2$ clearly appears).  That is,

For continuous distributions, the conditional expectation of $X$, given that $X\lt Y$, is less than the unconditional expectation of $X$ by half the expected size of the difference $|Y-X|$.

(This result is intuitively obvious: the amount by which the conditional expectation of $X$ falls below the unconditional expectation must be exactly the amount by which the conditional expectation of $Y$ exceeds the unconditional expectation and those two amounts sum to the expected difference.)
The additional terms $\mu_0$ and $p_0$ can now be understood as corrections for the possibility that $X=Y$.  They are a little harder to obtain intuitively, which is why some care was taken with the foregoing analysis.


text:
Q: Recording issue in loadrunner I'm able to access my application normally. But while recording in Google-chrome with load-runner Events are getting recorded but Application is getting hanged and not able to proceed further. I tried changing port in LR still the same issue. Provide some tips to resolve it.
I'm using HTTP protocol for recording in URL mode
Thanks

A: These URLs might help you in solving it
http://www.jds.net.au/tech-tips/how-to-fix-common-vugen-recording-problems/
http://h30499.www3.hp.com/t5/HP-LoadRunner-and-Performance/5-tips-to-solve-the-most-common-problems-seen-in-Web-recording/ba-p/6357387

A: Please check the supporting browsers for your vugen version that will help you.

A: Go for Proxy mode recording.   Proxy mode is browser agnostic


text:
Q: Combining two functions to apply them to the same input I'm new to Haskell and I'm still getting my head around it. I'm trying to combine two functions (isMark and isAlpha from Data.Char module in base package) as a first argument to Data.Text.filter function. What I've tried so far was:
import qualified Data.Char as C
import qualified Data.Text as T
import           Data.Text (Text)

strippedInput :: Text -> Text
strippedInput input = T.filter (C.isMark || C.isAlpha) input

which doesn't work, or
strippedInput input = T.filter (C.isMark . C.isAlpha) input

but obviously it doesn't work either, as the type of C.isAlpha is Char -> Bool which then becomes an input to C.isMark which is also of type Char -> Bool so types don't match.
I'd like to achieve the "C.isMark OR C.isAlpha" logic in the predicate but because of my very limited knowledge I've run out of ideas on how to search for the solution.

A: The simplest is to make use of a lambda-expression:
strippedInput :: Text -> Text
strippedInput input = T.filter (\x -> C.isMark x || C.isAlpha x) input
You can furthermore make use of the fact that a function is an applicative functor, and thus work with:
import Control.Applicative(liftA2)

strippedInput :: Text -> Text
strippedInput input = T.filter (liftA2 (||) C.isMark C.isAlpha) input

A: The accepted answer is perfectly right. Perhaps I would like to use the applicative operator though;
strippedInput = T.filter $ (||) <$> C.isMark <*> C.isAlpha

However the problem with liftA2 is, as depicted by the name, it is hardwired only to two parameter functions and yes, it is OK for this question. Yet... Haskell provides a more reasonable general abstraction for this job. It's basically called the function monad that is mostly generalized as the Reader monad by adding some utility functions and transformer abilities. However for simplicity we can try the function monad here.
Function/Reader monad is used to chain up not only two but indefinite number of functions (each taking two parameters) in which case the first parameter is fed by the previous function result and the second by a common read only state (in this case it is the input)
So the answer to this question could also be like
strippedInput = T.filter (C.isMark >>= (\b c -> b || C.isAlpha c) >>= return)

However since the Data.Char package is full of isThis, isThat type of checks we can show how one may extend this approach.
strippedInput = T.filter (C.isMark >>= (\b c -> b || C.isAlpha  c)
                                   >>= (\b c -> b || C.isSymbol c)
                                    .
                                    .
                                   >>= return)

and.. nobody stops you to make a comparison function such as
orWith f      = \b c -> b || f c
strippedInput = T.filter $ C.isMark >>= orWith C.isAlpha
                                    >>= orWith C.isSymbol
                                     .
                                     .
                                    >>= return


text:
Q: How to prove that a recursive function is equal to another formula? Define recursively b sub 0 = 1 and for n > 0, let b sub n = 3b sub (n−1) − 1. Prove by
induction the formula holds: b sub n =(3^(n)+1)/2.
I started out with a basis:
Let n=1
We get that
2=2
Induction Step:
Assume for a fixed n, n>0, that 3b sub (n-1) -1 = (3^(n)+1)/2
Want to show that if the formula is true for n, it works for n+1.
Where should I go from here? I am not all too familiar with induction proofs involving recursive sequences.

A: Hint:
Using the original recursion and the inductive step, you have
$$\begin{equation}\begin{aligned}
b_{n+1} & = 3b_{n} - 1 \\
& = 3\left(\frac{3^n + 1}{2}\right) - 1 \\
& = \left(\frac{3^{n+1} + 3}{2}\right) - \frac{2}{2} \\
& = \frac{3^{n+1} + 1}{2}
\end{aligned}\end{equation}\tag{1}\label{eq1A}$$
This is the same was you would get from your proposed formula for $n + 1$.


text:
Q: How to parse a CSV line in java I am having different use case than just using a csv reader and providing it with a CSV file for parsing. I need a java library for which I can provide a line from a CSV file and it should be able to parse it.
Any java libraries available which can do that ? (I tried google'ing for a while before posting this.). I found opencsv from apache, in its java docs it says it has a API called CSVParser which takes a line and parses it, but that API doesn't really exist in the binaries.
I am trying this dependency
<dependency>
    <groupId>net.sf.opencsv</groupId>
    <artifactId>opencsv</artifactId>
    <version>2.0</version>
</dependency>

and try initializing CSVParser. Its doesn't work. I am not sure there is a different or new version of opencsv, which I am missing, please let me know

A: I'm not sure what you mean by "it doesn't really exist". OpenCSV works perfectly. A usage example from the official website:
CSVReader reader = new CSVReader(new FileReader("yourfile.csv"));
String [] nextLine;
while ((nextLine = reader.readNext()) != null) {
    // nextLine[] is an array of values from the line
    System.out.println(nextLine[0] + nextLine[1] + "etc...");
}

Note, that CSVReader wraps CSVParser which is more low-level. The above example should be sufficient for any regular use, though.


text:
Q: What would be the sequence of $n!!$ (double factorial) I know that the sequence of $n!$ is $$n(n-1)(n-2)\cdots(2)(1)$$ but what would be the sequence of $n!!$?
(In the interest of clarity, this is also known as the double factorial, not to be confused with $(n!)!$, i.e. the factorial of $n!$.)
Would it be $n^2(n-1)^2(n-2)^2\cdots(2)^2(1)^2$?

A: Assuming you refering to the notation $n!!$ instead of $(n!)!$ this is the so-called double factorial defined as the following
$$n!!=\begin{cases}n\cdot(n-2)\cdots3\cdot1&,\text{for odd } n>0\\n\cdot(n-2)\cdots4\cdot2&,\text{for even } n>0\\1 &,\text{for } n=0,-1\end{cases}$$
This definition can be either rewritten as a product formulation similiar to the one of the factorial or it can be expressed in terms of the factorial. To be precise the double factorial $(2n-1)!!$ is given by
$$(2n-1)!!=\frac{(2n)!}{2^n n!}$$
which can be proved via inductiion. Another interesting expression is given by the Pochhammer Symbol connecting the double factorial with the Gamma Function. Thus it can be written as
$$(2n-1)!!=2^n\frac{\Gamma(n+1/2)}{\Gamma(1/2)}$$
Hopefully this gives you a little insight on what the double factorial is and especially how it is related to the factorial.

A: for even n $n!!=\prod_{k=1}^{\frac{n}{2}} 2k=n(n-2)(n-4)...4.2$
for odd n $n!!=\prod_{k=1}^{\frac{n+1}{2}} 2k-1=n(n-2)(n-4)...3.1$


text:
Q: Input string was not in a correct format while doing ParseInt in C# I am trying to do a Parse int in C# but I am getting the exception in the line int mFrom = int.Parse(fromTo.Substring(1, fromTo.IndexOf("C"))); like below

"System.FormatException: Input string was not in a correct format.

Code is below:
using System;
using System.Linq;
using System.Linq.Expressions;
using System.Text.RegularExpressions;
 class Program
   {
    static void Main()
     {
       string fromTo= "M5000C001";
       int mFrom = int.Parse(fromTo.Substring(1, fromTo.IndexOf("C")));
       int cFrom = int.Parse(fromTo.Substring(fromTo.LastIndexOf("C") + 1));
       Console.WriteLine("FromTo" + mFrom);
     }
}

A: Try this:
IndexOf will return the index of the character literal that you have requested.
string fromTo= "M5000C001";
int mFrom = int.Parse(fromTo.Substring(1, fromTo.IndexOf("C") - 1));
int cFrom = int.Parse(fromTo.Substring(fromTo.LastIndexOf("C") + 1));
Console.WriteLine("FromTo" + mFrom);

Refer this documentation.

A: Start by breaking your code apart:
string fromTo = "M5000C001";
var stringMFrom = fromTo.Substring(1, fromTo.IndexOf("C"));
var stringCFrom = fromTo.Substring(fromTo.LastIndexOf("C") + 1);

Console.WriteLine(stringMFrom);
Console.WriteLine(stringCFrom);

You'll see from the output that stringMFrom contains a character, which is causing the problem.
You can now work out what it is you need to tweak, which looks like it should end up being:
string fromTo = "M5000C001";
var stringMFrom = fromTo.Substring(1, fromTo.IndexOf("C") -1);
var stringCFrom = fromTo.Substring(fromTo.LastIndexOf("C") + 1);

Console.WriteLine(stringMFrom);
Console.WriteLine(stringCFrom);

If you now put the calls to int.Parse back in, you'll see success:
string fromTo = "M5000C001";
var stringMFrom = fromTo.Substring(1, fromTo.IndexOf("C") -1);
var stringCFrom = fromTo.Substring(fromTo.LastIndexOf("C") + 1);
int mFrom = int.Parse(stringMFrom);
int cFrom = int.Parse(stringCFrom);
Console.WriteLine("FromTo" + mFrom);

There's no real need to have the int.Parse and fromTo.Substring all form part of one statement, it makes it a bit harder to debug in circumstances like this and it's likely the compiler will reduce both my code above, and your original (with the added -1) to the same code in the end. Always try to write your code so it's as clear and easy to work with as possible for you.

A:   string fromTo= "M5000C001";
       int mFrom = int.Parse(fromTo.Substring(1, fromTo.IndexOf("C")));

In your code fromTo.Substring(1, fromTo.IndexOf("C")) would return 5000C. So do it accordingly either subtract 1 from index  or use lastIndex.

A: another approach using linq (and imho a bit more easy, if you are interrested)
you could split for M and C, parse them and take first and last. If there is no C Last() would be equal to First()
static void Main(string[] args)
{
    string fromTo = "M5000C001";

    IEnumerable<int> values = fromTo.Split('M', 'C')
                                    .Where(w => !string.IsNullOrWhiteSpace(w))
                                    .Select(int.Parse)
                                    .ToList();
    int from = values.First();
    int last = values.Last();

    Console.WriteLine("From" + from);
    Console.WriteLine("Last" + last);
}


text:
Q: exclude multiple terms using get_terms() function I am using this function to filter category terms from a calendar:
  $terms = get_terms( TribeEvents::TAXONOMY, array( 'orderby' => 'name', 'order' => 'ASC','exclude' => array(77)) );

  echo '
Category:
';
  foreach ( $terms as $term ) {
    echo '
term_taxonomy_id.'">'.$term->name.'
';
  }

I need to exclude event category ID 71 too. How can I do that?

A: With get_terms(), the exclude parameter takes an array of term IDs, so just add the second term to the array:
$terms = get_terms( TribeEvents::TAXONOMY, array(
                        'orderby' => 'name',
                        'order'   => 'ASC',
                        'exclude' => array( 77, 71 ),
) );

echo '
Category:
';
foreach ( $terms as $term ) {
    echo '
term_taxonomy_id.'">'.$term->name.'
';
}


text:
Q: EF 4 - Exception when updating table with timestamp column I have created the following table in SQL Server
CREATE TABLE [dbo].[Role](
   [Id] [int] IDENTITY(1,1) NOT NULL,
   [Name] [nvarchar](20) NOT NULL,
   [CreatedDate] [datetime] NULL,
   [TIMESTAMP] [timestamp] NOT NULL,
   [ModifiedDate] [datetime] NULL,

   CONSTRAINT [PK_TBL_ROLES] PRIMARY KEY CLUSTERED ([Id] ASC)
       WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF,
             ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY].

With EF, I created a ste class with timestamp column of type byte[] which is readonly.
I retrieve an object from my db using the datacontext e.g.
var roleObject = roleService.getObject(id);

now I change the rolename as follows
roleObject.Name = "New Name";
roleObject.ModifiedDate = DateTime.Now;

finally I call my repository to persist the object using the following generic method
public void PersistUpdatedItem(T entity){
   _ctx.ApplyCurrentValues(typeof (T).Name, entity);
   _ctx.ObjectStateManager.ChangeObjectState(entity, EntityState.Modified);
   _ctx.SaveChanges();
}

Note ctx is my session object and T is the entity class. At this point I get an exception

Cannot update Timestamp Column

Can someone please assist me in solving this one.
thanks

A: Two points:

*

*You cannot make Timestamp property "read only". EF must be able to set that value so the property must have setter and accessibility of the setter must be same as accessibility defined in the designer.

*Your Timestamp property must be configured with Concurrency Mode Fixed and StoreGenerated Pattern Coumputed. Both these configurations are defined in properties window in the designer.

A: Just remove the timestamp from your model object.


text:
Q: C# Windows Service (Network Service user) - UnauthorizedAccessException We have hosted the windows service in Machine 1 as NetworkService account. When windows service tries to delete files from a shared folder in Machine 2, we are getting UnauthorizedAccessException. Shared Folder has given full permissions as NetworkService account. But if we are giving full permissions for EveryOne or Users for Shared folder, then everything goes well. We have tried setting the directory and file attributes to Normal. But still same exception is coming up.

Machine1 and Machine 2 is in same domain. Logged in to both machine as
  same user with admin privileges.

  SetDirAttributesNormal(new DirectoryInfo("//Machine2//SharedFolder"));

  private static void SetDirAttributesNormal(DirectoryInfo dir)
        {
            foreach (var subDir in dir.GetDirectories())
                SetDirAttributesNormal(subDir);
            foreach (var file in dir.GetFiles())
            {
                file.Attributes = FileAttributes.Normal;
            }
        }


text:
Q: How do I make a logarithmic histogram in SQL? My table:
val
1
2
3
4
5
6
10
15

Desired results:
bin | qty
1   | 1
2   | 2
4   | 3
8   | 3

Which means there are, with inclusive/exclusive ranges,

*

*1 value between 1-2,

*2 values between 2-4,

*3 values between 4-8,

*3 values between 8-16.

A: Your bin size, in this case, in logarithmic terms, is 2.
If you wish to use another bin size, substitute the 2s in the script below.
select
    pow(2, floor(ln(val) / ln(2))) as bin,
    count(bin) as qty
from
    mytable
group by
    bin;

Explanation
First, we take the log of your values in base 2. log(val, 2) might work in some RDBMS, but if not, just remember the log property that log(val, 2) = ln(val) / ln(2).
val | ln(val) / ln(2)
1   | 0
2   | 1
3   | 1.58496250072
4   | 2
5   | 2.32192809489

Then we floor this:
val | floor(ln(val) / ln(2))
1   | 0
2   | 1
3   | 1
4   | 2
5   | 2

Finally, we use the power of two to transform these floored values into the logarithmic bin values.
val | pow(2, floor(ln(val) / ln(2)))
1   | 1
2   | 2
3   | 2
4   | 4
5   | 4

The rest is simply grouping by the logarithmic bins and counting.
Caveats
No pow
If your RDBMS does not support pow(x, y), you can use exp(y * ln(x)). The expression then becomes:
    exp(floor(ln(val) / ln(2)) * ln(2))

Zero
log(0) is undefined. In the RDBMS I tested, it returns null.
If your table has values of 0, you most likely want to bin them between 0 and 1. To do that, you can wrap the whole expression with ifnull(..., 0), like so:
    ifnull(pow(2, floor(ln(val) / ln(2))), 0)

Negative
The log of negative numbers is undefined... But you probably want to bin them like [0 to -1), [-1 to -2), [-2 to -4), [-4 to -8), etc.
If your database has negative values, you can achieve that binning by first using abs in your value, then in the end restoring its original signal by multiplying the result by val/abs(val). Your expression then becomes:
pow(2, floor(ln(abs(val)) / ln(2))) * val/abs(val)

Negative and zero
If your database has both negative and zero values, you should wrap the ifnull around everything else. Otherwise, the val/abs(val) part would make you divide by zero, re-introducing nulls.
ifnull(pow(2, floor(ln(abs(val)) / ln(2))) * val/abs(val), 0)


text:
Q: Check if a field exists in an object in js_of_ocaml In my wrap.ml, I have a function as follows:
  Js.Unsafe.global##.test := Js.wrap_callback (
    fun params ->
      print_endline "params##.a:";
      print_endline (Js.to_string params##.a);
      print_endline "params##.b:";
      print_endline (Js.to_string params##.b);
      Js.string ((Js.to_string params##.a) ^ (Js.to_string params##.b))
  );

As a result, in a JavaScript file, I could call e.g., test({a: "abc", b:"efg"}).
I would like to know in the OCaml file, is there a way to check if the field b exists in the object params, before evaluating Js.to_string params##.b?

A: You can see how to do this at the bottom of this page:

https://ocsigen.org/js_of_ocaml/latest/manual/bindings

For this code:
let () =
    if Js.Optdef.test ((Js.Unsafe.coerce Dom_html.document)##.URL) then
        Printf.printf "document.URL exists\n"
    else
        Printf.printf "document.URL does not exist\n";
    if Js.Optdef.test ((Js.Unsafe.coerce Dom_html.document)##.XXX) then
        Printf.printf "document.XXX exists\n"
    else
        Printf.printf "document.XXX does not exist\n";

I see the following on the Javascript console:
document.URL exists
document.XXX does not exist


text:
Q: how to get out from admin/text mode I have literaly no idea on what happened and what are the next steps.
I've installed the upgrade to 18.04.1 LTS after restarting computer I found myself in admin (?)/text (? - I even don't know the proper name).
It asks me to log in.
Apparently I enter the correct data.
Than it shows:
XXX@XXX:~$

what should I type? Kind request for 6-year old level answer, my coding understanding is probably even not at that level.
CTRL+D, exit, ~Desktop - did not work. It comes back to login and password request.
Any help will be appreciated.

A: Do you mean you get into text console after boot up? Try to login and type startx - it should get you to graphical environment. Its a temporal solution, if it works.
May be something wrong with greeter, if above runs fine, try reinstall it: sudo apt-get --reinstall install gdm3
Also do run sudo systemctl enable graphical.target

A: It sounds like you set the default target on your machine to something other than graphical.  Try
sudo systemctl enable graphical.target

and then reboot and see what happens.

A: So, I run all the suggested commands. It (I mean the device) gave me, generally speaking, "all field" response to any try. An hour passed. Partly devastated I looked  time at TTY (new word - thanks LeonidMew!) nothing changed. While moving it I accidentally turned off the wi-fi button and than instinctively turned it back on. Some new strange/scary info appeared on my TTY. So, pannic buttons configuration was pressed (CTRL+ALT+DEL) and... IT WARKS AGAIN! I am back in GIU. Thank,I love you guys. You are fantastic!

A: Open a text-only virtual console by using the keyboard shortcut Ctrl+Alt+F3.
Press the keyboard shortcut Ctrl+Alt+F7 to exit the virtual console.


text:
Q: Which analysis to use to discriminate morphometrics measurements from different species from 2 different environment? So I have a dataset of measurements (lengths, surface areas, volumes...) from 3 species from 2 different environments, with 3 individuals per species. Can be summarised like that:
ENVIRO  SPECIES  INDIV  meas1  meas2   ...
1       sp1       A     8017    4.5    ...
1       sp1       B     5019    4.5    ...
1       sp1       C     8017    4.6    ...
2       sp2       D     8870    2.1    ...
2       sp2       E     8305    2.0    ...
2       sp2       F     8305    2.2    ...
2       sp3       G     8221    2.6    ...
2       sp3       H     8994    2.5    ...
2       sp3       I     8775    2.5    ...

I have about 40 measurement variables... I was looking at trying to do a something like a linear discriminant analysis do discriminate between environment 1 and 2. However, I have way too many variables (~40) compared to observations (9) to make it work.
Could anyone advise me on which other analysis (on R) would allow me to study the relationships of these morphological measurements with an environment? (if that is even possible before getting more observations).
I would appreciate any ideas. Thank you!

A: This is how I would do it with R, assuming that the data is in the object data.
library("RGCCA") # Library for the canonical correlation analysis
environment <- data[, 1]
measures <- data[, 4:44]
A <- list(environment, measures)
tau <- c(1, tau.estimate(measures)) # Regularization parameter, 1 for covariance with the environment.
C <- matrix(c(0, 1, 1, 0), ncol = 2, nrow = 2) # Design matrix
CCA <- rgcca(A, tau, C, scheme = "centroid")

However, I think this is to few data to make an accurate relationship between environment and measurements. It would be perfect if you could have more samples/individuals for both environments


text:
Q: Zend captcha html I am creating captcha like this using Zend_Form:
class Form_Signup extends Zend_Form {

    public function __construct( array $options = null ) {

        // set method
        $this->setMethod('post');

        // other elements here

        // captcha
        $captcha = new Zend_Form_Element_Captcha('captcha', array(
                'id'=>'captcha',
                'title'=>'Security Check.',
                'captcha' => array(
                'captcha' => 'Image',
                'required' => true,
                'font'=> 'fonts/ARIALN.TTF',
                'wordlen'=>'4',
                'width'=>'200',
                'height'=>'50',
                'ImgAlign'=>'left',
                'DotNoiseLevel'=>'30',
                'LineNoiseLevel'=>'7',
                'Expiration'=>'1000',
                'fontsize'=>'30',
                'gcFreq'=>'10',
                'imgdir'=> 'images/captcha/',
                'ImgAlt'=>'Captcha',
                'imgurl'=>'/images/captcha/'
                )));
        $captcha->removeDecorator('HtmlTag')
        ->removeDecorator('Label')
        ->addDecorator('Label');

        // add captcha
        $this->addElement( $captcha );
        $this->setDecorators( array( array( 'ViewScript', array( 'viewScript' => 'signup/signup-form.phtml' ) ) ) );
    }

}

It is generating HTML like this:

<input type="hidden" name="captcha[id]" value="cabf4d4d759ae8e4b7404b95e032e231" title="Security Check." id="captcha">
<input type="text" name="captcha[input]" id="captcha" value="" title="Security Check.">

But I want textbox of captcha below the image like this:

<input type="hidden" name="captcha[id]" value="cabf4d4d759ae8e4b7404b95e032e231" title="Security Check." id="captcha">
<input type="text" name="captcha[input]" id="captcha" value="" title="Security Check.">

Any idea ?
Thanks

A: Zend Captcha element decorators are little complected. The batter solution to this is to create our own decorators. And once you are done with it. you can change the order as you want
You can find complete answer here
If you are not in hurry, and if you have enough time then Go through this article by Methew explaining how to play with decorators.
Near about same question I asked here, where I dont wanted to create a Separate decorator class, but did not get any proper answer. And then I did some css trick and forced <input type='text'> to go down. So only solution is to generate Custom captcha decorator class.
If you don't get anything there then let me know. Thank you


text:
Q: PowerBuilder Datawindow Crashes when Opening I've been working on a payroll system right now and been modifying a ledger type datawindow. Suddenly, after testing the data the powerbuilder crashes...
What i have done is uncheck the "Remember the retrieval argument" but to no avail. Every time im opening the datawindow, the application crashes.
what fix can I use?

A: Maybe some of the programmer here who are new to powerbuilder might be asking this but to solve this problem, you have to delete the datawindow registry key in regedit. the key is located at HKEY_CURRENT_USER/SOFTWARE/Sybase/Layout/Default
There you will see at least 9 registry key. Close you powerbuilder IDE and then delete the Datawindow key. Open you PowerBuilder IDE again and it should get rid of the Datawindow crashing down.
Thanks!


text:
Q: what is the difference between TDengine 3.0 datafile and 2.0 datafile? in the 2.0, I can see the datafile composed of three files which are .data file,.last,.head file.
By the time of 3.0 version. it is changed to data, stt, head, sma file.
what is the difference between TDengine 3.0 datafile and 2.0 datafile?

A: In TDengine 3.0 version , there is no .smal file anymore but only .sma file . it is the equivalent of .smad file in 2.0 version
the .data file in  TDengine 3.0 version is the partly same thing with .data file in 2.0 . except for multi-version introduced.
the .head file in  TDengine 3.0 version is the total same thing with .head file in 2.0 .
.stt file in  TDengine 3.0 version is the functionally same thing with .last file in 2.0  .


text:
Q: Angular i18n : How to make language change using URL routing /Switcher Buttons? I am building a simple app to learn internationalisation using Angular 11. The tutorial I am following is: https://lokalise.com/blog/angular-i18n/
I followed the tutorial and tried to create an app with 2 configurations - an En (english) one and an Ru (russian). When I run the app with

ng serve --configuration=ru --open

I can see the russian translation
when I use:

ng serve

It shows me the English version of the app.
Both these configurations run in different ports. I tried to create a language switcher to be able to switch between the english and russian version of the app here is the code for that in

app.component.ts & app.component.html

import { Component } from '@angular/core';
import {registerLocaleData} from '@angular/common';
import localeRu from '@angular/common/locales/ru';

registerLocaleData(localeRu, 'ru');

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
    company = "Ash B.";
  created_by = $localize`Created by ${this.company}`
  today: number = Date.now();
   localesList = [
    { code: "en-US", label: 'English' },
    { code: "ru", label: 'Русский' }
  ];
  tasksCount = 201;
  genderCode = 0;

  // tslint:disable-next-line:typedef
  male() { this.genderCode = 0; }
  // tslint:disable-next-line:typedef
  female() { this.genderCode = 1; }
  // tslint:disable-next-line:typedef
  other() { this.genderCode = 2; }
}

      {{locale.label}}

When I click on the buttons it changes the url from

localhost:4200/ru to localhost:4200/en-Us

but the content of the app is not translated. In order to see the translation I must run 2 different versions of the app. How can I make the language switch when I click on the buttons ?

A: to switch between versions you need to serve the build instead of serving the development configuration, each language will be compiled into a separate bundle, watch your dist folder after you run ng build --localize=true to make sure everything went ok.


text:
Q: jquery append text if doesnot exists I am trying to append text if it does not exists inside a form , if it exists donot append:
<form method="post" action="" class="horizontal-form">
<fieldset>
<input type="file" align="left" name="patient_image[]" multiple="multiple" min="1" max="6"/>
</fieldset>
</form>
jQuery(function(){

$('form').each(function () {
    if ($(this).find('fieldset').html() ===  '
Total image size is limited to 4MB.  If you are uploading more than one image, the total combined size is still 4MB.  Files should be formatted into JPG or BMP.') {
       $("input[name*='patient_image']").after('
Total image size is limited to 4MB.  If you are uploading more than one image, the total combined size is still 4MB.  Files should be formatted into JPG or BMP.');
    }
});

});

Here is the link to fiddle I have tried so far: http://jsfiddle.net/zbpv5zfk/37/

A:

jQuery(function() {
  var sText = 'Total image size is limited to 4MB.  If you are uploading more than one image, the total combined size is still 4MB.  Files should be formatted into JPG or BMP.';
  $('form').find('fieldset:not(:contains("' + sText + '"))')
  .find("input[name*='patient_image']").after( '
' + sText);
});

<form method="post" action="" class="horizontal-form">
  <fieldset>
    <input type="file" align="left" name="patient_image[]" multiple="multiple" min="1" max="6" />
  </fieldset>
</form>

A: It will never happens, because if you dump to the console this: $(this).find('fieldset').html() the valu of that will be:
`
                    <input name="patient_image[]" multiple="multiple" min="1" max="6" align="left" type="file">
             [and a new line and a lot of space here]

So, what you need is to do is check a part of your text, is there are, and append if not:
$(function() {
    if ($(this).find('fieldset').html().indexOf('Total image size is limited to 4MB') === -1) {
        $(this).find('fieldset').after('
Total image size is limited to 4MB.  If you are uploading more than one image, the total combined size is still 4MB.  Files should be formatted into JPG or BMP.');
    }
});

See working jsfiddle: http://jsfiddle.net/zbpv5zfk/38/
Of course you can use your whole string also. But i think, this is a bad practice, because if you want to change anything in your text, that is hard to maintain.


text:
Q: Can I modify a Xcode Build Settings from a cordova plugin's plugin.xml? I am creating a custom Cordova plugin that requires some custom Xcode Build Settings to be specified (for example, CLANG_CXX_LANGUAGE_STANDARD).
I thought I would be able to set it using the config.xml specs of the cordova-custom-config plugin as follows:
 <custom-preference name="ios-XCBuildConfiguration-CLANG_CXX_LANGUAGE_STANDARD" value="gnu++0x" quote="none" buildType="release" />
 <custom-preference name="ios-XCBuildConfiguration-CLANG_CXX_LANGUAGE_STANDARD" value="gnu++0x" quote="none" buildType="debug" />
 <custom-preference name="ios-XCBuildConfiguration-CLANG_CXX_LIBRARY" value="libc++" quote="none" buildType="release" />
 <custom-preference name="ios-XCBuildConfiguration-CLANG_CXX_LIBRARY" value="libc++" quote="none" buildType="debug" />
 <custom-preference name="ios-XCBuildConfiguration-GCC_C_LANGUAGE_STANDARD" value="gnu99" quote="none" buildType="release" />
 <custom-preference name="ios-XCBuildConfiguration-GCC_C_LANGUAGE_STANDARD" value="gnu99" quote="none" buildType="debug"/>

However, when installing the plugin with plugman install they are not applied.
Any suggestion on how to modify Xcode Build Settings from a Cordova plugin? Thanks

A: You can add build flags to the build.json
{
    "ios": {
        "debug": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "FG35JLLMXX4A",
            "packageType": "development",
            "buildFlag": [
                "EMBEDDED_CONTENT_CONTAINS_SWIFT = YES",
                "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES=NO",
                "LD_RUNPATH_SEARCH_PATHS = \"@executable_path/Frameworks\""
            ]
        },
        "release": {
            "codeSignIdentity": "iPhone Developer",
            "developmentTeam": "FG35JLLMXX4A",
            "packageType": "app-store",
            "buildFlag": [
                "EMBEDDED_CONTENT_CONTAINS_SWIFT = YES",
                "ALWAYS_EMBED_SWIFT_STANDARD_LIBRARIES=NO",
                "LD_RUNPATH_SEARCH_PATHS = \"@executable_path/Frameworks\""
            ]
        }
    }
}

https://cordova.apache.org/docs/en/latest/guide/platforms/ios/#using-buildjson


text:
Q: Part (a) of Exercise 13 of first chapter of Rudin's book "Functional Analysis" I would really appreciate it if you could give me some advice on the part (a) of Exercise 13 of first chapter of Walter Rudin's book "Functional Analysis":

Let $C$ be the vector space of all complex continuous functions on $[0, 1]$. Define
  \begin{equation}
d(f,g) = \int_0^1 \frac{\lvert f(x) - g(x) \rvert}{1 + \lvert f(x) - g(x) \rvert} \ dx \ .
\end{equation}
  Let $(C, \sigma)$ be $C$ with the topology induced by this metric. Let $(C, \tau)$ be the topological vector space defined by the semi-norms
  \begin{equation}
P_x(f) = \lvert f(x) \rvert, \qquad (0 \leq x \leq 1),
\end{equation}
  Prove that every $\tau$-bounded set in $C$ is also $\sigma$-bounded and that the identity map $id: (C, \tau) \rightarrow (C, \sigma)$ therefore carries bounded sets into bounded sets.

I tried using the theorem that says a set $E \subseteq C$ is bounded if and only if every semi-norm in our semi-norms is bounded on $E$. This theorem tells us that if $E$ be a bounded set in $(C, \tau)$, then for every $x \in [0, 1]$, $P_x(E)$ is bounded, i.e.
\begin{equation}
\forall x \in [0, 1] \ \exists M_x, \quad s.t. \quad \forall f \in E, \quad \lvert f(x) \rvert \leq M_x \ .
\end{equation}
I think now we should use Uniform boundedness principle and obtain $M > 0$ such that
\begin{equation}
\forall x \in [0, 1] \ \forall f \in E, \quad \lvert f(x) \rvert \leq M \ .
\end{equation}
Then we have $d(f, 0) \leq \frac{M}{1+M}$ for all $f \in E$. So $E$ is bounded in $(C, \sigma)$.
In the last step, to use Uniform boundedness principle, I think we should prove that $(C, \tau)$ is a Banach space, and $(C, \sigma)$ a normed space. I don't know what should I do in this step.

A: What's condition of UBP and what's the conclusion? You need a Banach space, a normed linear space and a linear map between them. Your conclusion is also about the norm of a bounded linear map. Where is the linear map in your question?
Even if you define those $Q_x$, they are linear functionals in the dual space of $C[0,1]$ with the $\|\cdot\|_\infty$ norm. Nothing about these $f\in E$ can you obtain from the boundedness of these functionals.
Besides, what's the definition of a bounded set in some topological vector space? It is not equivalent to a bounded set with respect to some metric. Actually the whole space is already bounded with respect to the metric.
If $B_r(0)$ is an open $0$-nbhd in ($C,\sigma)$, you want to show $\exists t>0$ s.t. $E\subseteq t\cdot B_r(0)$. For some $f\in E$, $f=t\cdot\frac{f}{t}.$ Your goal is to prove $\frac{f}{t}\in B_r(0)$. i.e.
$$
    \int_0^1
        \frac
            {\frac{|f(x)|}{t}}
            {1+\frac{|f(x)|}{t}}
    dx
    = \int_0^1 \frac{|f(x)|}{t+|f(x)|}dx<r.
$$
That is to find some $t$ big enough such that $\int_0^1\frac{|f(x)|}{t+|f(x)|}dx$ can be arbitrarily small for pointwise bounded family of functions. When $t\to\infty$, $\frac{|f(x)|}{t+|f(x)|}\to0$ pointwise and $\frac{|f(x)|}{t+|f(x)|}$ is always bounded by an integrable function. What does this imply? Can you prove that
$$
\lim_{t\to\infty}\int_0^1 \frac{|f(x)|}{t+|f(x)|}dx=0?
$$
How to make that happen for all $f\in E$ so that you can have the $t$ big enough uniformly? i.e. the following hidden hint.

 The pointwise supreme of any family of lower semi-continuous functions is also lower semi-continuous thus measurable.

 Define $\phi(x)=\sup_{f\in E}|f(x)|$. They are all bounded thus $\phi$ is a well defined real function and $\phi$ is lower semi-continuous. Thus $$d(f/t,0)=\int_0^1\frac{|f(x)|}{t+|f(x)|}dx\le\int_0^1\frac{\phi(x)}{t+\phi(x)}dx\to 0\ \ (DCT).$$

A: You want to apply the UBP to the functionals given by the point evaluations, say $Q_x (f)=f (x) $. So your $Y $ ( in the notation from the linked article in Wikipedia ) is $\mathbb C $.
And the topology on $C $ plays no role in your argument: you are already assuming that, for each $f\in E $, $|Q_x (f)|\leq M_x$. So you apply the UBP to the functionals $\{Q_x\}_{x\in [0,1]} $ acting on the Banach space $C [0,1] $.


text:
Q: jQuery plugin dev: null or empty function as default for optional callbacks? I'm developing my first jQuery plugin that offers a number of optional callbacks. For example, there's an onChange callback that fires when the value of an input field changes.
For all of the settings, I have a defaults object that holds the default values, which is then merged with the instance settings: var settings = $.extend({}, defaults, options);
What is the best default value for these optional callbacks? Right now, I use null, but this requires that I check if the callback is a function or not all over the place:
if ($.isFunction(settings.onChange)) {
  settings.onChange(...);
}

Is a better default an empty function? Or something else? What's the standard in jQuery plugin development?
Thanks!

A: You can use null as the default value and do:
var settings = $.extend({}, defaults, options);
settings.onChange && settings.onChange(/* arguments */);

A: I think that the best decision - use empty functions


text:
Q: Suddenly error coming up in content repository when accessing documents stored Widlfly machine is setup with modeshape which uses infinispan.
When i try to accesing documebnts stored through front end, suddenly below error is coming up.
execution error: org.infinispan.persistence.spi.persistenceexception: java.io.ioexception: unsupported protocol version 0
before this server ran out of memory problem. I took backup of logs and freed the space before restarting the server then this problem is popping up.
What might have gone wrong and is there any to recover files. I can see files in there so there was no evidence of data loss.
Below is the error
ISPN000136: Execution error: org.infinispan.persistence.spi.PersistenceException: java.io.IOException: Unsupported protocol version 0
rshalledEntryImpl.java:114) [infinispan-core-6.0.2.Final.jar:6.0.2.Final]


text:
Q: Подсчет количества статей в родительской категории Так вот выглядит таблица категорий, реализована безграничная вложенность
CREATE TABLE IF NOT EXISTS `articles_cat_baby` (
`id` int(11) NOT NULL auto_increment,
`realid` int(11) NOT NULL,
`refid` int(11) NOT NULL default '0',
`name` text NOT NULL,
`text` text NOT NULL,
`kartinka` text NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT
CHARSET=utf8;

Таблица статей
CREATE TABLE IF NOT EXISTS `articles_baby` (
`id` int(11) NOT NULL auto_increment,
`id_user` int(11) NOT NULL,
`id_cat` int(11) NOT NULL,
`name` text NOT NULL,
`text` longtext NOT NULL,
`moderation` int(1) NOT NULL default '2',
`time` int(11) NOT NULL,
`prosmotrov` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT
CHARSET=utf8;

Подсчет количества статей в категории - mysql_result(mysql_query("SELECT COUNT(*) FROM articles".$prefixbaby." WHERE id_cat='".$row['id']."';"),0)
Вопрос: как подсчитать количество статей в родительской категории?
A: Как-то так:
SELECT
  COUNT(*) AS cnt
FROM
  articles_cat_baby AS c,
  articles_baby AS a
WHERE
  c.id = $id AND
  a.id_cat = c.refid

P.S: У вас ужасные имена колонок


text:
Q: DRF method GET not allowed on @action based function I have the two models: Article and Comment. I have the ArticleAPI viewset, which have methods decorated with @action to handle requests to comments model, but when I am trying to test this endpoint via Postman I get an error:
{
    "detail": "Method \"GET\" not allowed."
}

ArticleAPI.py
class ArticleAPI(viewsets.ModelViewSet):
    serializer_class = ArticleSerializer
    permission_classes = [
        permissions.IsAuthenticatedOrReadOnly
    ]
    queryset = Article.objects.order_by('number')
    lookup_field = 'pk'

    ...

    @action(methods=['GET'], detail=True,
            url_path='comments', url_name='article-comments-list')
    def get_comments_queryset(self, request):
        instance = self.get_object()
        serializer = CommentSerializer(queryset=instance.comment_set.all(), many=True)
        return Response(serializer.data)

    @action(methods=['GET'], detail=True,
            url_path='comments', url_name='article-comments-object')
    def get_comment_object(self, request, pk=None):
        instance = self.get_object()
        serializer = CommentSerializer(queryset=instance.comment_set.get(pk=pk))
        return Response(serializer.data)
    @action(methods=['post'], detail=True,
            url_path='comments', url_name='article-create-comment')
    def create_comment(self, request):
        serializer = CommentSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.create(serializer.data)
        return Response({
            "comment": serializer.data
        }, status=201)

    @action(methods=['patch'], detail=True,
            url_path='comments', url_name='article-update-comment')
    def partial_update_comment(self, request):
        instance = self.get_object()

        if not self.check_self_or_admin(request, instance):
            return Response({
                "errors": "Logged in user and author must be same"
            }, status=403)

        serializer = CommentSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        self.partial_update(serializer.data)
        return Response({
            "comment": serializer.data
        })

    @action(methods=['delete'], detail=True,
            url_path='comments', url_name='article-update-comment')
    def delete_comment(self, request):
        instance = self.get_object()

        if not self.check_self_or_admin(request, instance):
            return Response({
                "errors": "Logged in user and author must be same"
            }, status=403)

        self.perform_destroy(instance)
        return Response(status=204)

urls.py
router = SimpleRouter()
router.register('articles', articleAPI.ArticleAPI, basename='articles')

UPD:
my routes related to comments
<URLPattern '^articles/(?P<pk>[^/.]+)/comments/$' [name='articles-article-create-comment']>, <URLPattern '^articles/(?P<pk>[^/.]+)/comments/$' [na
me='articles-article-update-comment']>, <URLPattern '^articles/(?P<pk>[^/.]+)/comments/$' [name='articles-article-comments-object']>, <URLPattern '^articles/(?P<pk>[^/.]+)/comments/$' [name='articles-article-comments-list']>, <URLPattern '^articles/(?P<pk>[^/.]+)/co
mments/$' [name='articles-article-update-comment']>]

UPD 2:
Also POST and other method are not working


text:
Q: AVAssetExportSession only exporting audio I am trying to export a QuickTime movie file with a video track in DNxHD and a couple of audio tracks in "Integer (Little Endian)", into a natively supported codec, like h.264.
The export succeeds with the code below but unfortunately the output movie only contains the audio track (in AAC, which is ok).  Why is it not transcoding the video track, despite not reporting any errors?
The code:
NSURL * url = [NSURL fileURLWithPath:inPath];
NSDictionary * options = @{ AVURLAssetPreferPreciseDurationAndTimingKey : @YES };
AVURLAsset * asset = [[[AVURLAsset alloc] initWithURL:url options:options] autorelease];

AVAssetExportSession * exportSession =
[AVAssetExportSession exportSessionWithAsset:asset
                                  presetName:AVAssetExportPreset1280x720];

if (nil == exportSession)
    return NO;

exportSession.outputURL = [NSURL fileURLWithPath:outPath];
exportSession.outputFileType = AVFileTypeQuickTimeMovie;

__block BOOL success = NO;
__block BOOL done = NO;

// perform the export
[exportSession exportAsynchronouslyWithCompletionHandler:^{

    switch ([exportSession status])
    {
        case AVAssetExportSessionStatusCompleted:
            NSLog(@"Export succeeded");
            success = YES;
            done = YES;
            break;

        case AVAssetExportSessionStatusFailed:
            NSLog(@"Export failed: %@", [[exportSession error] localizedDescription]);
            done = YES;
            break;

        case AVAssetExportSessionStatusCancelled:
            NSLog(@"Export canceled");
            break;

        default:
            NSLog(@"Export Session Status: %d", exportSession.status);
            break;
    }
}];

while (!done)
    usleep(1000*250);

return success;


text:
Q: More theading confusion. Why are Semaphores SO slow? This question is a sequel to my previous question (Threading in Python - What am I missing?).
Thanks to the people who indicated where the threading problem was. That problem finally solved, I enabled the semaphores and was surprised that just enabling them took the execution time of the program from a fraction of a second to 4 seconds! WOW... 3 seconds for just 80000 iterations seems frighteningly slow, even taking into account the collisions.
The exact times:
Without semaphore      0.0167980194092 s
With semaphore         2.76963996887 s

Here's the code:
import threading
import time
import random

turnstile_names = ["N", "E", "S", "W"]
count = 0
sem = threading.Semaphore(1)

class Incrementer(threading.Thread):
    def __init__(self, id):
        threading.Thread.__init__(self)
        self.id = id

    def run(self):
        global count, sem
        for i in range(20000):
            sem.acquire()
            count = count + 1
            sem.release()

def main():

    random.seed(507129)
    incrementers = [Incrementer(name) for name in turnstile_names]

    for incrementer in incrementers:
        incrementer.start()

    # We're running!

    for incrementer in incrementers:
        incrementer.join()

    print count
    return 0

if __name__ == '__main__':
    main()

A: I can't comment on why the semaphore is so slow, but there is a way to significantly speed up your code by using a lock instead of a semaphore:
lock = threading.Lock()

class Incrementer(threading.Thread):
    def __init__(self, id):
        threading.Thread.__init__(self)
        self.id = id

    def run(self):
        global count, lock
        for i in range(20000):
            with lock:
                count = count + 1

No synchronisation: 0.02s
Semaphore synchronisation: 2.69s
Using a lock: 0.36s
That said, I think that acquiring and releasing a semaphore eighty thousand times in slightly more than two and a half seconds is decent performance - thread synchronisation comes at a cost - but you should look at your options and select the tool that fits your use case the best, and in this case it's a lock and not a semaphore since you only have one resource.

A: Semaphores are implemented in Operating System. They offer the ability to synchronize among other processes which can not be achieved using locks.
So the reason that they are slow should be obvious now, each time you interact with a semaphore the process needs to make a system call to OS , context switches to Kernel Mode , do the logic and then again context switch back to the calling process if it is not blocked.


text:
Q: how to embed spring mvc application with jetty I have a working Spring MVC application(doing everything I wanted when deployed to jboss) and now I'm looking a way how to start my application from a jar. What I've though of is when starting jar, first some kind of web server should be started in order to be able to run the application.
And I've tried like a tons of combinations with jetty(lost about 2 days already), and I failed every one of them, mostly suggestions from https://stackoverflow.com/tags/embedded-jetty/hot
My main weakness is that I don't really have thorough understanding of servlets, contexts and so on. Terms which I see on a regular basis while browsing google search, maybe I found a solution already but didn't understand it.
Has anyone done something similar? And yes I've asked similar question for tomcat :
Maven tomcat plugin

A: Yes, I've done this sort of this several times, and it's fairly straight forward if you know how the bits work.
Since you've explained that you don't know how the bits work, that's going to be a bit harder :)
But they're not too hard to learn, and the easiest way to learn is by doing - so you're heading down the right path.
The accepted answer here: Executable war file that starts jetty without maven is some of the best advice you're going to get on this topic.
I would suggest:

*

*Create a WAR to start with (which you probably have from your JBoss deployment)

*Get that WAR running under standard Jetty (fairly straight forward, with lots of tutorials around)

*Then follow the advice I linked to, to turn embedded Jetty into your WAR file.

If you run into any issues, ask specific questions with specific examples of what went wrong, and we'll try and help out.


text:
Q: is function continuous? Let G be the real line with addition as the group operation and with the topology for which the open sets are those that either are empty or have a countable complement  then we want to show that (x,y) $\mapsto$ x+y is continuous if either one of the entries is held fixed. This is my approach. Suppose that $x_0$ $\in$ $G$ is fixed. Let $U$ be open in $\mathbb{R}$. Then, $U$:=$\mathbb{R}$-$\{x_n\}_{n=1}^{\infty}$ for some countable collection $\{x_n\}_{n=1}^{\infty}$ $\subset$ $\mathbb{R}$. The complete preimage of $U$ is
\begin{eqnarray}
\nonumber \{(x_0,y) \in \{x_0\} \times \mathbb{R}: x_0+y \in U \} &=& \{(x_0, y) \in \{ x_0 \} \times \mathbb{R} : x_0+y \neq x_n, n \in N \}\\
\nonumber &=&\{(x_0,y) \in \{ x_0 \} \times \mathbb{R}:y \neq x_n-x_0,  n \in N \}\\
\nonumber &=&\{x_0\} \times (\mathbb{R}-\{x_n-x_0\}_{n=1}^{\infty}).
\end{eqnarray}
How to show that this set is open $\in \{x_0\} \times \mathbb{R}$ to show that the map [($x_0$,$y$) $\longmapsto$ $x_0$+$y$]: $\{$ $x_0$ $\}$ $\times$ $\mathbb{R}$ $\longrightarrow$ $\mathbb{R}$ is continuous.


text:
Q: "If" Clause, Type 3, and Perfect Tense
"If he had come yesterday, he might have seen his sister."

This sentence implies he didn't come yesterday and didn't see his sister.

"If he has come YESTERDAY, he may have seen his sister."

İ know that i cannot use this sentence with YESTERDAY to imply that i don't know whether he came or not.
Why is it possible to use it with past perfect,  when I know that the action didn't happen and I imagine an unreal situation about this past action ?

A: *

*In your first sentence the construction "If he had come" is not an ordinary past perfect: it is employed to express the unreality of a past event.
You might find my answer at this question helpful.

*In your second sentence, present perfect is a present tense construction, not a past tense, and may not be used with temporal expressions such as "yesterday" which do not include the present. What you want here is an ordinary past tense expressing a possible event, one which may or may not have happened:

If he came yesterday he may have seen his sister.


text:
Q: Flask proxy response for file download I am using a Flask route as a proxy to download a file, like this:
@esa_handler.route("/data/<int:series>/<int:file_num>", methods=["GET"])
def DownloadRemote(series, file_num):
    """
    Downloads the remote files from the ESA.
    :param series: 0-20.
    :param file_num: File within the series, 0-255
    :return: Compressed CSV file.
    """

    # if the file is bad.
    if series >= 20 and file_num > 110:
        return jsonify({"error": "file does not exist."})

    url = "http://cdn.gea.esac.esa.int/Gaia/gaia_source/csv/GaiaSource_000-{:03d}-{:03d}.csv.gz".format(series,
                                                                                file_num)
    req = requests.get(url, stream=True)
    return Response(stream_with_context(req.iter_content(chunk_size=2048)), content_type=req.headers["content-type"])

It works fine, however, the filename that is presented to the client is whatever the file number that is passed to the endpoint. For example, if I put http://127.0.0.1:5000/esa/data/0/0 to download the very first file, it downloads, but Chrome/Firefox/IE/Edge are offering to save the file with a filename as "0". While there is nothing wrong with that, I would like a better user experience.
How can I intercept the response to proffer a filename based off the URL requested?

A: This can be done with the Content-Disposition HTTP header. Here you can specify a filename for the newly downloaded file.
This can be added to a Flask Response as follows:
url = "http://cdn.gea.esac.esa.int/Gaia/gaia_source/csv/GaiaSource_000-{:03d}-{:03d}.csv.gz".format(series,
req = requests.get(url, stream=True)

headers = Headers()
headers .add('Content-Type', req.headers["content-type"])
headers .add('Content-Disposition', 'attachment; filename="filename.txt"')

return Response(stream_with_context(req.iter_content(chunk_size=2048)), headers=headers)

Note: The Content-Type was moved into headers for simplicity


text:
Q: how to prevent duplicated mail without deleting mails on server I run getmail + maildrop to get all mails locally, but every time getmail runs, it will download a copy of all messages.
even setting delete option in getmail or mailfilter config does not help
the related config:
[options]
verbose = 5
read_all = 0
delete = 0
/usr/bin/reformail  -D 8000 $HOME/.getmail/duplicate.cache
if ( $RETURNCODE == 0 )
 exit


text:
Q: When using the gtsummary library, I get the warning that says the calculation of the p-value differs from the summary stats. How can this be fixed? The warning states: "Some observations included in the calculation of summary statistics were omitted from the p-value calculation due to unbalanced missingness within group."
Here is my code:
add_p_ex2 <-
  temp2 %>%
  mutate(Intervention = forcats::fct_rev(Intervention)) %>%
  tbl_summary(by = Intervention, missing = "always", include = -id) %>%
  add_p(
    # perform t-test for all variables
    test = `Medication Used` ~ "paired.t.test", group = id) %>%
  modify_caption("**Text**")
add_p_ex2

temp 2 has columns with being the amount of medications used, and the second column represents the time point (before or after)


text:
Q: How to get sources for Android 7.1.1 (Nougat)? At the of writing, there is no option to download Sources for Android 25:

Does it not have released yet? Or my SDK manager is broken?

A: SDK 25 sources are now available for download in the SDK manager. After downloading you might need to refresh the SDK with this trick to make Android Studio aware of them.


text:
Q: For multi-page forms where parent has to call validate() on child, how to manage state? To provide some context, I am working on building a multi-page form where each page is its own component that should re-render itself in response to (valid/invalid) user input and prevent the form to move to the next page for invalid inputs on current page. Since there is no two-way binding in React, I leveraged a shared context provider between parent-child and used a custom hook to access validation logic. In order to perform the validation checks from the parent I attach a reference to a function which I call inside the child by sending it via props. Each time the parent has to move to next page it simply calls the function that is pointed to by this reference.
Shared context:

class Role {
    id: string = '';
    description: string = '';
    tenure: string = '';
}

class Person {
    name: string = '';
    age: string = '';
    roles: Role[] = [];
}

export const SharedContextProvider: React.FC = ({children}) => {
    const [person, setPerson] = useState<Person>(new Person('', ''));

    const validateName = () => {
        let isValid = person.name !== '';
        return {isValid: () => isValid, error: () => isValid ? '' : 'Invalid Name'};
    };
    ...; // other validation methods here skipped

    const isValidSection = (errorSetters: Map<FIELDS, (error: string) => void>, validatorHelper: Map<FIELDS, Helper>) => {
        let isValidSection = true;
        errorSetters.forEach((setError, field) => {
            let validation = validatorHelper.get(field);
            if (!validation) {
                throw new Error('validation not defined!');
            }
            let isValidField = validation.isValid(); // check if field is valid
            isValidSection = isValidSection && isValidField;
            let error = validation?.error() || '';
            console.log('Validating', field, 'isValid:', isValidField, 'error:', error);
            let doSth = errorSetters.get(field)!!;
            doSth(error); // debugging
        });
        return isValidSection;
    }

    const personalDetailsValidator = (errorSetters: Map<FIELDS, (error: string) => void>) => {
        const validatorHelper = new Map<FIELDS, Helper>(
            [
                [FIELDS.NAME, validateName()],
                [FIELDS.AGE, validateAge()],
            ]
        );
        return {isValidSection: () => isValidSection(errorSetters, validatorHelper)};
    };

    const professionalDetailsValidator = (role: Role, errorSetters: Map<FIELDS, (error: string) => void>) => {
        const validatorHelper = new Map<FIELDS, Helper>(
            [
                [FIELDS.DESCRIPTION, validateRoleDescription(role)],
                [FIELDS.TENURE, validateTenure(role)],
            ]
        );

        return {isValidSection: () => isValidSection(errorSetters, validatorHelper)};
    };

    const data: SharedContextValue = {
        person,
        personalDetailsValidator,
        professionalDetailsValidator,
        setPerson
    };

    return <SharedContext.Provider value={data}>{children}</SharedContext.Provider>
}

const useSharedContext = () => {
    const context = useContext(SharedContext);
    if (context === undefined) {
        throw new Error('Cannot be undefined');
    }
    return context;
}

Parent
const App = () => {
    const [
        activeStepIndex, // controls page on the form
        setActiveStepIndex
    ] = React.useState(0);

    let isCurrentSectionValid: () => boolean; // reference to function

    const validationHandler = (validateSection: () => boolean) => {
        isCurrentSectionValid = validateSection;
    }

    return (
        <Wizard
            i18nStrings={{...}}
            onNavigate={({detail}) => {
                let isValidSection = isCurrentSectionValid();
                console.log('[isValidSection]', isValidSection);
                if (isValidSection) {
                    setActiveStepIndex(detail.requestedStepIndex)
                }
            }
            }
            activeStepIndex={activeStepIndex}
            steps={[
                {
                    content: <PersonalDetails validationHandler={validationHandler}/>
                },
                {
                    title: "Completed",
                    content: <Final validationHandler={validationHandler}/>,
                    isOptional: true
                },
            ]}
        />
    );
}

Child1

const PersonalDetails: React.FC<PersonalProps> = ({validationHandler}) => {
    const {person, personalDetailsValidator, setPerson} = useSharedContext();
    const [name, setName] = useState(person.name || '');
    const [age, setAge] = useState(person.age || '');
    const [nameErrorText, setNameErrorText] = useState<string>('');
    const [ageErrorText, setAgeErrorText] = useState<string>('');

    useEffect(() => {
        setPerson(new Person(name, age));
    }, [name, age]);

    const validator = personalDetailsValidator(new Map<FIELDS, (error: string) => void>([
        [FIELDS.NAME, setNameErrorText],
        [FIELDS.AGE, setAgeErrorText],
    ]));

    // store validation state for each child
    const rolesValidators: Map<string, () => boolean> = new Map<string, () => boolean>();
    const roleValidationHandler = ((validateSection: () => boolean, id: string) => {
        rolesValidators.set(id, validateSection);
    });

    validationHandler(() => {
        let isValidSection = validator.isValidSection();
        let areValidRoles = Array.from(rolesValidators.values()).map(item => item())
            .reduce((i, j) => i && j, true);
        console.log('isValidSection', isValidSection, 'areValidRoles', areValidRoles);
        return isValidSection && areValidRoles;
    });

    return (
        <Container
            header={
                <Header variant="h2">
                    Personal Info
                </Header>
            }
        >
            <SpaceBetween direction="vertical" size="l">
                <FormField label="Name" errorText={nameErrorText}>
                    <Input value={name} placeholder={'Enter Name'} onChange={({detail}) => {
                        setName(detail.value);
                    }}/>
                </FormField>
                <FormField label="Age" errorText={ageErrorText}>
                    <Input value={age} placeholder={'Enter Age'}
                           onChange={({detail}) => {
                               setAge(detail.value);
                           }}
                    />
                </FormField>
                {person.roles.map((role, index) =>
                    <ProfessionalDetails key={role.id} validationHandler={roleValidationHandler} role={role}/>)}
            </SpaceBetween>
        </Container>
    );
}

Child2:
const ProfessionalDetails: React.FC<ProfessionalProps> = ({validationHandler, role}) => {
    const [description, setDescription] = useState(role.description || '');
    const [tenure, setTenure] = useState(role.tenure || '');
    const [descriptionErrorText, setDescriptionErrorText] = useState<string>();
    const [tenureErrorText, setTenureErrorText] = useState<string>();
    const {professionalDetailsValidator} = useSharedContext();

    const validator = professionalDetailsValidator(role, new Map<FIELDS, (error: string) => void>([
        [FIELDS.DESCRIPTION, setDescriptionErrorText],
        [FIELDS.TENURE, setTenureErrorText],
    ]));

    validationHandler(() => {
        return validator.isValidSection();
    }, role.id);

    useEffect(() => {
        role.description = description;
        role.tenure = tenure;
        console.log('Updating role...', JSON.stringify(role));
    }, [role]);

    return (
        <Container
            header={
                <Header variant="h2">
                    Professional Info
                </Header>
            }
        >
            <SpaceBetween direction="vertical" size="l">
                <FormField label="Description" errorText={descriptionErrorText}>
                    <Input value={description} placeholder={'Enter Occupation'}
                           onChange={event => setDescription(event.detail.value)}/>
                </FormField>
                <FormField label="Tenure" errorText={tenureErrorText}>
                    <Input value={tenure} placeholder={'Enter Hobby'}
                           onChange={event => setTenure(event.detail.value)}/>
                </FormField>
            </SpaceBetween>
        </Container>
    );
}

Child1,Child2 is validated as expected in isolation. But for list of child2 components if previous states capture an error (for empty input) then the state is not reset when the error is rectified and the errors are retained preventing moving to the next page.
I had two questions:

*

*Is this a sustainable approach to validate forms with deep nested components?

*What are good patterns for parent-child communication in these situations?

Note: I cannot use Redux due to my company constraints. It has to be done via React Context/Hooks.


text:
Q: Omniauth + apple + rails error: nonce_mismatch Trying to Sign in with Apple on my Rails6 app. It looks like I may be making multiple omniauth calls? But I don't have anything referenced in my devise.rb file.
Here's the error log:
> Started POST "/users/auth/apple" for 71.232.157.93 at 2021-11-18
> 15:58:12 +0000 DEBUG -- omniauth: (apple) Request phase initiated.
> Started POST "/users/auth/apple/callback" for 71.232.157.93 at
> 2021-11-18 15:58:17 +0000 DEBUG -- omniauth: (apple) Callback phase
> initiated. ERROR -- omniauth: (apple) Authentication failure!
> nonce_mismatch: OmniAuth::Strategies::OAuth2::CallbackError,
> nonce_mismatch | nonce mismatch
> Processing by CallbacksController#failure as HTML
> HTTP Origin header (https://appleid.apple.com) didn't match request.base_url (https://www.mywebsite.com)
> Completed 422 Unprocessable Entity in 1ms (ActiveRecord: 0.0ms | Allocations: 292)
> ERROR -- omniauth: (apple) Authentication failure! ActionController::InvalidAuthenticityToken: ActionController::InvalidAuthenticityToken, ActionController::InvalidAuthenticityToken
> Processing by CallbacksController#failure as HTML
> HTTP Origin header (https://appleid.apple.com) didn't match request.base_url (https://www.mywebsite.com)
> Completed 422 Unprocessable Entity in 0ms (ActiveRecord: 0.0ms | Allocations: 162)
> ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):

gemfile
gem 'omniauth-apple'
gem "omniauth-rails_csrf_protection", "~> 1.0"

routes.rb:
  devise_for :users, :controllers => { :omniauth_callbacks => "callbacks" }

config/initializers/omniauth.rb:
Rails.application.config.middleware.use OmniAuth::Builder do

  result = OpenSSL::PKey::EC.new(env[APPLE_PEM])
  key = result.to_pem

  provider :apple, 'com.myapp.auth', '',
           {
             scope: 'email name',
             team_id: 'ENV[APPLE_TEAM_ID]',
             key_id: 'ENV[APPLE_KEY_ID]',
             pem: key,
             redirect_uri: 'https://www.mywebsite.com/users/auth/apple/callback',
             provider_ignores_state: true
           }
end

user.rb
 devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable,
         :omniauthable, :omniauth_providers => [:apple]

def self.from_omniauth(auth)
    where(provider: auth.provider, uid: auth.uid).first_or_create do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.email = auth.info.email
      user.phone = '000-000-0000'
      user.password = Devise.friendly_token[0,20]
      user.remember_me = true
    end
  end

callbacks_controller.rb
class CallbacksController < Devise::OmniauthCallbacksController
    def apple
        @user = User.from_omniauth(request.env["omniauth.auth"])
        sign_in_and_redirect @user
    end
end

view.html.erb
<%= link_to user_apple_omniauth_authorize_path, method: 'post' do %>

<% end %>


text:
Q: My computer wouldn't shut down so i pulled out mains lead, now my computer won't switch back on. What can i do? Have My computer was switched on but I lost connection to the monitor, it was blank with just digital and analogue notice in left hand corner so I couldn't shut computer down even when holding in On button. I pulled out mains lead from PC and now it won't work at all. Have I permanently damaged my PC or its it fixable?

A: Find a bootable USB Key (Windows Install Key, or make a Linux bootable USB key. Try to start with a USB Key. Does it run?  If not, something broke, which caused it not to start.
If the above as all true and it won't run, take it to a local computer shop.


text:
Q: Local max/min points, partial derivatives I'm having a lot of problems with figuring out how to properly do max/min with partial derivatives.
To my knowledge, we have:
$$D(x, y) = f_{xx}(x, y)f_{yy}(x, y) - (f_{xy}(x, y))^{2}$$
With the following conditions:
-If $D > 0$ and $f_{xx} < 0$, the critical point is a local max
-If $D > 0$ and $f_{xx} > 0$ then the critical point is a local min
-If $D < 0$ then the point is a saddle point
-If $D = 0$ then the test is inconclusive
I have the following function:
$$f(x,y) = 2xye^{-x^{2}-y^{2}}$$
I solved the first derivatives (not entirely sure that these are right):
$$f_{x}(x, y) =2ye^{-x^{2}-y^{2}} \cdot (-2x) = -4xye^{-x^{2}-y^{2}}$$
$$f_{y}(x, y) =2xe^{-x^{2}-y^{2}} \cdot (-2y) = -4xye^{-x^{2}-y^{2}}$$
But now I have no idea how to solve $f_{x} = 0$ and $f_{y} = 0$ to find my critical points. I suspect I have to do the natural logarithm of something?
Any help is appreciated, thanks!

A: We have:
$$f(x,y) = 2xye^{-x^{2}-y^{2}}$$
A plot of this shows:

A different view shows:

A contour plot shows:

The partials are:

*

*$f_{x}(x, y) = 2 y e^{-x^2-y^2}-4 x^2 y e^{-x^2-y^2}$

*$f_{y}(x, y) = 2 x e^{-x^2-y^2}-4 x y^2 e^{-x^2-y^2}$

*$f_{xx}(x, y) = 8 x^3 y e^{-x^2-y^2}-12 x y e^{-x^2-y^2}$

*$f_{yy}(x, y) = 8 x y^3 e^{-x^2-y^2}-12 x y e^{-x^2-y^2}$

*$f_{xy}(x, y) = f_{yx}(x, y) = -4 x^2 e^{-x^2-y^2}+8 x^2 y^2 e^{-x^2-y^2}+2 e^{-x^2-y^2}-4 y^2 e^{-x^2-y^2}$

You should have five critical points as:
$$(x, y) = (0,0), \left(-\dfrac{1}{\sqrt{2}}, -\dfrac{1}{\sqrt{2}}\right), \left(-\dfrac{1}{\sqrt{2}}, \dfrac{1}{\sqrt{2}}\right), \left(\dfrac{1}{\sqrt{2}}, -\dfrac{1}{\sqrt{2}}\right), \left(\dfrac{1}{\sqrt{2}}, \dfrac{1}{\sqrt{2}}\right)$$
To find these we have $f_x = f_y = 0$, which leads to the following:
$$2 y - 4 x^2 y = 0, 2 x - 4 x y^2 = 0 \implies 2x^2 = 1, 2y^2 = 1, ~\mbox{and}~x=y=0$$
This gives a total of five roots (critical points) shown above.
Can you now proceed?

A: If $f(x,y)=2xye^{-x^2-y^2}$, then $$\frac{\partial f}{\partial x}=2ye^{-x^2-y^2}-4x^2ye^{-x^2-y^2}$$ Setting this equal to 0 gives $$y(1-2x^2)=0$$ and setting $f_y=0$ gives $$x(1-2y^2)=0$$ The possible points are $(0,0),\hspace{2mm}\left(\pm{1\over\sqrt{2}},\pm{1\over\sqrt{2}}\right)$ (the second point is really four different points).
Now you would have to compute the second derivatives, and evaluate the discriminant $D$ at each of these points to determine what type of extrema they are.


text:
Q: Break existing code into java and android modules I have created an Android app. To facilitate maintenance of the code, I want to break it into modules and move code to these modules. I know how to create modules in Android Studio 2.2.2.
I am not able to find any shortcut in the IDE to move the code (something like moving code to a different class using "Refactor" menu item) to the new module.

A: Click on the package or the file you want to move and drag and drop in the src package of the newly created module.


text:
Q: Tool to extract Type and Method signatures from namespace? I am looking to write a black box implementation of an existing Class Library: Microsoft.Xna.Framework.Net.
It would be very helpful if there was a tool to extract write stubs for all the types and method signatures without having to do it myself..

A: I think you can decompile source code and there are very application  such as redgate.


text:
Q: YADCF - filtering using hidden columns Going through this jsFiddle, I wanted to know the YADCF equivalent of hidden columns, as shown in use for the standard DataTables, to enable for filtering from hidden columns (DataTable's targets seems to be equivalent to YADCF's column number).
Below is the code I have for a table where I want to hide the first column,
 yet still allow filtering from it.

$(document).ready(function() {
  'use strict';
  var foodTable = $('#foodTable').DataTable({
  });
  yadcf.init(foodTable, [{
      column_number: 0,
      filter_type: "select",
      visible: "false"
    },
    {
      column_number: 1,
      filter_type: "select"
    }
  ], {
    cumulative_filtering: true,
  });
});

      Category
      Type
      Subtype
      Comments

      Fruit
      Apple
      Fuji
      Very sweet apple

      Vegetable
      Pumpkin
      Butternut
      Very fibrous pumpkin

A: You should place the filter of the hidden column out side of the table, for that purpose you can use filter_container_id (read docs)
for example
yadcf.init(oTable, [{
    column_number: 0,
    filter_container_id: "myId",
    column_data_type: "html",
    filter_type: "multi_select"
},{
    column_number: 1,
    filter_type: "multi_select"
}], "footer");

See working jsfiddle

As to the cumulative_filtering you should use more recent version of yadcf (see change log)