text:
Q: Because project depends on flutter_localizations any from sdk which depends on intl 0.16.1, intl 0.16.1 is required Okay so i have built an app nearly a year and half ago for my company, my boss recently wanted me to add a new screen to it and i did using all old and deprecated code of firebase and everything else (i really really dont wanna update them because i know everything nearly changed and building a whole new app would be better than editing this lol, so i'm trying to avoid that option), the app runs on Android just fine, but it doesnt build on ios and it does not allow me do "flutter build ios" in the terminal giving above error when trying to build ios or trying to pub Get.
Granted my intl version was ^0.16.1 , then it would say that it requires 0.17.0 , then I changed it based on another post here to intl: ^0.17.0-nullsafety.2 but it gives the  output above. what's the problem?
Here is my Pubspec.yaml:
name: tamatafreshiq
description: A new Flutter application.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

version: 1.0.0+1

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

  cloud_firestore: ^0.14.0+2
  firebase_core: ^0.5.0
  shared_preferences: ^0.5.7+2
  firebase_messaging: ^7.0.0
  cupertino_icons: ^0.1.2
  http: ^0.12.0+2
  flutter_spinkit: ^3.1.0
  english_words: ^3.1.5
  firebase_auth: ^0.18.0+1
  provider: ^4.1.3
  firebase_storage: ^4.0.0
  image_picker: ^0.6.7+2
  image_cropper: ^1.2.3
  url_launcher: ^5.4.11
  localization: ^0.1.0
  cached_network_image: ^2.2.0+1
  fluttertoast: ^6.0.1
  badges: ^1.1.3
  data_connection_checker: ^0.3.4
  intl: ^0.17.0-nullsafety.2

dev_dependencies:
  flutter_test:
    sdk: flutter

flutter:
  uses-material-design: true
  assets:
    - assets/images/
    - assets/gifs/
    - assets/languages/
  fonts:
    - family: Rabar
      fonts:
        - asset: assets/fonts/Rabar_014.ttf
    - family: Rubik
      fonts:
        - asset: assets/fonts/Rubik-Light.ttf

A: You need to upgrade your flutter version on your local machine to flutter 2.0+ now cause you are importing null safety supported dependency which uses dart sdk 2.12.0 but you have 2.7.0 which is making conflict with the other dependencies. If you do have 2.0+ already then upgrade the sdk of your app from pubspec.yaml. You will then have to update your code to full sound null safety starting from upgrading all the dependencies then the code, its not that hard even if your app is using firebase I get my apps upgraded to null safety within a week. Once all gets sorts out you'll have no trouble with your project in importing some null safety dependency or some else more importantly you will be able to have better performance of your app and can keep all the dependencies to support latest versions and might possible you app will be android 12 ready too


text:
Q: phpmyadmin vs EPEL I am running Centos 6.0 (Final) , the i386 version.
I am trying my hardest to get a decent LAMP Server running, with phpMyAdmin.
I can get everything installed just fine, MySQL, Apache2 (httpd), PHP 5.x, etc..., but when I get to reading some tutorials on installing phpMyAdmin, I fail miserably.  Each tutorial I read mentions enabling the EPEL/REMI repo..   As soon as I add this repo I am not able to use yum anymore.
I continue to get this error message
[root@username tmp]# yum update
Loaded plugins: aliases, fastestmirror
Loading mirror speeds from cached hostfile
Traceback (most recent call last):
  File "/usr/bin/yum", line 29, in <module>
    yummain.user_main(sys.argv[1:], exit_code=True)
  File "/usr/share/yum-cli/yummain.py", line 285, in user_main
    errcode = main(args)
  File "/usr/share/yum-cli/yummain.py", line 136, in main
    result, resultmsgs = base.doCommands()
  File "/usr/share/yum-cli/cli.py", line 434, in doCommands
    self._getTs(needTsRemove)
  File "/usr/lib/python2.6/site-packages/yum/depsolve.py", line 99, in _getTs
    self._getTsInfo(remove_only)
  File "/usr/lib/python2.6/site-packages/yum/depsolve.py", line 110, in _getTsInfo
    pkgSack = self.pkgSack
  File "/usr/lib/python2.6/site-packages/yum/__init__.py", line 887, in <lambda>
    pkgSack = property(fget=lambda self: self._getSacks(),
  File "/usr/lib/python2.6/site-packages/yum/__init__.py", line 669, in _getSacks
    self.repos.populateSack(which=repos)
  File "/usr/lib/python2.6/site-packages/yum/repos.py", line 279, in populateSack
    self.doSetup()
  File "/usr/lib/python2.6/site-packages/yum/repos.py", line 105, in doSetup
    self.ayum.plugins.run('postreposetup')
  File "/usr/lib/python2.6/site-packages/yum/plugins.py", line 184, in run
    func(conduitcls(self, self.base, conf, **kwargs))
  File "/usr/lib/yum-plugins/fastestmirror.py", line 202, in postreposetup_hook
    all_urls = FastestMirror(all_urls).get_mirrorlist()
  File "/usr/lib/yum-plugins/fastestmirror.py", line 369, in get_mirrorlist
    self._poll_mirrors()
  File "/usr/lib/yum-plugins/fastestmirror.py", line 413, in _poll_mirrors
    pollThread.start()
  File "/usr/lib/python2.6/threading.py", line 474, in start
    _start_new_thread(self.__bootstrap, ())
thread.error: can't start new thread

It's driving me insane.  I am using a VPS so everytime this happens I am easily able to restart from scratch, but after so many times with the same results I have no clue where I am going wrong.

A: Your (very small, and probably crappy OpenVZ) VPS has run out of memory.
You can try working around this by disabling the (probably strictly unnecessary) yum plugins, to reduce the memory usage:
yum --disableplugin=* update

If that doesn't get you any farther, you'll have to stop some services to free up memory.
If you still can't get anywhere, you'll have to upgrade your VPS package.

redpajama_set_name: RedPajamaStackExchange


text:
Q: dialogflow webhook in go I was following the step on this website but when I try to push on Heroku and connect to it with Dialogflow Fulfillment, my website page always says 404 not found.
The heroku logs always show this:
2020-01-17T15:53:17.864991+00:00 heroku[router]: at=error code=H10 desc="App crashed"
method=POST path="/webhook" host=herokugit-test.herokuapp.com request_id=bfed8942-7009-474c-a67c-b84b5e79a94f fwd="64.233.172.43" dyno= connect= service= status=503 bytes=
protocol=https

Here is the code:
package main

import (

    "fmt"
    "net/http"
    "github.com/gin-gonic/gin"
    "github.com/golang/protobuf/jsonpb"
    "github.com/sirupsen/logrus"
    "google.golang.org/genproto/googleapis/cloud/dialogflow/v2"
)

func handleWebhook(c *gin.Context) {
    var err error

    wr := dialogflow.WebhookRequest{}
    if err = jsonpb.Unmarshal(c.Request.Body, &wr); err != nil {
        logrus.WithError(err).Error("Couldn't Unmarshal request to jsonpb")
        c.Status(http.StatusBadRequest)
        return
    }
    fmt.Println(wr.GetQueryResult().GetOutputContexts())
}

func main() {

    var err error

    r := gin.Default()
    r.POST("/webhook", handleWebhook)

    if err = r.Run("127.0.0.1:8080"); err != nil {
        logrus.WithError(err).Fatal("Couldn't start server")
    }
}

How to fix it?
And how to show the right WebhookRequest on my website page?
Thanks a lot for helping me.

A: I think you should obtain the port from the Heroku runtime
var port = os.Getenv("PORT")

It looks like it is hardcoded.


text:
Q: setExposureModeLocked does not work for iPhone 11 and above So, I have an application where I am streaming images and need consistent results across all images even when exposed to bright light(NO AUTO ADJUSTMENTS).
For this I used a AVFoundation as follows:
[device setExposureMode:AVCaptureExposureModeLocked];
This works great for any model below iPhone 11.
It seems like the newer camera modules do not react the same to the functions called in AVFoundation as the older ones. In these images the first 2 has the flash on and after the flash is turned off.Here is an example of any iPhone below the 11.

Here is an example of any iPhone 11 and above.
As you can see they do not lock the same way. If anyone has a similar issue please share your experience or comment what you think may help.
Thanks in advance.


text:
Q: Using Temporary Layer/not loaded Layer in Field Calculator I'm writing a processing script with the given tools from the toolbox.
Now I want to use the Field Calculator to add a column to an output layer of a tool.
The Field Calculator/column should contain a 1/0 if a feature of a layer 'touches' any other feature in the same layer. Since the layer is not yet loaded, while I start the Field Calculator, I can't get it to work.
Another option was to call another function after the algorithm returns all values, but I don't know exactly where to call that function from def processAlgorithm(...).
I tried different approaches for the 'FORMULA'-parameter with the right results but only in QGIS with the loaded layer and not from Python.
fieldcalc_touches = processing.run("native:fieldcalculator", {
            'INPUT':polygonize['OUTPUT'],
            'FIELD_NAME':'HasNeighbours',
            'FIELD_TYPE':1,
            'FIELD_LENGTH':10,
            'FIELD_PRECISION':0,
            'FORMULA':'overlay_touches(@Layer_Name)',
            'OUTPUT':out_fieldcalc_touches},
            is_child_algorithm=True,
            context=context,
            feedback=feedback)

current += 1
feedback.setProgress(int(current * total))


text: Q: Collection of Cylinder-Set as a semi ring This proof should show a collection of cylinder set is a Semi-ring. But for the last point they just showed $B\setminus A$  is either $B$ or $\emptyset$. However $B$ or $\emptyset$ is an element of the semiring itself and according to this proof the collection of cylinder set is even a ring. I cant see the point why it should be a semi ring. Could anyone help?


text:
Q: Editing a torrent's magnet link Is there a way to make a magnet link for downloading specific files of a torrent, for example : adding something to the link to specify (select) the files to be downloaded.

A: Is there a way to make a magnet link for downloading specific files of a torrent?
No. Magnet links don't know anything about files in the torrent.

A magnet link is essentially a hyperlink containing the hash code for
  that torrent, which your torrent client can immediately use to start
  finding people sharing those files. Magnet links don't require a
  tracker (since it uses DHT, which you can read more about here), nor
  does it require you to download a separate file before starting the
  download, which is convenient.

Source What Are Magnet Links, and How Do I Use Them to Download Torrents?


text:
Q: MySQL query - force case-sensitive with a ORDER BY rand( ) Is it possible to force case-sensitive for a query?
Mine sounds like this:
"SELECT g_path FROM glyphs WHERE g_glyph = :g_glyph ORDER BY rand()"

if g_glyph = r, the result can be R or r and it's not what I expect.
I'm looking for a case-sensitive return.
I googled my issue and I found this solution:
/*Case-sensitive sort in descending order.
In this query, ProductName is sorted in
case-sensitive descending order.
*/
SELECT ProductID, ProductName, UnitsInStock
FROM products
ORDER BY BINARY ProductName DESC;

But the following line doesn't work at all:
"SELECT g_path FROM glyphs WHERE g_glyph = :g_glyph ORDER BY BINARY rand()"

Any Suggestion?
Thank you very much for your help.

A: The order and equality of characters is defined by the collation. In most cases, a case-insensitive collation is used.
If you need to use a strict, case-sensitive comparison for a specific datum, use the BINARY operator:
mysql> SELECT 'a' = 'A';
        -> 1
mysql> SELECT BINARY 'a' = 'A';
        -> 0
mysql> SELECT 'a' = 'a ';
        -> 1
mysql> SELECT BINARY 'a' = 'a ';
        -> 0

So in your case:
SELECT g_path FROM glyphs WHERE BINARY g_glyph = :g_glyph ORDER BY rand()

A: This is covered in the manual page Case Sensitivity in String Searches.
You need to specify a case sensitive or binary collation.

The default character set and collation are latin1 and latin1_swedish_ci, so nonbinary string comparisons are case insensitive by default. This means that if you search with col_name LIKE 'a%', you get all column values that start with A or a. To make this search case sensitive, make sure that one of the operands has a case sensitive or binary collation. For example, if you are comparing a column and a string that both have the latin1 character set, you can use the COLLATE operator to cause either operand to have the latin1_general_cs or latin1_bin collation:
col_name COLLATE latin1_general_cs LIKE 'a%'
col_name LIKE 'a%' COLLATE latin1_general_cs
col_name COLLATE latin1_bin LIKE 'a%'
col_name LIKE 'a%' COLLATE latin1_bin

If you want a column always to be treated in case-sensitive fashion, declare it with a case sensitive or binary collation. See Section 13.1.14, "CREATE TABLE Syntax".

The _cs in the collation name stands for "case sensitive".


text:
Q: How to make temporarily center-aligned math equation, when using option [fleqn] for amsmath I am using fleqn for amsmath. So the euqation is default left-aligned.
Now I want to teamporarily make one equation center-aligned. How to do this?
Thank you all.

MWE
\documentclass{article}
\usepackage{ragged2e}
\usepackage[fleqn]{amsmath}

\begin{document}
\section{left-align}
   \begin{equation}
        y = x
   \end{equation}

\section{center-align}
    \begin{equation}
        \centering
         y = x + x
     \end{equation}

\end{document}

A: This is what the ceqn environment, from nccmath is for. Conversely, it defines a fleqn environment for temporarily left-aligned groups of equations  in the default context:
\documentclass{article}
\usepackage{ragged2e}
\usepackage[fleqn]{amsmath}
\usepackage{nccmath}

\begin{document}

\section{left-align}
   \begin{equation}
        y = x
   \end{equation}

\section{center-align}

\begin{ceqn}
    \begin{equation}
        \centering
         y = x + x
     \end{equation}
\end{ceqn}

\end{document}


text:
Q: hadoop3 can not create timeline server hbase table I read the Hadoop 3 about the timeline server v.2 document, it says
Finally, run the schema creator tool to create the necessary tables:

bin/hadoop
  org.apache.hadoop.yarn.server.timelineservice.storage.TimelineSchemaCreator
  -create

The TimelineSchemaCreator tool supports a few options that may come handy especially when you are testing. For example, you can use -skipExistingTable (-s for short) to skip existing tables and continue to create other tables rather than failing the schema creation. By default, the tables will have a schema prefix of "prod.". When no option or '-help' ('-h' for short) is provided, the command usage is printed. and continue to create other tables rather than failing the schema creation. When no option or '-help' ('-h' for short) is provided, the command usage is printed. By default, the tables will have a schema prefix of "prod."
but I cannot find code about TimelineSchemaCreator code in package org.apache.hadoop.yarn.server.timelineservice.storage in any jar about Timeline server, why? is the document not update in time?
# find /opt/ -name 'hadoop-yarn-server-timelineservice*jar'
/opt/hadoop-3.1.1/share/hadoop/yarn/timelineservice/hadoop-yarn-server-timelineservice-3.1.1.jar
/opt/hadoop-3.1.1/share/hadoop/yarn/timelineservice/hadoop-yarn-server-timelineservice-hbase-common-3.1.1.jar
/opt/hadoop-3.1.1/share/hadoop/yarn/timelineservice/test/hadoop-yarn-server-timelineservice-hbase-tests-3.1.1.jar
/opt/hadoop-3.1.1/share/hadoop/yarn/timelineservice/hadoop-yarn-server-timelineservice-hbase-coprocessor-3.1.1.jar
/opt/hadoop-3.1.1/share/hadoop/yarn/timelineservice/hadoop-yarn-server-timelineservice-hbase-client-3.1.1.jar

A: i find in hadoop-yarn-server-timelineservice-hbase-client-3.1.1.jar


text:
Q: DateFormat in java giving unexpected result I have created a DateFormat object in java
DateFormat formatter = new SimpleDateFormat("yyyy-mm-dd HH:mm:ss");

then created a Date object
Date d = formatter.parse("2015-03-23 11:59:59");

but the value of d that i am getting is "Fri Jan 23 11:59:59 IST 2015", but it should be "Mon Mar 23 11:59:59 IST 2015"
Can somebody please explain why i am getting this result. I have already checked explanation in
Java DateFormat format and parse gives unexpected result but i have specified yyyy in smaller case.

A: Your date format is incorrect.
You should use yyyy-MM-dd HH:mm:ss instead of  yyyy-mm-dd HH:mm:ss.
We use MM for month while mm for minutes in Java simpelDateFormat.
M   Month in year
m   Minute in hour


text:
Q: StringEscapeUtils.escapeHtml/escapeHtml4 inconsistent between commons-lang and commons-lang3 unit test shows StringEscapeUtils.escapeHtml/escapeHtml4 don't produce same results.
trying to upgrade commons-lang(2.6) to commons-lang3(3.9) and found parity-mismatch in escapeHtml/escapeHtml4 methods.
for (String s : Stream.generate(()-> RandomStringUtils.random(100)).limit(100).toArray(String[]::new)) {
    String oldVersion =
        org.apache.commons.lang.StringEscapeUtils.escapeHtml(s);

    String newVersion =
        org.apache.commons.lang3.StringEscapeUtils.escapeHtml4(s);

    Assertions.assertEquals(oldVersion, newVersion);
}

i would have expected the commons-lang3 StringEscapeUtils.escapeHtml4() to produce the same results as commons-lang StringEscapeUtils.escapeHtml().  granted, this test is over the full unicode range but still...
org.opentest4j.AssertionFailedError:
Expected :靂ᬧ뒼뽼㞛⼁寺ǐ弬澳��ﮒᜑ揢䈤ꮚ耳ᣛ泐䪶��늁㠌鋊劂荃❊��단ꂎ櫼㔀䯼絹䲼뎱뽚템☉钆쪄൒䷗㪨��鑺巉Ὄ䱒헓꧿㡕퟼㦰▬䟀⨈ꕓ⇊삗Շ㘵ᐟ蚳��➺컏풎쬴徊풫ᶒ咼芸ᘞ记ᣎἪ꣏陘ґ耚䂊녊ᵙ雜
Actual   :靂ᬧ뒼뽼㞛⼁寺ǐ弬澳ﮒᜑ揢䈤ꮚ耳ᣛ泐䪶늁㠌鋊劂荃❊단ꂎ櫼㔀䯼絹䲼뎱뽚템☉钆쪄൒䷗㪨鑺巉Ὄ䱒헓꧿㡕퟼㦰▬䟀⨈ꕓ⇊삗Շ㘵ᐟ蚳➺컏풎쬴徊풫ᶒ咼芸ᘞ记ᣎἪ꣏陘ґ耚䂊녊ᵙ雜

are these chars not escaped in HTML4 any longer?  doesn't that depend on your encoding?  is there a way to force commons-lang3 to behave like commons-lang in this regard?


text:
Q: openssl md5 in command line and php md5 produce different results Here is the string I am submitting as text file (csr.txt) with command line
https://pastebin.com/qBLJcKQB
openssl command I am passing is:

openssl req -noout -modulus -in csr.txt | openssl md5
e199562f2e9f6a29826745d09faec3a6

Here is the php script version for getting the md5 hash
<?php

$csr = '-----BEGIN CERTIFICATE REQUEST-----
MIIBxzCCATACAQAwgYYxCzAJBgNVBAYTAlVLMQ8wDQYDVQQIDAZMb25kb24xDTAL
BgNVBAcMBEJsYWgxDjAMBgNVBAoMBUJsYWgxMQ4wDAYDVQQLDAVCbGFoMjETMBEG
A1UEAwwKSm9lIEJsb2dnczEiMCAGCSqGSIb3DQEJARYTb3BlbnNzbEBleGFtcGxl
LmNvbTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAsfzWjyj7zlVFlXCaGMH6
Gj3jsWV2tC6rLnRKK4x7hUaI0JriqXUQTNYKTgVhDslR1K0zrJYcaqpmwb4PrUJ/
2RY5si7QvHnndwJ3NOdHFOK8ggn1QqRvFFo4ssPpYWGY63Abj0Df9O6igEHQRQtn
5/9WkkM8evLLmS2ZYf9v6W8CAwEAAaAAMA0GCSqGSIb3DQEBBQUAA4GBADLYvFDq
IfxN81ZkcAIuRJY/aKZRcxSsGWwnuu9yvlAisFSp7xN3IhipnPwU2nfCf71iTe/l
SZifofNpqrnamKP90X/t/mjAgXbg4822Nda1HhbPOMx3zsO1hBieOmTQ9u03OkIZ
hkuQmljK8609PGUGcX5KeGBupZPVWJRf9ly7
-----END CERTIFICATE REQUEST-----';

$csrDetails = openssl_pkey_get_details(openssl_csr_get_public_key($csr));

echo md5($csrDetails['rsa']['n']);
?>

php script produces:

718926bb97aabc0fd1116fa25c295612

I have seen other threads which talk about excluding new line but in my case I am not using echo but rather using openssl. Why PHP's md5 is different from OpenSSL's md5?
Appreciate some assistance.
NOTE: If I drop from the command line "| openssl md5" & in the php script remove md5() then the results are identical

php script produces:
echo strtoupper(bin2hex($csrDetails['rsa']['n']));

B1FCD68F28FBCE554595709A18C1FA1A3DE3B16576B42EAB2E744A2B8C7B854688D09AE2A975104CD60A4E05610EC951D4AD33AC961C6AAA66C1BE0FAD427FD91639B22ED0BC79E777027734E74714E2BC8209F542A46F145A38B2C3E9616198EB701B8F40DFF4EEA28041D0450B67E7FF5692433C7AF2CB992D9961FF6FE96F

A: In the php version you are hashing the binary representation of the modulus, i.e. the binary data 0xB1FCD68F28.... With the command line version you are hashing a printable text string representation of the modulus, i.e. the string "Modulus=B1FCD68F28...". Assuming you are on a machine using an ASCII based character set, this translates to the binary data 0x4D6F64756C... Therefore you are hashing different data in each case and so you are going to get a different result.
Also it looks like openssl is adding a "\n" to the end of the output from the "openssl req ..." command. From php try running md5("Modulus=B1FCD68F28...\n"), i.e. note using " instead of ' and the \n on the end. I tried that and got "e199562f2e9f6a29826745d09faec3a6" - the same as the OpenSSL command line


text:
Q: Is ActivityMapper the right place to block Place requests I want to implement some form of (GWT 2.1 MVP) pre-Activity checking that ensures the user has complied with various things before an Activity can be presented (e.g. logged in, agreed to t&c's, read the description, etc.)  These checks would take the form of Activities also.
Regardless of the specifics, I'm looking to keep my Activity's clean and not implement this checking in each one.  So far, the best place I've seen this is ActivityMapper, where I can perform the checks based on the requested place, and return a different Place than requested.  Perhaps FilteredActivityMapper might be a better way even.
Ideally, I'd like to preserve the originally requested Place, either by not updating history when showing these intermediate (checking) Activities, or caching the original Place object inside the intermediate Place object, and if the user accepts the agreement, then lauching the original Place.
Has anyone done something similar, or has a cleaner approach to this?

A: If you don't insist on having login, t&c and description inside GWT module, and can use jsps for these three things I'd suggest to:
* Create security constraint in web.xml and protect whole GWT module via standard web container features. Each access to unprotected resource will be redirected to login form.
* Use servlet filter to check whether user has agreed to t&c and read description and store information about it in http session.
By the way it'd be quite elegant to use ActivityMapper for second thing, but for login I'd definitely use server-side, proven mechanisms.
Hope it helps.


text:
Q: Python RF Model Evaluation Metrics I have run the random forest model in Python. I need to store the TP,FP,FN and TN data in a dataframe.
    cf_matrix_train = pd.DataFrame([{'Key':0,'TN':0,'FP':0,'FN':0,'TP':0}])

df = pd.DataFrame()

max_f = list(range(1,3))
max_d = list(range(10,12))

for fea in max_f:
    for dep in max_d:
        clf=RandomForestClassifier(random_state=1,n_estimators=100,max_features=fea, max_depth=dep)
        clf.fit(X_train,y_train)
        train_pred = clf.predict(X_train)
        cm_train = confusion_matrix(train_pred,y_train)
        cf_matrix_train['TN'] = cm_train[0][0]
        cf_matrix_train['FP'] = cm_train[1][0]
        cf_matrix_train['FN'] = cm_train[0][1]
        cf_matrix_train['TP'] = cm_train[1][1]
        cf_matrix_train.append(df)
        print(cm_train)

Though all the four model were generated, only the last model output saved to dataframe "cf_matrix_train".
Current Output:
Expected Output

A: The .append() operation in pandas is not done inplace. It returns a new dataframe. So you've to assign it to something. Further, you're doing the opposite.
Replace the line
cf_matrix_train.append(df)

with
df = df.append(cf_matrix_train)

Apart from this, you can also do something like this:
df = pd.DataFrame(columns=['Key', 'TN', 'FP', 'FN', 'TP'])

max_f = list(range(1, 3))
max_d = list(range(10, 12))

index = 0
for fea in max_f:
    for dep in max_d:
        clf = RandomForestClassifier(random_state=1, n_estimators=100,
                                     max_features=fea, max_depth=dep)
        clf.fit(X_train,y_train)
        train_pred = clf.predict(X_train)
        cm_train = confusion_matrix(train_pred, y_train)

        df.loc[index, 'Key'] = f"{fea}, {dep}"
        df.loc[index, 'TN'] = cm_train[0][0]
        df.loc[index, 'FP'] = cm_train[1][0]
        df.loc[index, 'FN'] = cm_train[0][1]
        df.loc[index, 'TP'] = cm_train[1][1]

        index += 1


text:
Q: What is the value of validating JSON? Can we compile a list of reasons to validate JSON? There are a couple aspects I think we should consider:

*

*Security

*Debugging

Are there others?
Also, where should validation happen?

*

*Server

*Client

*Policy Enforcement Points? - does JSON validation make sense on an enterprise firewall? Why?

A: JSON is just a subset of JavaScript, so validating would help to insure that it is only that subset, and that the act of parsing it wouldn't have side effects.  In general I validate on the client if the error is likely the result of user error (like email addresses), and on the server for things that will result in opportunities to hack (like any string that will be presented someone else I make sure to escape it on the server).  I guess I don't put that much stock in the fear that JavaScript might leak into sensitive parts of the system through JSON parsing, I'm not evaluating JavaScript server side when I parse JSON I'm just treating it as a collection of strings and numbers (like a Dicitonary in C#).

A:
Can we compile a list of reasons to validate JSON?

*

*Data validity.

Also, where should validation happen?

*

*Before data usage.


text:
Q: Someone is using my IP address and changing things It looks as if someone is using my IP address, going into one of my work programs and changing things.  How can I research this and see who it is?

A: You probably need to provide us with more details about "what things" are being changed, and how your network is set up - its almost impossible to answer your question based on the scant information you have provided.
Assuming - and its a big assumption - that your work programs are located "in the cloud" - ie not on your premises, and that everyone at work is behind the same connection is presenting the same IP addres it makes it highly likely that the person who is "going in and changing things" is on your network.
I guess you can either change your password to protect yourself or you can start intercepting the traffic and then tracking it down - this would need to be done on your LAN by a system administrator who has access to the router (as well as a router which can support this) - its not something "any end user" can do.
Something "any end user" may be able to do is to get a list of login times and see if you can co-ordinate them with who was at work at each time and narrow things down that way.  It might also help protect you if you can demonstrate it was not you.   If you are very lucky (and your work program is actually a web browser) you may find the service provider can find the browser type which might give you more clues.
Again, absent knowing anything about your network and the work programs in question this is simply wild speculation.   (It is possible that someone could be masquerading as your computer by forcing the IP address on the LAN, but this is more likely to ring alarm bells and prevent your connection from working - it is also a much more sophisticated attack, so you would immediately suspect people with a good knowledge of networking.


text:
Q: Why does passing an unsigned int to performSelector lose bits? I am trying to pass a hex value as an unsigned int to a method using a dynamic link. The value I pass as a parameter is getting corrupted somehow. What is happening?
- (void)callPerformSelector
{
    NSNumber *argument = [NSNumber numberWithUnsignedInt:(unsigned int)0xFFFFFFFF];
    SEL selector = NSSelectorFromString(@"testPerformSelector:");
    NSLog(@"testPerformSelector object %@", argument);
   [self performSelector:selector withObject:argument];
}

- (void)testPerformSelector:(unsigned int) arg1
{
    NSLog(@"testPerformSelector unsigned int %u", arg1);
    NSLog(@"testPerformSelector hex %X", arg1);
}

Output is:
testPerformSelector object 4294967295
testPerformSelector unsigned int 4294967283
testPerformSelector hex FFFFFFF3

A: Because it should be:
- (void)callPerformSelector
{
    NSNumber *argument = @0xFFFFFFFF;
    SEL selector = @selector(testPerformSelector:);
    NSLog(@"testPerformSelector object %@", argument);
   [self performSelector:selector withObject:argument];
}

- (void)testPerformSelector:(NSNumber *) arg1
{
    NSLog(@"testPerformSelector unsigned int %u", arg1.unsignedIntValue);
}

unsigned int and NSNumber * is two different things

A: There's an easy reason and a complex reason.
Simple reason: Why this doesn't work. The first argument to the target of a performSelectorWithObject must be an object. You are specifying a pointer to an unsigned integer in your function signature but then passing an object (NSNumber) when you call it. So instead of:
- (void)testPerformSelector:(unsigned int) arg1

you should have
- (void)testPerformSelector:(NSNumber *) arg1

You will then need to use NSNumber's unsignedIntValue to get the 0xFFFFFFFF out of the object.
The complex reason is much more interesting: Why this nearly works and looks like it loses a few bits. NSNumber is an object that wraps a numeric value this is very different from a raw numeric value. However NSNumber is implemented as a tagged pointer so although objective-c knows it is an object and treats it like an object, a subset of NSNumber values are implemented as tagged pointers where real values are coded into the "pointer" and the fact that this is not a normal pointer is indicated in the (otherwise always zero) bottom four bits of a pointer see Friday Q&A.

A: You can only pass objects to selectors and not primitive types, and therefore the selector should be:
- (void)testPerformSelector:(NSNumber *) arg1
{
    NSLog(@"testPerformSelector hex %x", [arg1 unsignedIntValue]);
}

Update: As pointed-out by @gnasher729, the reason the number passed appears to be -13 is because it's a tagged pointer.


text:
Q: Parsing raw text and extracting object mentions and the 'and', 'or' relation between them given a predefined set of objects I have a predefined list of objects such as
["pop", "pizza", "orange juice", "apple juice", "pasta", "taco", ...]

I'm given a raw text asking for these objects such as
Buy a pizza for me and a pasta for my friend. Also buy me a pop, an orange juice, or an apple juice.

I would like to extract the objects mentioned in the text as well as the 'and', 'or' relationship between them. E.g., for the example above, I need the output to be something like:
[["pizza"], ["pasta"], ["pop", "orange juice", "apple juice"]]

showing the text is asking for pizza, pasta, and at least one object from (pop, orange juice, apple juice). i.e., the text is looking for (pizza AND pasta AND (pop OR orange juice OR apple juice)). There can be several variations in the raw text.
I was looking at parsing and nlp techniques, but could not find anything helpful. I appreciate any help or pointer.

A: I would using a combination of verb-SRL and other annotations:
Here is the output annotations for your input sentences:

As you can see, the things that you want often appear with "A1" label:

*

*A1.thing needed: at least one of these: pop, apple juice, orange juice

*A1.thing bought: a pizza

*A1.thing bought: a pop, an orange juice, or an apple juice

And it misses "pasta". Within "A1" span it's often easy to split into different items, say by splitting on commas.
Note that this also tells you who wants it; for example: A0.neader: I
Btw you can play with the demo yourself here: http://deagol.cs.illinois.edu:8080/
If you want to connect "I" to "me", etc, of course you can use co-reference.


text:
Q: Openwisp -> Failed to connect to controller during registration Well, I'm working with Openwisp and when I tried to register a device (router), I got this error.
Error
This is the configuration on the router
Config
Any idea what I might be doing wrong?

A:
CURLE_PEER_FAILED_VERIFICATION (60)
The remote server's SSL certificate or SSH md5 fingerprint was deemed
  not OK. This error code has been unified with CURLE_SSL_CACERT since
  7.62.0. Its previous value was 51.

If you're in development/testing mode, you can disable SSL verification in openwisp-config by modifying /etc/config/openwisp and setting verify_ssl to 0.
In production you will have to make sure the SSL certificate of the server is valid.


text:
Q: Connecting A Second Site To Current SQL Database Ok - long story short.
Have an e-comm site hosted on Windows VPS using SQL Server 2005, site been up for years and works just fine.
I am now trying to set up a new site hosted on another Windows VPS Server that will share the same database.
Both sites are using classic asp and I have put up a duplicate page to each server that has a simple SQL query to display back a product name on screen.
On the new site I get the 500 error listed below:

GET /testConnection.asp |49|800a0bb9|Arguments_are_of_the_wrong_type__are_out_of_acceptable_range__or_are_in_conflict_with_one_another.

Line 49 in the code is:

rsProdDetail.Open SQL, cnn, adOpenForwardOnly, adLockReadOnly, adCmdText

As I mentioned the page is identical on the 2 servers. The adovbs.inc is there and the path for the file include is correct on the new server.
Where do I look next?

A: Have you tried using
rsProdDetail.Open SQL, cnn, 0, 1, 1

to see if the ADO constants are defined correctly ?


text:
Q: Why throw does not support for Exception class? Why throw does does not support for exception type. As Exception is also a type of throwable class.
try {
    throw new Exception("demo");
} catch (NullPointerException e) {
    System.out.println("Caught inside fun().");
    throw e; // rethrowing the exception
}

A: As for your code:
Exception is NOT NullPointerException.
NullPointerException IS an Exception
Its like with square and rectangle - every square is a rectangle, but not every rectangle is a square.
Your code catches NPE - and that is not what code is throwing.


text:
Q: Closure under Intersection I know that if you have two regular languages $L$ And $M$ then they are closed under intersection, that is the intersection is also regular.
However, if you have two non regular languages L and M, is it possible that their intersection is regular?
I came across a certain example and it seems this is the case but seemed counter intuitive so I wanted to see if that was possible.

A: It is indeed possible. Even if the two languages L and M are complicated it may be the case that their intersection is trivial. In particular if they do not share the same alphabet. For example if L is $a^nb^n$ and $M$ is $c^nd^n$ the intersection is empty (thus regular).


text:
Q: Invalid Module Descriptor Exception Error occurred during initialization of boot layer

java.lang.module.FindException: Unable to derive module descriptor for
  /Users/macbook/eclipse-workspace/softeng5/Resources/rs2xml.jar Caused
  by: java.lang.module.InvalidModuleDescriptorException:
  JDOMAbout$Author.class found in top-level directory (unnamed package
  not allowed in module)

How to solve this exception when trying to run java program?
Also have warning Name of automatic module junit is unstable, it is derived from the module's file name.
and
Name of automatic module rs2xml is unstable, it is derived from the module's file name.


text:
Q: How does points calculation work in Nation Red barricades? For me is not clear how the points calculation works in "Barricades" mode of Nation Red.
I resisted 20 minutes and did 1800 frags, but I got less points than the player that come before me on Steam ladder that resisted 10 minutes and got 1000 frags.

A: There is a difficulty slider you can adjust pre-game which affects the number of points that are awarded per kill. The slider goes from 0% - 100%: The slider level determines the percentage of points that are awarded.
From this thread where the question is noted(albeit mistyped):

Ran 2 games on Barricade warehouse for 5 mins. One at 100% difficulty and the other at 50% (default)
At 100% i scored 21.5 million
At 50% i scored 14.1 million
Both i had auto XP as first perk.

Hope this helps!
EDIT:
Okay, so, again from the Steam forums:

I can probably guess what caused that: the tweaking of the difficulty level and the amount of Xp you get per kill.
When Nation Red was released a lot of
players said it was too easy to
collect perks: The difficulty level
was then increased (apart from new
perks, bosses, weapons, etc. which of
course also affects scoring) so it
became harder to beat existing scores.
Players felt NR became a bit too hard:
the Xp per kill was increased.
So what you're seeing is some scores
achieved with an 'older' version of
the game and some with the current
version.
In the end the game is constantly
evolving with new weapons, perks,
player classes, etc. It's impossible
to keep the scoring perfectly equal
(some new boss may be a bit harder
than others, some new perk may be a
bit too powerful, etc.)
Resetting leaderboards is one fix but
I've tried to resist doing this until
no new perks/bosses/player
classes/weapons, etc. are added.
The next update will be a major one
with 3-4 player coop and the final
player classes. If a leaderboard reset
is needed, that may be the best time.
Having said that, if you want to beat
existing scores:

*

*You get a lot more Xp playing on higher difficulty than lower

*You get more Auto Experience (Perk) on higher than lower difficulty

*On higher difficulty, zombies spawn more often = more Xp.
So beating existing scores is very
possible but maybe try not to
investigate the exact playing times,
etc. when comparing scores.

Hopefully this helps. :)


text:
Q: Has anyone discovered any compatibility issues between ArcGIS 10 clients editing older ArcSDE geodatabases (e.g 9.3.x)? I've read the ESRI documentation here:  http://goo.gl/UUSM (link to ESRI) and http://goo.gl/TsmV  (link to ESRI) , so I know the documentation states that you can.  And I've actually edited data (a very small amount) in a 9.3 ArcSDE with no problems.
For those who are actually producing & maintaining on their versioned 9.3 geodatabases with ArcGIS 10 clients, have you experienced any issues?   Or has it been a relatively smooth experience (i.e works as advertised)?

A: I agree, I've used ArcMap and ArcGis Server 10 for various editing tasks with no real problems on sde9.3. Obvioulsy the new v10 features are not available in sde9.3, but otherwise it's been very solid.

A: ArcGIS 10 applications are all compatible with down-level versions of SDE (SDE 9.2 and higher as your links also indicate). Your only limitation should be the lack of options that require features only supported in the geodatabase at 10 such as e.g. feature attachments. If any problems were to be encountered, and I haven't heard of any, I'd log a bug with Esri tech support.
(disclaimer: although I am an Esri employee this is my personal experience and no guarantees are implied)

A: We have an issue editing with ArcMap 10 to a 9.3.1 Oracle SDE database.  The issue is when the dataframe is in a different coordinate system than the feature layer being edited (which I know this is a big no, no... but never had this issue with 9.3).  It doesn't seem to project the data when inserting into the database.  Then the domain of the feature class gets all messed up... I submitted this to ESRI, never really heard anything much.


text:
Q: Displaying on different times This is for my timer
     private void timer_tick(object sender, EventArgs e)
    {
        string timeNow = "";

        timeNow = DateTime.Now.ToString("hh:mm") + " " + DateTime.Now.ToString("tt");
       medicineAlarm();
    }
    private void medicineAlarm()
    {
        DataTable dt = new DataTable();
        dt = database.getSchedule();

        string AMTime;
        string PMTime;
        string NNTime;
        foreach (DataRow row in dt.Rows)
        {
            AMTime = row["AMIntake"].ToString();
            PMTime = row["PMIntake"].ToString();
            NNTime = row["NNIntake"].ToString();

             if (AMTime == timeNow || PMTime == timeNow || NNTime == timeNow)
            {
                MessageBox.Show("Drink Medicine");
            }
        }
    }

How can i show the message even if i am running the program? Hope you can help me. This is inside my form_load
    private void Form1_Load(object sender, EventArgs e)
    {
        timer.Interval = 1000;
        timer.Tick += new EventHandler(this.timer_tick);
        timer.Start();

A: I don't think your code compiles at all since the variable string timeNow = ""; is declared in event handler and doesn't exists in your method body. You may want to pass it to the method like
private void medicineAlarm(string timeNow)
{

You then call it
 private void timer_tick(object sender, EventArgs e)
{
    string timeNow = "";

    timeNow = DateTime.Now.ToString("hh:mm") + " " + DateTime.Now.ToString("tt");
   medicineAlarm(timeNow);
}

A: The medicineAlarm() method does not have any access to the timeNowvariable that you are setting up in the timer_tick() event handler. I suggest you pass the variable in:
private void timer_tick(object sender, EventArgs e)
{
    string timeNow = DateTime.Now.ToString("hh:mm") + " " + DateTime.Now.ToString("tt");
   medicineAlarm(timeNow);
}

private void medicineAlarm(string timeNow)
{
    DataTable dt = database.getSchedule();

    foreach (DataRow row in dt.Rows)
    {
        foreach(var label in new [] {"AM", "PM", "NN"})
            if (row[label + "Intake"].ToString() == timeNow)
                {
                   MessageBox.Show("Drink Medicine");
                   return;
                }
    }
}


text:
Q: In rails 3, how do I use page.call to call a function and pass it multiple parameters? I'm using page.call to call a function in my rails application that is using jquery-ujs. Right now I have it working fine with one parameter being passed:
page.call "functionName", "div_name"

to call
functionName(div_name)
{
}

but I'd like to pass two parameters to this function:
functionName(div_name, other_variable)
{
}

How can I do this using page.call?
Thanks so much.

A: Have you tried simply adding another argument to the call? It looks like page.call() uses varargs for the arguments.
You should simply be able to do
page.call 'functionName', 'arg1', 'arg2'


text:
Q: Windows Forms application lots of ambiguous symbols Creating a c++ forms application, I have started getting some ambiguous symbol errors. But I am not quite sure what from, it was compiling fine earlier but I may have changed something?
Thee error itself:
1>Application.cpp
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(4089): error C2872: 'IDropTarget': ambiguous symbol
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\oleidl.h(3508): note: could be 'IDropTarget'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(4089): note: or       'System::Windows::Forms::IDropTarget'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(6496): error C2872: 'IServiceProvider': ambiguous symbol
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\servprov.h(98): note: could be 'IServiceProvider'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(6496): note: or       'System::IServiceProvider'
1>main.cpp
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(4089): error C2872: 'IDropTarget': ambiguous symbol
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\oleidl.h(3508): note: could be 'IDropTarget'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(4089): note: or       'System::Windows::Forms::IDropTarget'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(6496): error C2872: 'IServiceProvider': ambiguous symbol
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\servprov.h(98): note: could be 'IServiceProvider'
1>c:\program files (x86)\windows kits\10\include\10.0.15063.0\um\ocidl.h(6496): note: or       'System::IServiceProvider'

I found this strange because my form isn't contained with any of these files, I assume it's that due to the namespacing. I just don't know where this is actually coming from.
Here is my form for info:
#include <Windows.h>

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

public ref class CFormController : public Form
{
public:
    CFormController(void)
    {
        InitializeComponent();
    }
    ~CFormController()
    {
        delete components;
    }

    System::ComponentModel::Container ^components;

    void InitializeComponent(void)
    {
        this->components = gcnew System::ComponentModel::Container();
        this->Size = System::Drawing::Size(300, 300);
        this->Text = L"FormController";
        this->Padding = System::Windows::Forms::Padding(0);
        this->AutoScaleMode = System::Windows::Forms::AutoScaleMode::Font;
    }
};

The only other information about my form is in another class. Thats only used to display or hide it.
I found similar issues in that people didn't include the windows header before "using namespace..." but I added the include as you saw and it didn't make a difference whatsoever

A: You are importing conflicting symbols into the global namespace.
The code you posted should fine if it is the first file included in the compile unit. If that is not the case (e.g. you included another header file before the header file you posted) they you could have the WinForms types already present in the global namespace when you include windows.h, and causes C2872.
You can move the using statements or windows.h include into a namespace to avoid the conflict.
e.g.
namespace Win32 {
#include "windows.h"
}

or
namespace ProjectName {

using namespace System;
......
}

Or if you really want to import the types into the global namespace, separate your code into two cpp files and import them one at a time.

A: C++/CLI is notorious for symbol conflicts, whenever you are "using" many C# namespaces. Obviously, you have a conflict between System and System::Windows::Forms. Try to remove the latter "using" declaration, and specify symbols from this namespace by prefixing them with System::Windows::Forms::. I know this is a royal pain, but as far as I know there's no other workaround.
I face this problem regularly whenever I need classes from System::Collections::Generic.


text:
Q: Is there a generalized way to tell when a function has two or more solutions? I am trying to define "when" a function loses its property of being a function when it is inverted, but the only sure way I know of is simply by inspection that graphically, the inverse function looks like it fails the vertical line test. But what is a more formal way to deduce that a function has at least two possible outputs for a given input?

A: The only way to do that is to solve $f(x)=c$ for the specific given constant $c$. There is no real way to see that at first glance (maybe for specific examples you recognize like $f(x)=\frac1x$), because "function" is a far too broad term.
There is a term however, "injective", that signifies a related property; every element in the codomain of an injective function can only be mapped to by at most one element in the domain.

A: Note that a function is invertible if and only if

*

*it is injective

*and it is surjective

that is if and only if $f$ is bijective.

A: For differentiable functions defined on an interval, if at some point of the interval the derivative changes sign from positive to negative or from negative to positive, then your function is not one-to-one.
For example $f(x)=x^2$ is differentiable and its derivative $f'(x)=2x$, changes sign from negative to positive at $x=0$.
So it is not one to one as we can see that  from $f(-1)=f(1)=1$.


text:
Q: Как вырезать поддомен с строки? Пример строки:
S:/domains/account.site.com

S:/domains/support.site.com

S:/domains/company.site.com

S:/domains/forum.site.com

Вопрос:
Как вырезать с строки поддомен не зная его, вместе с точкой?

A: $string = '
    S:/domains/account.site.com
    S:/domains/support.site.com
    S:/domains/company.site.com
    S:/domains/forum.site.com
';

echo preg_replace('/S:\/domains\/\K[^\.]+\.(?=site\.com)/', '', $string);

https://3v4l.org/ZoeJZ
https://regex101.com/r/qB6cOy/1


text:
Q: unable to get value from  I have multiple <input class="form-control inputDate" type="text" value="12/31/1899 7:00 PM"> on a page. I also have the following javascript,
var inputs = jQuery('.inputDate');
for (var i = 0; i < inputs.length; i++) {
  console.log("test");
  jQuery(inputs[i]).val().split('/')[2];
  var input = jQuery(inputs[i]).val().split('/')[2];
  console.log("TEST" + input);
  if (input.length > 4) {
    input = input.split(" ")[0];
  }
  if (input < '2015') {
    jQuery(inputs[i]).val("");
  }
}

The problem is that var input does not have a value. I have tried opening up the console and testing (against the html from above) and nothing is getting the value.
I have tried,
jQuery(inputs[i]).val();
jQuery(inputs[0]).val();
document.getElementsByClassName("inputDate")[0].value;

But nothing returns the value. I think part of the issue is that the value is set in the backend to 1899 instead of starting off null.
How can I get the value?
EDIT-------------------------------------
I have done more testing and when I do
var test = inputs[0];
jQuery(test).val("123")

The HTML markup still shows the date. But if I do (from IntheWeeds)
jQuery(".inputDate").each(function() {
   console.log($(this).val());
});

it returns 123 and "" even though the value in the HTML markup is still a date.

A: You are not accessing the value attribute there. try
 var test = inputs[i];
 jQuery(test).val();

or use .each method:
var inputs = jQuery('.inputDate');
jQuery(inputs).each(
  jQuery(this).val().split('/')[2];
  // rest of the code don't forget to get rid of ending '}'

A: I definitely would recommend using "each", as noob described in his updated answer. Here is a simplified example showing how to log each textbox value:
$(".inputDate").each(function() {
   console.log($(this).val());
});

A: Try this:
var inputs = $('.inputDate').val();

// Expect: input = "12/31/1899 7:00 PM"


text:
Q: Discrete Maths: Ways of sitting 3 exams during a 13 week semester. I had a discrete maths test today and this question was the last one and it really threw me off.

During a 13 week semester ( no breaks in between ), a student must sit 3 exams >for a particular course.
  However, he must sit them in order, i.e 1st -> 2nd -> 3rd. In other words, you must first sit the 1st exam, then the 2nd then the 3rd. so can't sit the second exam without having sat the 1st one, etc..
If he can only sit one exam per week, in how many ways can the student sit the exams.

I tried during inclusion/exclusion principle but it got messy real quick. I also thought of doing the lines and dots method but figured it's wrong since the dots are not identical.
I'm just curious how to do this.
the second part of the question was

Suppose they are not allowed to sit two exams in consecutive weeks, now in how >many ways can the student sit the exams.

I didn't even attempt the second part as I did not have time.
Any help would be greatly appreciated.

A: (Edited the answer to fit all criterias.)
Choose the 3 weeks out of 13 on which the student writes the exam. On the first chosen week the first exam, the second chosen week the second exam, third week the third.
There is a known mathematical formula for choosing $k$ instances from $n$, which is calculated by
$${n\choose k} = \frac{n!}{k!(n-k)!}$$
Note that this already fits the criteria of writing the exams in order. It just selects $3$ weeks out of $13$, and on the $n^{th}$ selected week ($n \in \{1,2,3\}$) you write the $n^{th}$ exam.
In this case:
$${13\choose 3} = \frac{13!}{3!(13-3)!} = 268$$
However, if you need to have at least $1$ week off before you write the next exam, you really only have $11$ objects to order (instead of $13$):

*

*(First exam's week + a week off)

*(Second exam's week + a week off)

*(Third exam's week)

*(Other exam free weeks)$\times 8$

You need to choose $3$ places out of $11$ to fit these weeks (or double weeks) into the semester, so the answer is:
$${11\choose 3} = \frac{11!}{3!(11-3)!} = 165.$$

A:
During a $13$-week semester, a student must sit $3$ exams for a particular course.  However, he must sit them in order (the first exam must precede the second and the second must precede the third).  If he can only sit one exam per week, in how many ways can he sit the exams?

Method 1:  Since he must sit the exams in order, his examination schedule is completely determined by choosing during which three of the thirteen weeks he schedules an exam.  Hence, there are
$$\binom{13}{3}$$
ways for the student to schedule his exams.
Method 2:  This method is less efficient, but I am adding it to address the questions raised in the comments.
Suppose the student takes the $k$th examination in week $a_k$.  Define
\begin{align*}
x_1 & = a_1\\
x_2 & = a_2 - a_1\\
x_3 & = a_3 - a_2\\
x_4 & = 13 - x_3
\end{align*}
Then
$$x_1 + x_2 + x_3 + x_4 = 13 \tag{1}$$
Observe that $x_1$ is a positive integer.  Since the student cannot sit two examinations in the same week and the exams must be sat in order $x_2$ and $x_3$ are also positive integers.  Since the student can sit an examination in the last week, $x_4$ is a nonnegative integer.
We can transform equation 1 into an equation in the positive integers by setting $x_4' = x_4 + 1$.  Substituting $x_4' - 1$ for $x_4$ in equation 1 yields
\begin{align*}
x_1 + x_2 + x_3 + x_4' - 1 & = 13\\
x_1 + x_2 + x_3 + x_4' & = 14 \tag{2}
\end{align*}
Equation 2 is an equation in the positive integers that is equivalent to equation 1.  A particular solution of equation 2 corresponds to the placement of three addition signs in the $13$ spaces between successive ones in a row of $14$ ones.
$$1 \square 1 \square 1 \square 1 \square 1 \square 1 \square 1 \square 1\square 1 \square 1 \square 1 \square 1 \square 1 \square 1$$
For instance, choosing the third, seventh, and thirteenth spaces yields
$$1 1 1 + 1 1 1 1 + 1 1 1 1 1 1 + 1$$
which corresponds to the solution $x_1 = 3$, $x_2 = 4$, $x_3 = 6$, $x_4' = 1$ ($x_4 = 0$) or $a_1 = 3$, $a_2 = 7$, $a_3 = 13$.  The number of such solutions is the number of ways we can select three of the thirteen spaces between successive ones in a row of fourteen ones in which to place an addition sign, which is
$$\binom{13}{3}$$

Suppose a student cannot sit an exam in consecutive weeks.  In how many ways can the student sit the exams?

We arrange ten blue balls and three green balls so that no two of the green balls are consecutive.
Line up ten blue balls in a row.  This creates eleven spaces, nine between successive blue balls and two at the ends of the row.
$$\square \color{blue}{\bullet} \square \color{blue}{\bullet} \square \color{blue}{\bullet} \square \color{blue}{\bullet} \square \color{blue}{\bullet} \square \color{blue}{\bullet} \square \color{blue}{\bullet} \square \color{blue}{\bullet} \square \color{blue}{\bullet} \square \color{blue}{\bullet} \square$$
To ensure that the three green balls are separated, choose three of these eleven spaces for the green balls.  For instance, if we choose the third, sixth, and eleventh spaces, we obtain
$$\color{blue}{\bullet} \color{blue}{\bullet} \color{green}{\bullet} \color{blue}{\bullet} \color{blue}{\bullet} \color{blue}{\bullet} \color{green}{\bullet} \color{blue}{\bullet} \color{blue}{\bullet} \color{blue}{\bullet} \color{blue}{\bullet} \color{blue}{\bullet} \color{green}{\bullet}$$
Now number the balls from left to right.  The numbers on the green balls are the examination weeks.  In this case, they are $a_1 = 3$, $a_2 = 7$, and $a_3 = 13$.  The number of such solutions is the number of ways we can select three of these eleven spaces in which to insert a green ball. Hence, there are
$$\binom{11}{3}$$
ways to schedule the exams so that the student does not sit exams in consecutive weeks.


text:
Q: How to get average for specific list elements I have the following part input file (has over 500 lines):
L1, a, b, 10, 20, pass,
L1, c, d, 11, 21, pass,
L1, e, f, 12, 22, pass,
L1, a, b, 13, 23, pass,
L1, e, f, 14, 34, pass,

I would like to get the average's of the duplicates i.e. the output as follows:
(where for L1, a, b, 11.5 = (10+13)/2, 21.5 = (20+23)/2)
L1, a, b, 11.5, 21.5
L1, c, d, 11, 21
L1, e, f, 13, 28

My current beginner python code is as follows- still working to tweak it better
 import csv
 from collections import defaultdict
 import numpy as np

 dd = defaultdict(list)
 with open("mean.csv") as input_file:
 for row in csv.reader(input_file):
            dd[tuple(row[:3])].append(float(row[3]))
            dd[tuple(row[:3])].append(float(row[4]))

 for k, v, m in dd.iteritems():
      if len(v) > 1:
           print (' '.join(k), np.mean(v), np.mean(m))

The error I get is:
   Traceback (most recent call last):
   File "average.py", line 11, in <module>
      for k, v, m in dd.iteritems():
   ValueError: need more than 2 values to unpack

A: Untested, but something like this as base can be adapted for the other column... as this just does one at the moment.
import csv
from collections import defaultdict
import numpy as np

dd = defaultdict(list)
with open('in.csv') as fin:
    for row in csv.reader(fin):
        dd[tuple(row[:3])].append(float(row[3]))

for k, v in dd.iteritems():
    if len(v) > 1:
        print ' '.join(k), np.mean(v)

A: With pandas this would be very short (and it should be fast).
You can do something like this (don't know the meaning or naming of your columns, so it depends what you want to use as the index of your DataFrame):
In [1]: df = pd.read_csv('mean.csv', delimiter=',', header=None)

In [2]: df
Out[2]:
  X.1 X.2 X.3  X.4  X.5
0  L1   a   b   10   20
1  L1   c   d   11   21
2  L1   e   f   12   22
3  L1   a   b   13   23
4  L1   e   f   14   34

In [3]: df.groupby(['X.1', 'X.2', 'X.3']).mean()
Out[3]:
              X.4   X.5
X.1 X.2 X.3
L1   a   b   11.5  21.5
     c   d   11.0  21.0
     e   f   13.0  28.0


text:
Q: Python dict with duplicated keys or None I have a class in python where I have a dict containing neighbors, and a list pri_list containing 21 instances of the class, but if I iterate over the neighbor,  I get duplicated keys or None.
print type(self.neighbors)
print str(self.id) + " " + str(self.neighbors)
print ""
for n in self.neighbors:
    print str(pri_list[n].id) + " " + str(pri_list[n].neighbors)
    pri_list[n].neighbors.update({self.id:self.neighbors[n]})
    print str(pri_list[n].id) + " " + str(pri_list[n].neighbors)

resulting in
<type 'dict'>
21 {22: 34.348765355132869, 23: 0, 19: 0.049076419727497315, 20: 36.087031068160286}

22 {21: 34.348765355132869, 23: 34.602568871995345, 8: 0.2351466696454737, 17: 0, 20: 0}
22 {21: 34.348765355132869, 23: 34.602568871995345, 8: 0.2351466696454737, 17: 0, 20: 0}
23 {21: 0, 22: 34.602568871995345, 8: 26.643673903936367, 17: 36.80385613689073}
23 {21: 0, 21: 0, 22: 34.602568871995345, 8: 26.643673903936367, 17: 36.80385613689073}
19 {21: 0.049076419727497315, 14: 0, 18: 41.407044987390677, 20: 39.517515427920443}
19 {21: 0.049076419727497315, 14: 0, 18: 41.407044987390677, 20: 39.517515427920443}
20 {21: 36.087031068160286, 22: 0, 18: 0.58414114578772669, 19: 39.517515427920443}
20 {21: 36.087031068160286, 22: 0, 18: 0.58414114578772669, 19: 39.517515427920443}

Observe how the key 21 occur twice in the id=23 dict after doing a update.
I have tried
pri_list[n].neighbors[self.id] = self.neighbors[n]

Giving the same result.
I Have tried it on two different machines which gave the same result.
I made a test example where I copied the data from the dict over as.
class A:
    neighbors = {}
    id = 0

    def __init__(self,id, neighbors):
        self.id = id
        self.neighbors = neighbors.copy()

if __name__ == "__main__":
    pri_list = [A(i, {})for i in range(0, 19)]

    pri_list.append(A(19, {21: 0.049076419727497315, 14: 0, 18: 41.407044987390677, 20: 39.517515427920443}))
    pri_list.append(A(20, {21: 36.087031068160286, 22: 0, 18: 0.58414114578772669, 19: 39.517515427920443}))
    pri_list.append(A(21, {22: 34.348765355132869, 23: 0, 19: 0.049076419727497315, 20: 36.087031068160286}))
    pri_list.append(A(22, {21: 34.348765355132869, 23: 34.602568871995345, 8: 0.2351466696454737, 17: 0, 20: 0}))
    pri_list.append(A(23, {21: 0, 22: 34.602568871995345, 8: 26.643673903936367, 17: 36.80385613689073}))

    print type(pri_list[21].neighbors)
    print str(pri_list[21].id) + " " + str(pri_list[21].neighbors)
    print ""

    for n in pri_list[21].neighbors:
        print str(pri_list[n].id) + " " + str(pri_list[n].neighbors)
        pri_list[n].neighbors.update({pri_list[21].id:pri_list[21].neighbors[n]})
        print str(pri_list[n].id) + " " + str(pri_list[n].neighbors)

This gave the expected result
<type 'dict'>
21 {22: 34.348765355132869, 23: 0, 19: 0.049076419727497315, 20:     36.087031068160286}

22 {8: 0.2351466696454737, 17: 0, 20: 0, 21: 34.348765355132869, 23: 34.602568871995345}
22 {8: 0.2351466696454737, 17: 0, 20: 0, 21: 34.348765355132869, 23: 34.602568871995345}
23 {21: 0, 22: 34.602568871995345, 8: 26.643673903936367, 17: 36.80385613689073}
23 {21: 0, 22: 34.602568871995345, 8: 26.643673903936367, 17: 36.80385613689073}
19 {21: 0.049076419727497315, 14: 0, 18: 41.407044987390677, 20: 39.517515427920443}
19 {21: 0.049076419727497315, 14: 0, 18: 41.407044987390677, 20: 39.517515427920443}
20 {21: 36.087031068160286, 22: 0, 18: 0.58414114578772669, 19: 39.517515427920443}
20 {21: 36.087031068160286, 22: 0, 18: 0.58414114578772669, 19: 39.517515427920443}

Observe how the key 21 occur only once in the id=23 dict after doing an update, and the arrangement of the dict is also different.
I'm having a hard time even grasping how multiple keys can occur in the same dict, according to https://docs.python.org/2/library/stdtypes.html#dict this should not be possible

A: The problem with the code you provided is that you update the dictionary while iterating through it. I am not 100% sure that this is the cause, but generally it is a bad idea and it does lead to unpredictable results. Just make a copy to iterate through.


text:
Q: Two divs within another div overlap I asked a similar question already but haven't found an answer. I am now at a different section of my website but have the the issue here as well. The code is super basic, so I am hoping this will help to solve the issue.
Some context: My front page is sectioned in 3 container divs, each of them with 100vh, so they should take up the entire screen, even when someone resizes the browser. The second div in the code below (.showcase) should stick to the bottom of the Container div (that's why I added position: absolute and bottom: 0).
My issue is now that the two divs in the Container div 1, keep overlapping when I reduce the browser height for example. But I want them to 'push' each other away from each other, basically not giving space for the other div to overlap. So that when I, for example, would add a padding to the two divs, that the padding still shows on the page even if resizing the browser. And no matter what I added (display: block, Flexbox, even putting the divs into a table etc) all of this didn't help and the content of the two divs keeps overlapping.
Can anyone help me here? I literally don't know how to go from here...
Here is the code:

.Container1 {
  overflow: hidden;
  height: 100vh;
  width: 100%;
  margin: 0;
  background: rgb(74, 105, 113);
  background: linear-gradient(90deg, rgba(74, 105, 113, 1) 0%, rgba(129, 161, 170, 1) 60%, rgba(181, 207, 214, 1) 100%);
  text-align: center;
  display: block;
}

.hp_slogan {
  padding-top: 20%;
  padding-bottom: 3%;
}

.showcase {
  position: absolute;
  bottom: 0;
  display: block;
}

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

A: I believe this will solve your problem If I understood correctly what you need.
.Container1 {
  overflow:hidden;
  height: 100vh;
  width: 100%;
  margin: 0;
  background: rgb(74,105,113);
  background: linear-gradient(90deg, rgba(74,105,113,1) 0%, rgba(129,161,170,1) 60%, rgba(181,207,214,1) 100%);
  text-align: center;
  display: flex;
  flex-direction:column;
}

.hp_slogan {
  padding-top: 20%;
  margin-bottom:20px;
  padding-bottom: 3%;
}

.showcase {
  bottom: 0;
}

You can simulate it in JSFiddle with this link

A: See if this works for you. Used flexbox to distance two divs

.Container1 {
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  overflow: hidden;
  height: 100vh;
  width: 100%;
  margin: 0;
  background: rgb(74, 105, 113);
  background: linear-gradient(90deg, rgba(74, 105, 113, 1) 0%, rgba(129, 161, 170, 1) 60%, rgba(181, 207, 214, 1) 100%);
  text-align: center;
}

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.

    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
    in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.


text:
Q: kafka streams total word count in a message https://kafka.apache.org/10/documentation/streams/quickstart
I had a question on counting words within a message using kafka streams. Essentially, I'd like to count the total number of words, rather than count each instance of a word.
So, instead of
all     1
streams 1
lead    1
to      1
kafka   1

I need
totalWordCount   5

or something similar.
I tried a variety of things to this part of the code :
KTable<String, Long> wordCounts = textLines
    .flatMapValues(value -> Arrays.asList(value.toLowerCase().split("\\W+")))
    .groupBy((key, value) -> value)
    .count();

such as adding .selectKey((key, value) -> "totalWordCount") in an attempt to change each key (all, streams, etc) to totalWordCount thinking it'll increment itself
I've also tried to edit my code using this to try and achieve the total word count.
I have not succeeded, and after doing some more reading, now I am thinking that I have been approaching this incorrectly. It seems as if what I need to do is have 3 topics (I've been working with only 2) and have 2 producers where the last producer somehow takes data from the first producer (that shows the word count of each instance) and basically add up the numbers in order to output the total number of words, but I'm not entirely sure how to approach it. Any help/guidance is greatly appreciated. Thanks.

A: Where did you put the selectKey()? The idea is basically correct, but note, that groupBy() does set the key, too.
KTable<String, Long> wordCounts = textLines
    .flatMapValues(value -> Arrays.asList(value.toLowerCase().split("\\W+")))
    .groupBy((key, value) -> "totalWordCount")
    .count();

or (using groupByKey() to not change the key before the aggregation)
KTable<String, Long> wordCounts = textLines
    .selectKey((key, value) -> "totalWordCount")
    .flatMapValues(value -> Arrays.asList(value.toLowerCase().split("\\W+")))
    .groupByKey()
    .count();

A: @Configuration
@EnableKafkaStreams
public class FirstStreamApp {

@Bean
public KStream<String,String> process(StreamsBuilder builder){
    KStream<String,String> inputStream = builder.stream("streamIn", Consumed.with(Serdes.String(),Serdes.String()));
    KStream<String,String> upperCaseStream = inputStream.mapValues(value->value.toUpperCase());
   upperCaseStream.to("outTopic", Produced.with(Serdes.String(),Serdes.String()));

    KTable<String, Long> wordCounts = upperCaseStream.flatMapValues(v-> Arrays.asList(v.split(" "))).selectKey((k, v) -> v).groupByKey().
           count(Materialized.<String, Long, KeyValueStore<Bytes, byte[]>>as("counts-store"));
    wordCounts.toStream().to("wordCountTopic", Produced.with(Serdes.String(),Serdes.Long()));

    return upperCaseStream;
}

}


text:
Q: Error STDERR: : is outside repository I have created a file(my_f) and a directory(my_dir) under my local repo using my python script (my script, my_f and my_dir are all under the same path in my repo).
I moved my_f into my_dir inside my script and as the final step I want to add this file to my tracking file list, make a commit and push it to remote repo. When I run sh.git('add', /absolute/path/to/my_dir/my_f) I get this error:
STDERR:
fatal: /absolute/path/to/my_dir/my_f: 'absolute/path/to/my_dir/my_f' is outside repository
/absolute/path/to/my_dir/my_f: This is the absolute path to my file and its type is Posixpath.
I have also converted this path to script and tried in in sh.git('add', '/absolute/path/to/my_dir/my_f') but I get the same error.
If I manually add the file to repo in my terminal using git add command I have no problem! Does anyone have an idea what I am doing wrong?
Thanks in advance for your help.


text:
Q: Help in understanding frequency vs phase difference graph The following graph in my textbook plots the relationship of external driving frequency and phase difference of the driver and a system. From this question (Why dosn't amplitude increase when drive frequency is above resonance?) I understand that the amplitude  is maximum at the natural frequency because the system and driving force are in phase. Therefore phase difference is $0$ at $f_0$. Why does this change for when damping comes into the picture. In other words, why isnt $0=f_0$ for higher damping?

A:
I understand that the amplitude is maximum at the natural frequency
  because the system and driving force are in phase.

That statement is wrong.
Undamped systems a special case, and are different from damped systems because there is no work required to maintain a constant amplitude over time.
For a damped system, the maximum amplitude occurs when the driving force can do the maximum work on the system, and that is when the phase difference between force and displacements is 90 degrees. If the force was in phase with the displacement, the force would do positive work as the force and displacement both increase, but then do equal and opposite negative work as the displacement returned to zero, so the net work over a whole cycle would be zero.
In fact the general solution for an undamped system excited at is resonant frequency also has the displacement out of phase with the force, and the displacement amplitude increases linearly over time  (i.e. the displacement is something like $x = x_0 t \sin \omega t$). To maintain a constant amplitude at the resonant frequency, the applied force must be zero, and therefore "the phase angle between the force and displacement" is undefined.
For any other excitation frequency, the force and displacement in an undamped system are exactly in phase below the natural frequency and out of phase (phase angle $\pi$) above it.


text:
Q: PowerApps Patch Function for Bulk Updates I have the following Text Fields that are being both updated and created as new, e.g. someone will come in and create a new record from blanks OR update existing records based on a gallery selection beforehand.
Is there a way to bulk update/create the backend SharePoint List with the updated values without writing a super long patch function? My SharePoint List is called Scores and there are 36 columns created to receive this data.

A: Somehow you have to get each field in your app into a column in the data source. You've got to map that relationship.
An alternative to a gnarly Patch() is:

*

*OnStart of the app, OnVisible of the screen or OnSelect of an item in a gallery, create a collection of the record(s) to be edited.

*

*Something like:

ClearCollect(colSomething,
    Filter(myDataSource, status = new)
)

*Then, OnChange of each text input box:

UpdateIf(colSomething, 1=1,
    {
        specificColumn1: thisTextBox.Text
    }
)

*

*This inserts the value of the Text Box into the Collection.

*Finally, to push this all to the Data Source, you can just write:

Patch(myDataSource,
    Defaults(myDataSource),
    colSomething
)

...if its a new record or
Patch(myDataSource,
    Filter(myDataSource, ID = varID),
    colSomething
)

You need the schema (column names and data types) of the Collection to exactly match that of the Data Source for this to work. Its a nice way to handle data within your app.
Good luck!


text:
Q: Randomize path in JMeter REST API load testing So I have a REST API that I want to test with JMeter.
I have few different paths in the REST Service.
If we take an example of simple REST service that will calculate based on two values passed in request, I have four different paths
/add
/sub
/mul
/div
Now I want to test this with a 5000 requests but want to randomize the path and the values in request parameters in each request. Also if possible, want to get the results in 4 categories separately for each path.
Can someone please suggest the right combination of elements?
I am very new to JMeter and hence, expect a little elaborated answer. :)

A: The fastest and the easiest way is using __chooseRandom() function available via JMeter Plugins. The relevant configuration of the HTTP Request Sampler would be:

*

*Path: /${__chooseRandom(add,sub,mul,div,path)} - get a random option and store it into ${path} JMeter Variable

*Name: ${path} - change HTTP Request Sampler Label (for separate reporting)

You can install __chooseRandom() and other plugins Functions via JMeter Plugins Manager from the "Available Plugins" tab:

Be aware that your requests will be random hence your test scenario won't be repeatable so I would recommend considering using other test elements instead i.e. Throughput Controller or Switch Controller or Weighted Switch Controller.
See Running JMeter Samplers with Defined Percentage Probability article for above test elements configuration details.


text:
Q: Trying to save an array of objects to Firestore and load it back How do I save an array of objects to Firestore and load it back? I get this error

Uncaught FirebaseError: Function DocumentReference.set() called with
invalid data. Unsupported field value: a custom object (found in
document userBooks/library)

This is my code to save it to Firebase and to load it later on after modifications have been done to myLibrary array.
let myLibrary = [];
let firestore = firebase.firestore();

let docRef = firestore.doc("userBooks/library");
saveLibrary = function () {
  docRef
    .set({
      userLibrary: myLibrary,
    })
    .then(function () {
      console.log("Library saved!");
    })
    .catch(function (error) {
      console.log("Got an error: ", error);
    });
};
saveLibrary()
getUpdate = function () {
  docRef.onSnapshot(function (doc) {
    if (doc && doc.exists) {
      const myData = doc.data();
      myLibrary = myData.userLibrary;
      console.log(myData.userLibrary);
    }
  });
};

// Here I add multiple objects to the array myLibrary.

saveLibrary();
getUpdate();

A: It looks like you're trying to store an empty array inside the document, then start to listen to updates?
I wouldn't store the empty array until it has data inside it, or store it with boilerplate data.
In your code, you're calling " saveLibrary() " before adding objects to it. I think that's what's causing the issue.
I would also encourage you to use {merge:true} within your .set() functions, so you don't overwrite your documents. ref here


text:
Q: The relation between the spectral theorem and unitary diagonalization There is a few thing that is not clear for me about those subjects that I would like for an explanation.
The spectral theorem:
according to my understanding, it says that if I have an operator $T$ or matrix $A$ in finite dimension space, we knot that $T$ is normal $\iff$ I have orthonormal basis to $V$ of eigenvectors of T.
my questions:
$1.$ that orthonormal basis is orthonormal with respect to the standard inner product space? or it can be true for any product space?
$2.$ if the answer for 1 is for any inner product space, what guarntee me that I have unitary $P$ matrix that I can apply the unitary diagonalization?

A: Saying that $T$ is normal means that $TT^*=T^*T$. You should keep in mind that $T^*$ is determined from the equation $\langle T\vec{v},\vec{u}\rangle=\langle \vec{v},T^*\vec{u}\rangle$, which means that for different inner products you will get different $T^*$'s.
So the spectral theorem works in general, and does not require any specific inner product. The "secret" is that the contidion "T is normal" is the condition that makes it work for whatever inner product you choose.
This should also answer the second question since $P$ being unitary means that $P^*=P^{-1}$ which also depends on the inner product endowed on your vector space.


text:
Q: Spring Boot Programmatically setting profiles How to set active profile in spring boot Application. This application will be deployed in stand alone Tomcat.
I have 2 property files application-{profile}.properties.
My Application class
    @SpringBootApplication
        public class Application extends SpringBootServletInitializer {

            @Override
            protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
                return application.sources(Application.class);
            }

            public static void main(String[] args) {
               System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
 ApplicationContext ctx = SpringApplication.run(Application.class, args);
      }
    }

if I run the app with embedded tomcat the dev profile is  set as active and it works fine. But when I deploy in stand alone tomcat. It does not work.
I tried to set active profile in configure method. but i get null pointer exception, when i get the environment from the context.
Any help on how to set the active profile.

A: Instead of activating the profile dynamically, you can put the profiles as vm-arguments in the catalina.sh
CATALINA_OPTS="-Dspring.profiles.active=dev"

A: You can set additional profiles on start up:
   SpringApplication springApp = new SpringApplication(Main.class);
   springApp.setAdditionalProfiles("profile1", "profile2");
   springApp.run(args);

A: System.setProperty("spring.profiles.active", "dev");

A: I also had the same problem and after struggling for half a day I ended up with this:
    @SpringBootApplication
    public class MyApplication extends SpringBootServletInitializer {

        public static void main(String[] args) {
            System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
            SpringApplication.run(MyApplication.class, args);
        }

        @Override
        public void onStartup(ServletContext servletContext) throws ServletException {
            System.setProperty(AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAME, "dev");
            super.onStartup(servletContext);
        }
    }

A: Another way of doing it in Spring Boot 2 is by using SpringApplicationBuilder:
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;

@SpringBootApplication
public class MySpringProgram {

    public static void main(String[] args) {
        new SpringApplicationBuilder(MySpringProgram.class)
                .profiles("profile1", "profile2")
                .run(args);
    }
}

A: SpringApplication app =new SpringApplication(Application.class);
    Properties props = new Properties();
    props.put("AbstractEnvironment.ACTIVE_PROFILES_PROPERTY_NAM", "dev");
    app.setDefaultProperties(props);
    app.run(args);

I think this code is better solution, because it doesn't set system property


text:
Q: Comments orderby comment date not working I have a template to get the comment replies to a user and display it on a static page. It works reasonably well in so far as the correct comments are displayed but whatever I try I can't get the replies to order by comment date, the newest first, but instead they will order by their parent comment first and after that by date. Also, the pagination is not displaying. I would be most grateful for any help or hints here!
<?php
global $current_user;
get_currentuserinfo();
define('DEFAULT_COMMENTS_PER_PAGE',6);
$page = (get_query_var('page')) ? get_query_var('page') : 1;
$limit = DEFAULT_COMMENTS_PER_PAGE;
$offset = ($page * $limit) - $limit;
$param = array(
    'status'=>'approve',
    'user_id' => $current_user->ID,
    'comment_parent' => 0
);
$parent_comments = get_comments($param); ?>
<?php foreach($parent_comments as $parent_comment) : ?>
<?php $parent_comment_id = $parent_comment->comment_ID;
$comment_args = array(
    'orderby' => 'comment_date',
    'status' => 'approve',
    'parent' => (int)$parent_comment_id,
    'offset' => $offset,
    'number' => $limit
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $comment_args );
if ( $comments ) : ?>
    <?php foreach($comments as $reply) : ?>

        <?php echo $reply->comment_author; ?>has left a
            <a href="<?php echo get_comment_link( $reply->comment_ID ); ?>">reply to your <a href="<?php echo get_comment_link( $parent_comment->comment_ID ); ?>">comment

            <?php echo apply_filters('the_content', $reply->comment_content); ?>

    <?php endforeach; ?>
<?php endif; ?>
<?php endforeach; ?>

<?php $pages = ceil(count($comments)/DEFAULT_COMMENTS_PER_PAGE); ?>

<?php
$args = array(
    'base' => 'http://mywordpress.example/user/replies/%#%',
    'format' => '?page=%#%',
    'total' => $pages,
    'current' => $page,
    'show_all' => False,
    'end_size' => 1,
    'mid_size' => 2,
    'prev_next' => True,
    'prev_text' => __('Previous'),
    'next_text' => __('Next'),
    'type' => 'plain');

 echo paginate_links( $args );
?>


text:
Q: How to resize the frame of embeded image in mail composer using MFMailComposeViewController in iphone I have embeded a user image in message body of MFMailComposeSheet
in my iPhone app.
NSMutableString *messageBody = [[[NSMutableString alloc] initWithString:@""] retain];

NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(capturedProfileImage)];
NSString *base64String = [self base64forData:imageData];

[messageBody appendFormat:@"
     %@.
",textMessage];
[messageBody appendFormat:@"
REGARDS
"];
[messageBody appendFormat:@"

", base64String];
[messageBody appendFormat:@"
     %@.
",userName];
[messageBody appendFormat:@"
     %@.
",userPhone];
[messageBody appendFormat:@""];

Require format is like as follows:

But the embedded image displayed in its actual size, and I need to display in 57x57 pixels. How do I fix the width and height of the image as 57x57?

A: Fixed:
[messageBody appendFormat:@"

", base64String];


text:
Q: How to add search option for the queries we create in Elastic Search? Hi Team I am new to log stash and Elastic search.
In my log stash, I get lot of logs, few examples are
celery-logs, nginx-logs, and management-logs
I have created Queries like category==celery-logs, category==nginx-logs and category==mgmt-logs
Created three panels attaching each specific query to all three, under every category there are multiple log levels like info, error, waring..etc
How can I create a search pattern which is individual to each panel?
I have tried creating filters, however filters are applicable to entire dashboard, please suggest me on how to create specific filters confined to panels.

A: What you can do is create visualizations which are general to all categories and then have a Dashboard for each category. Dashboards can have a filter associated that they will remember. That way you reuse your visualizations.

A: The simplest way is to create and save 3 visualizations, each one with a different filter. then each visuzlization will only display its filtered data.
Then you can put all 3 visualizations in a single dashboard. The dashboard query and filters can be empty (which will match_all) and still those 3 filters would be taken into account in the visualizations.


text:
Q: How do you find out the difference between workstations and servers on the network? I know how to get the machines on a server using the System.DirectoryServices network.
The issue is that I would like to ignore workstations/computers on the network and only retrieve servers.
In case someone says to check the OS version, the problem with getting a Win NT family OS version number is that each number may correspond to both a server and non-server OS (such as NT version 6.1 referring both to Win 7 and Win Server 2008 R2).
Here is my basic test class:
namespace Project1
{
    class Class1
    {
        public static void Main(string[] args)
        {
             List<string> list = Class1.GetComputersOnNetwork();
        }

        public static List<string> GetComputersOnNetwork()
        {
            string fileName = "networkcomputers.txt";

            // Delete the file if it exists.
            if (System.IO.File.Exists(fileName))
            {
                System.IO.File.Delete(fileName);
            }

            // Create the file.
            System.IO.FileStream fs = System.IO.File.Create(fileName, 1024);

            StreamWriter strwr = new StreamWriter(fs);

            int i = 0;
            List<string> list = new List<string>();
            DirectoryEntry root = new DirectoryEntry("WinNT:");
            foreach (DirectoryEntry computers in root.Children)
            {
                if ((computers.Name != "Schema"))
                {
                    i++;
                    Console.WriteLine("Machine Number " + i + ": " + computers.Name);
                    strwr.WriteLine("Machine Number " + i + ": " + computers.Name);
                    list.Add(computers.Name);
                }
            }
            return list;
        }
    }
}

A: Instead of going at the operatingSystemVersion property, look at the operatingSystem property. That'll give you the name of the SKU. You'll need to know which are server OS versions and which aren't - there's no IsServer boolean. Depending on how they're named, you may be able to do a wildcard search on operatingSystemVersion to find computers that have a operatingSystemVersion that contains the string "server".

A: You can read the registry key HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\InstallationType.
The key is:

*

*"Server" if this PC is running Windows Server (e.g. Windows Server 2012).

*"Client" if this PC is running Windows Desktop (e.g. Windows 8.1).

This registry key is quite easy to read using any language such as C#.
For more info, see article entitled "distinguish between server os and workstation".
Update
Link is dead, use archive.org:
https://web.archive.org/web/20140502101009/http://blogs.msdn.com/b/ejarvi/archive/2004/06/08/151162.aspx
Copying from this page:

ejarvi 8 Jun 2004 3:47 PM 9 I maintain a script in our test harness
  that autodetects and reports back the OS version of the machine under
  test.  I couldn't tell if I was running XP SP1 or XP SP2 - so I had a
  kludge that used spcheck from the reskit.  But the real problem was
  that I was getting most info using ver from the cmd shell but on
  Windows 2000 couldn't tell the difference between Professional and
  Server.  I was able to find all this info in the registry so I ripped
  out the hacks and now I'm just reading from there.  If anyone else out
  there is trying to do the same thing, here's where I get the
  information from (all are in HKLM):
SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProductName (Microsoft
  Windows Server 2003, Microsoft Windows XP, Microsoft Windows 2000)
SOFTWARE\Microsoft\Windows NT\CurrentVersion\CDSVersion (Service Pack
  1, Service Pack 2, ...)
And to distinguish between Pro and Server on Windows 2000:
  SYSTEM\CurrentControlSet\Control\ProductOptions\ProductType (WinNT,
  ServerNT)
I didn't actually use it in my case but if you're looking for more of
  a prepackaged tool to do this type of thing, DtWinVer at
  http://www.codeproject.com/system/dtwinver.asp also looks promising.


text:
Q: Push ViewController I have added UINavigationBar in appDelegate method. Please check my atatched screen shots. In bottom is i have used UINavigationBar. In middel of the page history button is there.
Here when i click the history button its cant go to historyviwcontrooler. Because i cant push the view. Can you please tell me how i can push here. When i click history its called only one calls after only thet called another class there only i given UI. How i handel here . please help me
#import "UICallButton.h"
#import "LinphoneManager.h"

#import <CoreTelephony/CTCallCenter.h>

@implementation UICallButton

@synthesize addressField;

#pragma mark - Lifecycle Functions

- (void)initUICallButton {
    [self addTarget:self action:@selector(touchUp:) forControlEvents:UIControlEventTouchUpInside];
}

- (id)init {
    self = [super init];
    if (self) {
        [self initUICallButton];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame {
    self = [super initWithFrame:frame];
    if (self) {
        [self initUICallButton];
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)decoder {
    self = [super initWithCoder:decoder];
    if (self) {
        [self initUICallButton];
    }
    return self;
}

- (void)dealloc {
    [addressField release];

    [super dealloc];
}

#pragma mark -

- (void)touchUp:(id) sender {

    NSString *address = [addressField text];
    NSString *displayName = nil;
    ABRecordRef contact = [[[LinphoneManager instance] fastAddressBook] getContact:address];
    if(contact) {
        displayName = [FastAddressBook getContactDisplayName:contact];
    }
    [[LinphoneManager instance] call:address displayName:displayName transfer:FALSE];

}

@end

A: Basically, you must have a UINavigationController, and not just a UINavigationBar, in order to be able to perform a push transition to one UIViewController to another.
I'm not explaining how to do that because it's very basic, you should study and read some books/tutorials before begin a real project.
Here's some links to help you:

*

*A nice tutorial

*How to use navigation controllers (from apple)

*Navigation Controller class reference


text:
Q: E(XY) = E(X).E(Y|X) . Is this true for mean = zero. I know that Joint Probability density function for two random functions $X$ and $Y$
$$P(XY) = P(X)\cdot P(Y|X)\tag{1}$$
But I just read in a set of lecture notes that for E(X)=E(Y)=0
$$E(XY) = E(X)\cdot E(Y|X)\tag{2}$$
I also know that $E(X) =$ Multiplication of $P(X)$ with $x$ and subsequent Integration over $x$
Hence, I don't see how equation (2) stands true. Any ideas? Is it wrongly written.

A: Your equation (1) is misleading.   The joint density function of two random variables is not related to their product.   Further we more commonly use $f$ for probability density functions, rather than $\mathsf P$.  So the joint PDF is:
$$f_{X,Y}(x,y) = f_X(x)f_{Y\mid X}(y\mid x)$$
The expected value of the product of two random variables is then:
$$\begin{align}
\mathsf E[XY]
 & = \iint_{\mathcal{X\times Y}} xy\; f_{X,Y}(x,y)\operatorname d y \operatorname d x
\\[1ex]
 & = \iint_{\mathcal{X\times Y}} xy\;f_{Y\mid X}(y\mid x)f_X(x)\operatorname d y \operatorname d x
\\[1ex]
 & = \int_\mathcal X x\left(\int_\mathcal{Y\mid X=x} y\;f_{Y\mid X}(y\mid x)\operatorname d y\right)f_X(x)\operatorname dx
\\[1ex] & = \int_\mathcal X x\;\mathsf E[Y\mid X=x]\;f_X(x)\operatorname dx
\\[1ex] & = \mathsf E[X\;\mathsf E[Y\mid X]]
\end{align}$$

Which is not the same thing as: $\mathsf E[X]\;\mathsf E[Y\mid X]$


text:
Q: Building a predictive model with text data and other predictors I'm trying to build a predictive model (random forest, sgd, etc.) using scikit-learn and it seems like every model only allows you to fit text data such as
classifier.fit(X,Y)

...where Y is the target and X is a text feature vector (count_vec -> tf_idf). Is there any way to have a model which in addition to the text feature matrix also contains several categorical variables? Can I simply append them as new columns on the right side of X?

A: You will need to convert categorical data first - simple appending of string categories to the number values from a feature extractor like TfIdfCountVectorizer will not work. Here's a SO question and answer on converting categories into numerical feature data that you can append to the right.


text:
Q: CPU temp monitoring tools freezes the laptop I have a problem running any form of CPU temp monitoring app on my Ubuntu(and same on Mint) on my old Dell Studio 1737(A09).
Whether I install psensor, sensors, lm-senors or i8kutils (this last one crashes the PC) the laptop freezes and I can't do anything until I restart and remove the package.
I had dual boot before (Windows 7) and did not have any problem monitoring CPU temperature so I am guessing it is related to my OS, not the hardware.
I ended up installing fan control which detects the fan and functions ok but I have to set intervals to 3600s to not to check on CPU often since every time it tries to check the CPU temp, my screen freezes for a few seconds and then is released until the next check. Any attempt by me to check the CPU temp (running 'sensors' in terminal) freezes everything.


text:
Q: Prove that $\forall\alpha\geq\omega$, $|L_\alpha|=|\alpha|$ without AC Without using Axiom of Choice, prove that
$$\forall\alpha\geq\omega,~~|L_\alpha|=|\alpha|,$$
in which $\alpha$ is an ordinals, $\omega$ is the set of natural numbers, $L_\alpha$ is the $\alpha$-th constructiable set, $|x|$ is the cardinals of $x$.
I am learning a set theory, and I have read a proof by using AC. The AC is used only when $\alpha$ is a limit ordinals during the transfinite inductive method for $\alpha$ . I wonder if there is a proof without AC.  THANKS!

A: First you can notice that for a limit ordinal $\delta$, $L_\delta\models V=L$ and in particular $L_\delta$ has a definable well-ordering of type $\delta$.
So the use of the axiom of choice can be removed and instead you can use the definable well-orderings for everything instead.
Then the proof is quite similar. First note that $L_\omega$ is countable; then proceed by induction. $L_{\alpha+1}$ has a bijection with $(L_\alpha)^{<\omega}\times\omega$ (by encoding formulas and parameters) and using the induction hypothesis $|\alpha|=|L_\alpha|=|L_{\alpha+1}|=|\alpha+1|$. When arriving to limit ordinals, use the fact that there is a definable well-ordering to conclude that $L_\delta$ is the union of uniformly well-ordered sets and conclude $|L_\delta|=|\delta|\cdot\sup\{|L_\alpha|\mid\alpha<\delta\}=|\delta|\cdot|\delta|=|\delta|$.
(All the cardinal arithmetic is true because it holds for ordinals without using choice.)
Note, by the way, that Gödel proved that the axiom of choice is at all consistent with the rest of the axioms of set theory by proving that it holds in $L$. So all the arguments about the construction of $L$ shouldn't, morally, appeal to the axiom of choice. And they don't.