text:
Q: Streamlit: How do I correctly add my python packages to the requirements.txt? I want to try out Streamlit Sharing (https://www.streamlit.io/sharing). This is my locally working code:
streamlit_app.py
import pandas as pd
import streamlit as st

from PIL import Image
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import train_test_split

# Model
df = pd.read_csv("IRIS.csv")

X = df.drop(columns=["species"])
y = df["species"]

X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.33, random_state=42)

rf = RandomForestClassifier()
rf.fit(X_train, y_train)

# Streamlit
st.header("Iris Classification")

image = Image.open("iris.jpg")
st.image(image, use_column_width=True, output_format="jpg")

st.write("Please insert values, to get Iris class prediction")

SepalLengthCm = st.slider('SepalLengthCm:', 2.0, 6.0)
SepalWidthCm = st.slider('SepalWidthCm:', 0.0, 5.0)
PetalLengthCm = st.slider('PetalLengthCm',0.0, 3.0)
PetalWidthCm = st.slider('PetalWidthCm:', 0.0, 2.0)
data = {'SepalLengthCm': SepalLengthCm,
        'SepalWidthCm': SepalWidthCm,
        'PetalLengthCm': PetalLengthCm,
        'PetalWidthCm': PetalWidthCm}

features = pd.DataFrame(data, index=[0])
prediction = rf.predict(features)
percentages = rf.predict_proba(features)

st.subheader("Prediction")
st.write(prediction[0])

st.subheader("Percentages")
st.write("Iris-setosa: ", percentages[0][0]*100)
st.write("Iris-versicolor: ", percentages[0][1]*100)
st.write("Iris-virginica: ", percentages[0][2]*100)

Now, to get the requirements.txt (that is necessary for streamlit sharing) I did the following:

*

*Create new environment using conda create --name streamlit-test python=3.7

*pip install streamlit

*pip install sklearn

*Optional: streamlit run streamlit_app.py successfully runs the app locally

*pip freeze > requirements.txt
When I deploy the app via Streamlit sharing, it says "ModuleNotFoundError: No module named 'sklearn'" (in line 5). You should actually be able to see this for yourself: https://share.streamlit.io/juliangermek/streamit_test
Checking requirements.txt reveals that sklearn is present like this sklearn==0.0.
This is the log from Streamlit Sharing:

[client] Connecting...
[manager] Starting up for owner: 'juliangermek', repository: 'streamit_test', branch: 'master', main module: 'streamlit_app.py'
[manager] Cloning repository ...
[manager] Cloning into 'streamit_test'...

[manager] Cloned repository!
[manager] Processing dependencies ...
Requirement already satisfied: altair==4.1.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 3)) (4.1.0)
ERROR: Could not find a version that satisfies the requirement anaconda-client==1.7.2
ERROR: No matching distribution found for anaconda-client==1.7.2
[manager] Processed dependencies!

  You can now view your Streamlit app in your browser.

  Network URL: http://10.12.4.85:8501
  External URL: [2021-01-22 07:46:22.016741] http://35.230.58.211:8501

Requirement already satisfied: altair==4.1.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 3)) (4.1.0)
ERROR: Could not find a version that satisfies the requirement anaconda-client==1.7.2
ERROR: No matching distribution found for anaconda-client==1.7.2
  Stopping...

  You can now view your Streamlit app in your browser.

  Network URL: http://10.12.4.85:8501
  External URL: http://35.230.58.211:8501

Requirement already satisfied: altair==4.1.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 1)) (4.1.0)
Requirement already satisfied: argon2-cffi==20.1.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 2)) (20.1.0)
Requirement already satisfied: astor==0.8.1 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 3)) (0.8.1)
Requirement already satisfied: async-generator==1.10 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 4)) (1.10)
Requirement already satisfied: attrs==20.3.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 5)) (20.3.0)
Requirement already satisfied: backcall==0.2.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 6)) (0.2.0)
Requirement already satisfied: base58==2.1.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 7)) (2.1.0)
Requirement already satisfied: bleach==3.2.2 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 8)) (3.2.2)
Requirement already satisfied: blinker==1.4 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 9)) (1.4)
Requirement already satisfied: cachetools==4.2.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 10)) (4.2.0)
Requirement already satisfied: certifi==2020.12.5 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 11)) (2020.12.5)
Requirement already satisfied: cffi==1.14.4 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 12)) (1.14.4)
Requirement already satisfied: chardet==4.0.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 13)) (4.0.0)
Requirement already satisfied: click==7.1.2 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 14)) (7.1.2)
Requirement already satisfied: decorator==4.4.2 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 16)) (4.4.2)
Requirement already satisfied: defusedxml==0.6.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 17)) (0.6.0)
Requirement already satisfied: entrypoints==0.3 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 18)) (0.3)
Requirement already satisfied: gitdb==4.0.5 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 19)) (4.0.5)
Requirement already satisfied: GitPython==3.1.12 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 20)) (3.1.12)
Requirement already satisfied: idna==2.10 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 21)) (2.10)
Requirement already satisfied: importlib-metadata==3.4.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 22)) (3.4.0)
Requirement already satisfied: ipykernel==5.4.3 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 23)) (5.4.3)
Requirement already satisfied: ipython==7.19.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 24)) (7.19.0)
Requirement already satisfied: ipython-genutils==0.2.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 25)) (0.2.0)
Requirement already satisfied: ipywidgets==7.6.3 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 26)) (7.6.3)
Requirement already satisfied: jedi==0.18.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 27)) (0.18.0)
Requirement already satisfied: Jinja2==2.11.2 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 28)) (2.11.2)
Requirement already satisfied: jsonschema==3.2.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 30)) (3.2.0)
Requirement already satisfied: jupyter-client==6.1.11 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 31)) (6.1.11)
Requirement already satisfied: jupyter-core==4.7.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 32)) (4.7.0)
Requirement already satisfied: jupyterlab-pygments==0.1.2 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 33)) (0.1.2)
Requirement already satisfied: jupyterlab-widgets==1.0.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 34)) (1.0.0)
Requirement already satisfied: MarkupSafe==1.1.1 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 35)) (1.1.1)
Requirement already satisfied: mistune==0.8.4 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 36)) (0.8.4)
Requirement already satisfied: nbclient==0.5.1 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 37)) (0.5.1)
Requirement already satisfied: nbconvert==6.0.7 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 38)) (6.0.7)
Requirement already satisfied: nbformat==5.1.2 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 39)) (5.1.2)
Requirement already satisfied: nest-asyncio==1.4.3 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 40)) (1.4.3)
Requirement already satisfied: notebook==6.2.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 41)) (6.2.0)
Requirement already satisfied: numpy==1.19.5 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 42)) (1.19.5)
Requirement already satisfied: packaging==20.8 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 43)) (20.8)
Requirement already satisfied: pandas==1.2.1 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 44)) (1.2.1)
Requirement already satisfied: pandocfilters==1.4.3 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 45)) (1.4.3)
Requirement already satisfied: parso==0.8.1 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 46)) (0.8.1)
Requirement already satisfied: pickleshare==0.7.5 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 47)) (0.7.5)
Requirement already satisfied: Pillow==8.1.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 48)) (8.1.0)
Requirement already satisfied: prometheus-client==0.9.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 49)) (0.9.0)
Requirement already satisfied: prompt-toolkit==3.0.11 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 50)) (3.0.11)
Requirement already satisfied: protobuf==3.14.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 51)) (3.14.0)
Requirement already satisfied: pyarrow==2.0.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 52)) (2.0.0)
Requirement already satisfied: pycparser==2.20 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 53)) (2.20)
Requirement already satisfied: pydeck==0.5.0 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 54)) (0.5.0)
Requirement already satisfied: Pygments==2.7.4 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 55)) (2.7.4)
Requirement already satisfied: pyparsing==2.4.7 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 56)) (2.4.7)
Requirement already satisfied: pyrsistent==0.17.3 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 57)) (0.17.3)
Requirement already satisfied: python-dateutil==2.8.1 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 58)) (2.8.1)
Requirement already satisfied: pytz==2020.5 in /usr/local/lib/python3.7/site-packages (from -r requirements.txt (line 59)) (2020.5)
ERROR: Could not find a version that satisfies the requirement pywin32==300
ERROR: No matching distribution found for pywin32==300
  Stopping...
[manager] Error checking Streamlit healthz: Get "http://localhost:8501/healthz": dial tcp 127.0.0.1:8501: connect: connection refused

  You can now view your Streamlit app in your browser.

  Network URL: http://10.12.4.85:8501
  External URL: http://35.230.58.211:8501

This is my repro with the app in it: https://github.com/juliangermek/streamit_test
I can't figure out why this is working locally, but not with Streamlit Sharing. Do you have any ideas?
Thanks, Julian

A: Unnecessary packages such as pywin32==300 should be removed from requirements.txt while deploying. This type of package causes errors, so it is better to remove all the unnecessary packages.
Also, it is not sklearn but actually it is scikit-learn. So to install scikit-learn use this line:
pip install scikit-learn

See here

You can also manually change the name of sklearn to scikit-learn by opening requirements.txt file.
scikit-learn==0.22.1
matplotlib==3.2.2
numpy==1.18.1
pandas==1.0.5
streamlit==0.62.0
Werkzeug==1.0.1


text:
Q: How can I remove Milliseconds from the TimeSpan in C#? I am new to c# and using windows forms. the result of this code is: 01:38:07.0093844 . Anyone knows how can I remove the millisecond part (0093844) from the result (ts) I want the result to look like this : 01:38:07 (H:mm:ss) without millisecond .
Please help .Thank you
string OldDateTime = "2016-03-02 13:00:00.597"; //old DateTime
DateTime CurrentDateTime = DateTime.Now;

TimeSpan  ts = CurrentDateTime.Subtract(Convert.ToDateTime(OldDateTime)); //Difference

//result of ts = 01:38:07.0093844

A: You can round through a division and a multiplication by the number of Ticks per second:
ts = new TimeSpan(ts.Ticks / TimeSpan.TicksPerSecond * TimeSpan.TicksPerSecond);

Internally a TimeSpan is "simply" a number of Ticks. By doing an integer division and an integer multiplication you can "round" them.

A: What the object contains and what you want on the screen are separate concerns, do not mix the 2. If you want it formatted on the screen as hourse, minutes, seconds then use ToString() and include that in your format. Example:
var forScreen = ts.ToString("hh:mm:ss");

See all the formatting options available on MSDN Custom TimeSpan Format Strings.

Edit
As mentioned, you can make it whatever you want. Here is an example of ToString which builds out a human readable string. These formatters are meant to build a string that you can display so you do not have to actually make changes to the underlying data. This is your presentation logic.
dif.ToString("'Elapsed: 'dd' days, 'hh' hours, 'mm' minutes and 'ss' seconds'")

A: Create an extension method:
public static class TimeExtensions
{
    public static TimeSpan StripMilliseconds(this TimeSpan time)
    {
        return new TimeSpan(time.Days, time.Hours, time.Minutes, time.Seconds);
    }
}

Usage:
string OldDateTime = "2016-03-02 13:00:00.597"; //old DateTime
DateTime CurrentDateTime = DateTime.Now;

TimeSpan  ts = CurrentDateTime.Subtract(Convert.ToDateTime(OldDateTime)).StripMilliseconds();

To format (make into a string) without milliseconds use this:
string OldDateTime = "2016-03-02 13:00:00.597"; //old DateTime
DateTime CurrentDateTime = DateTime.Now;

TimeSpan  ts = CurrentDateTime.Subtract(Convert.ToDateTime(OldDateTime));
string formatted = ts.ToString(@"dd\.hh\:mm\:ss");

A: You can just format the time like below:
string NewDateTime = ts.ToString("yyyy-MM-dd hh:mm:ss");

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails wont render a RestClient exception body unless I interpolate it I'm having a really weird issue trying to write a test around a rails controller.
The controller uses RestClient to get info from another server. If that 2nd server returns a bad response, I want to forward on that error message to the client.
The controller:
def callback_submit
  begin
    response = RestClient.post(...)
    render json: response
  rescue RestClient::BadRequest => e
    render status: :bad_request, json: { error: e.response.body }
  end
end

Then I have an rspec test for this:
  it 'returns a failure message' do
    stub_request( :post, 'http://...' ).to_return( status: 400, body: 'some error' )

    post :callback_submit

    expect(response.body).to eq({error: 'some error'}.to_json)
  end

Now the problem is that the rspec output is:
   expected: "{\"error\":\"some error\"}"
        got: "{\"error\":\"\"}"

Where it gets weird is that I can change my controller to puts some details...
  rescue RestClient::BadRequest => e
    error = e.response.body.to_s
    puts error.class
    puts error
    render status: :bad_request, json: { error: error }

Which outputs:
String
some error

   expected: "{\"error\":\"some error\"}"
        got: "{\"error\":\"\"}"

So the error variable seems to be a string and the correct value, but render turns it into an empty string.

Now it gets really weird... If I interpolate the string:
  rescue RestClient::BadRequest => e
    error = e.response.body.to_s
    puts error.class
    puts error
    render status: :bad_request, json: { error: "#{error}" }

Or just simply:
  rescue RestClient::BadRequest => e
    render status: :bad_request, json: { error: "#{e.response.body}" }

Then my test PASSES!

At first I thought e.response.body must not be a String, which is why I puts its class which prints "String" and also called .to_s on it, but that didn't seem to change anything.
Can anyone explain this weird behavior?

A: Asked some Ruby friends and one of them found the problem, but didn't want to come post an answer here....

The problem ends up being that we are on an older RestClient (1.8). In the RestClient 2.0 notes:

Response objects are now a subclass of String rather than a String that mixes in the response functionality.
Response#body and #to_s will now return a true String object rather than self. Previously there was no easy way to get the true String response instead of the Frankenstein response string object with AbstractResponse mixed in.

So in the older version I am using, e.response ends up being this weird String mixin mashup thing, and render doesn't seem to like it.
The interpolation turns it back into a real Ruby string again.

A: The problem is that response.body is looking at the response object and the body is empty because of the error.
Chances are you want e.message or just e.to_s which will be the error message (or the error class name) rather than the response body.
Excerpt:
class Exception < RuntimeError
  attr_accessor :response
  attr_writer :message
  #.......
  def to_s
    message
  end

  def message
    @message || default_message
  end

  def default_message
    self.class.name
  end
end

Source


text:
Q: What is the dimension of the subspace $W=\{ F(x) \mid (D^2+1)F(x)=0 \wedge F(x)=0\}$
What is the dimension of the subspace $W=\{ F(x) \mid (D^2+1)F(x)=0 \wedge F(x)=0\}$

I solved this and found $F(x)=a \cos(x)+b \sin(x)$, but due to the second condition I think it is the null space. Am I right or wrong?

A: As the assignment is currently written, my guess would be that the answer is yes. Though you may want to check if the second condition was meant to be $F(x_0)=0$ (as in $W=W_{x_0}$ being a set which depends on the parameter $x_0$).

A: I think that $W$ is the space of functions $y : \mathbb R \to \mathbb R$, which are solutions of the initial value problem
$y''+y=0$, $y(x_0)=0$,
where $x_0$ is a given point in $ \mathbb R$.
The general solution of the differential equation is given by $y(x)=a \cos(x)+b \sin(x)$.
From $0=y(x_0)$ we get $a \cos(x_0)+b \sin(x_0)=0$.
Case 1: $\cos (x_0) \ne 0$- Then $a= -\frac{b \sin(x_0)}{\cos(x_0)}$, hence
$$y(x)=b[ \sin(x)-\frac{\sin(x_0)}{\cos(x_0)} \cos(x)].$$
This gives $ \dim W=1$.
Case 2: $\sin(x_0) \ne 0$. Similar considerations (which are your turn) give again $ \dim W=1$.
Remark: the case $ \cos(x_0)=0= \sin(x_0)$ is not possible. Why ?


text:
Q: WebRtc on Windows phone 8.1 I need to implement WebRtc on a windows phone 8.1 universal app,
there is some kind of library available?
I have found this one www.nuget.org/packages/WebRTC/1.1.24, but there isn't documentation.
thanks

A: IceLink claims to support that (commercial):
http://www.frozenmountain.com/webrtc/


text:
Q: Counting repeat registers by column value with a simple query Given that I have the following table:
Id, Date, Data Identifier, Info
1, 2013-01-01, 'XSWQ', '#1'
2, 2013-01-02, 'ADWS', '#1'
3, 2013-01-02, 'ADWS', '#2'
4, 2013-01-02, 'QKVJ', '#1'
5, 2013-01-03, 'XSWQ', '#1'
6, 2013-01-03, 'ADWS', '#1'
7, 2013-01-04, 'QKVJ', '#1'
8, 2013-01-04, 'VSAQ', '#1'
9, 2013-01-04, 'VSAQ', '#2'

How can I counting the repeat registers (same Data Identifier in different Dates) with a unique and simple SQL (no subqueries) for a limited period but comparing records of all time?
For example, I want to count duplicate records that appear between 2013-01-02 and 2013-01-04 considering the entire table. The 'VSAQ' shouldn`t be considered repeated, but 'XSWQ' should be considered a duplicate record (the first appearance of it is outside the period stated).
Then the result is 3 (XSWQ, ADWS, QKVJ)
Is it possible with a unique and simple query?

A: SELECT DISTINCT tbl.Identifier
FROM tbl
LEFT JOIN tbl AS everything
ON tbl.Identifier = everything.Identifier
  AND tbl.Id <> everything.Identifier
WHERE tbl.Date BETWEEN '2013-01-02' AND '2013-01-04'
  AND everything.id IS NOT NULL
ORDER BY tbl.Identifier

but why the anti-subquery?  The subquery may be quicker
See http://sqlfiddle.com/#!2/19fb3/5


text:
Q: Centos - server iso I have downloaded the centos (6) minimal version and am trying to install on a virtual box.
When i fire up the installation, it starts a gui insaller.  I am trying to have a server only iso and this doesnt appear to be it.
Where can I find an ISO that does not have the gui included?

A: The installer having a GUI has no influence on the package selection for installation.
Select 'Minimal' during installation to get a minimal installation suitable for a server.
If you want a completely automated installation without any GUI, have a look at Kickstart.

A: I don't think you can decide if thats a server iso or not, based on the style of the installer. If the download link told you this is a server iso, i would assume it is, unless there is a good reason to think it isn't.

A: CentOS minimal version, No GUI in this it is CLI.
http://isoredirect.centos.org/centos/6/isos/x86_64/


text:
Q: Ответ сервера на C# Как просмотреть что написано на странице на C#?
Например содержание страницы содержит команду для программы:
wait
check
etc...
ну и
if(содержание == "wait")
{
    wait(true);
}

и ещё, как разбить строку, вот на php это explode(), а на шарпе как?
A: нашел ответ сам, может кому нужен будет
using System;
using System.Windows.Forms;
using System.Net;
using System.IO;
using System.Text;

    class Program
    {
        static void Main(string[] args)
        {

          WebClient wc = new WebClient();
          string remoteUri = "http://";
          byte[] myDataBuffer = wc.DownloadData (remoteUri);
          string download = Encoding.ASCII.GetString(myDataBuffer);
          Console.WriteLine(download);
          Console.Read();

        }
    }


text:
Q: Microsoft.ApplicationInsights.Log4NetAppender I'm getting a silent error when trying to create my Log4NetAppender, which stops the logging from working.

Could not load type
'Microsoft.ApplicationInsights.TelemetryConfiguration' from assembly
'Microsoft.ApplicationInsights, Version=1.1.0.1899, Culture=neutral,
PublicKeyToken=31bf3856ad364e35'.
at Microsoft.ApplicationInsights.Tracing.Tracer..ctor(String instrumentationKey)
at Microsoft.ApplicationInsights.Log4NetAppender.ApplicationInsightsAppender.ActivateOptions()
at log4net.Repository.Hierarchy.XmlHierarchyConfigurator.ParseAppender(XmlElement appenderElement)

From what I can see, the log provider is trying to create the class Microsoft.ApplicationInsights.TelemetryConfiguration but this is the wrong namespace and the class actually exists in Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration.
We are using the following libraries

Microsoft.ApplicationInsights - 1.1.0.1899
Microsoft.ApplicationInsights.Log4NetAppender - 0.10.0.0

They are both the latest versions, so I'm not sure why they aren't working together.

A: Fixed it - Just upgraded to the latest Microsoft.ApplicationInsights.Log4NetAppender stable pre-release 1.1.0


text:
Q: How to call accountManager.getUserData from a custom account that has been created with another app? I am creating two apps. The main app has included a login, where a custom account is created. With the second app I want to access the user data (refresh token is stored there) from the main app.
The main app is creating a custom account and the refresh token is stored via setUserData. Through the main app it is no problem to get the refresh token with
mAccountManager.getUserData(account, KEY_REFRESH_TOKEN);

It works perfectly fine to retrieve the refresh token, if the both apps are signed with the same key.
But when I call this method and the apps are not signed with the same key:
mAccountManager.getUserData(account, KEY_REFRESH_TOKEN);

I receive following error:
2019-10-01 12:01:51.143 5528-5528/at.exampleapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: at.exampleapp, PID: 5528
    java.lang.SecurityException: uid 10265 cannot get user data for accounts of type: accountType
        at android.os.Parcel.createException(Parcel.java:1950)
        at android.os.Parcel.readException(Parcel.java:1918)
        at android.os.Parcel.readException(Parcel.java:1868)
        at android.accounts.IAccountManager$Stub$Proxy.getUserData(IAccountManager.java:1020)
        at android.accounts.AccountManager.getUserData(AccountManager.java:515)
        at eu.aal.dapas.component_auth.AccountAuthenticator.getExistingAccountRefreshToken(AccountAuthenticator.java:206)
        at eu.aal.dapas.component_auth.AccountAuthenticator.refreshAccessToken(AccountAuthenticator.java:138)
        at eu.aal.dapas.component_auth.DapasAccountManager.getAccessToken(DapasAccountManager.java:41)
        at at.e_nnovation.emma.apps.exampleapp.MainActivity.getUserDetails(MainActivity.java:196)
        at at.e_nnovation.emma.apps.exampleapp.MainActivity$1.onClick(MainActivity.java:53)
        at android.view.View.performClick(View.java:6600)
        at android.view.View.performClickInternal(View.java:6577)
        at android.view.View.access$3100(View.java:781)
        at android.view.View$PerformClick.run(View.java:25912)
        at android.os.Handler.handleCallback(Handler.java:873)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6923)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:870)
     Caused by: android.os.RemoteException: Remote stack trace:
        at com.android.server.accounts.AccountManagerService.getUserData(AccountManagerService.java:1574)
        at android.accounts.IAccountManager$Stub.onTransact(IAccountManager.java:77)
        at com.android.server.accounts.AccountManagerService.onTransact(AccountManagerService.java:1100)
        at android.os.Binder.execTransact(Binder.java:735)

So my questions are:
1.) Is it possible at all to call the user data from a custom account with accountManager.getUserData(account, key) from another app?
2.) If not is there a way to get the refresh token from the custom account?

A: As you can see in the documentation:

This method requires the caller to have a signature match with the authenticator that owns the specified account.

So you need to have both apps signed with the same key.
Or you can just use getAuthToken and invalidateAuthToken in the second app and implement authenticator service in the first one. Just follow this documentation


text:
Q: What is the relation between the False Positive Rate to the True Positive and True Negative Rates? I know that the True Negative Rate plus the False Positive Rate is equal to 1. However, I don't quite see how the True Positive Rate and False Positive Rate are related. Is there a relation between them?

A: It might be helpful to think of these quantities as conditional probabilities. For concreteness, consider a medical test used to determine whether a patient has a disease. Define the following events:
$$\begin{align*}
"+" &= \text{the test is positive} \\
"-" & = \text{the test is negative} \\
\text{Disease} & = \text{the patient has the disease} \\
\text{Healthy} & = \text{the patient does not have the disease} \\
\end{align*}$$
Then
$$\begin{align*}
\text{True Negative Rate} &= P(- \mid \text{Healthy}) \\
\text{False Positive Rate} &= P(+ \mid \text{Healthy})
\end{align*}$$
Since the events $"+"$ and $"-"$ are the only possible outcomes given a healthy patient, these probabilities must sum to 1, as you observe.
On the other hand
$$\begin{align*}
\text{True Positive Rate} &= P(+ \mid \text{Disease})
\end{align*}$$
conditions on the event $\text{Disease}$, which is disjoint from $\text{Healthy}$. So in general there is nothing we can say about the relationship between the True and False Positive Rates.

A: As @tddevlin pointed out, there is no way to predict true positive rate from false positive rate, so they are not related.
However, if you know the actual numbers of true positives and false positives, you can quantify the precision of your classifier which would tell you the fraction of positive classifications that were actually true.
$$Precision = \frac{True Positives}{True Positives + False Positives}$$


text:
Q: Locus of complex number z Let $λ,z_1,z_2,z_3 ∈ \mathbb{C}$ (Complex Numbers) are such that
$$\frac{z_3-z_1}{z_2-z_1} = \lambda.$$
Now if $$λ=e^{it}$$ where  $t ∈ \mathbb{R}$ and $z_2, z_3$ are fixed, then what will be the locus of $z_1$.
NOTE: I am considering complex numbers $z_1, z_2, z_3$ as points on the Argand's Plane.

A: Since, $\dfrac{z_3-z_1}{z_2-z_1}$ is a complex number then it can be expressed as \begin{align*}
\dfrac{z_3-z_1}{z_2-z_1}=\left|\dfrac{z_3-z_1}{z_2-z_1}\right|e^{i\phi}=\dfrac{|\vec{AC}|}{|\vec{AB}|}e^{i\phi} \hspace{1cm}...... (1)
\end{align*}
where we have assumed that, $|z_3-z_1|$ is the distance between point $z_3$ and $z_1$ similarly $|z_2-z_1|$ is defined and named as $AC$ & $AB$ respectively. $\phi$ is the argument of the complex number $\dfrac{z_3-z_1}{z_2-z_1}$. But it will be easy if we consider $\phi$ as the angle between the vector $\vec{AC}$ and $\vec{AB}$. It is given that $$\dfrac{z_3-z_1}{z_2-z_1}=\lambda=e^{it}$$ hence we can say $|\vec{AC}|=|\vec{AB}|$. It means $z_1$ moves in such a way that $t$ is the angle between  $z_3-z_1$ and $z_2-z_1$ and the distance between $z_3-z_1$ and $z_2-z_1$ is equal. Geometrically it is the perpendicular bisector of the line joining $z_3$ and $z_2$. Hence locus of the equation $\dfrac{z_3-z_1}{z_2-z_1}=e^{it}$ is a straight line.


text:
Q: gmaps4rails Float rounding numbers with MySQL i haved a app with gmaps4rails running in development. The last week i upload to production with MySQL DB. All work cool but, searching address, i try to edit some longitude and latitude values and see the numbers appears rounded when i try to edit some location.
I want to know if i can do something like height or precision in float values? Or if is possible work with decimals in this two fields with gmaps4rails? and how can i move the values i have right now in float to the decimal values?
Thank you for you attention.

A: You DB fiels are float, I am almost sure it need to be decimal in MySQL for it to work with gmaps4rails. You should perform a migration to modify your fields
Very important: if you have data you need to protect, you MUST do a full database dump before running the migration, I cannot guarantee you there is no risk to this operation.
As you have the situation in your prod server, additional to the DB dump I would advise to import the prod DB to your dev computer and test the migration here.
The rails migration should look like this:
change_column :my_table, :latitude, :decimal, precision: 10, scale: 8
change_column :my_table, :longitude, :decimal, precision: 11, scale: 8

Replace my_table by your table name, and adjust precision and scale as needed


text:
Q: What is the purpose of packages "provide" and "ifneeded" command in TCL? I Want to know , What is the purpose of packages "provide" and "if-needed" commands in TCL ? Please any body clarify my doubts.
Thanks in Advance.

A: The package provide command goes in the definition code of a package to declare that a particular package with a particular version has been defined.
Here's a trivial example:
namespace eval ::foo {
    proc bar {} {
        puts "this is the bar procedure in the foo namespace"
    }
}
package provide foobar 1.1

The aim is that a package is a higher-level concept than just "oh, here's a bunch of files that you source", even though that's quite possibly how it is implemented.
Some people prefer to put the package provide at the top of the script.

The package ifneeded command is used to supply metadata about a package to Tcl before loading the package itself. It goes inside a script named pkgIndex.tcl (usually) in the same directory as your package implementation, and it is used to say "if you want to use the package with this name and this version, run this script". The final bit you need to know about this is that the package discovery code (run when you ask for a package it doesn't know about) runs the pkgIndex.tcl scripts that it finds in contexts that define the variable dir to be the directory containing the pkgIndex.tcl script that is being run; you don't need to do anything special to relocate the package if you use that convention (which is really convenient).
An example that might match up with the above code:
package ifneeded foobar 1.1 [list source [file join $dir foobar.tcl]]

There is a library command to generate the pkgIndex.tcl scripts for you — pkg_mkIndex — but I don't use it as it's not exactly difficult to write it by hand. (Note also that just because we've implemented the package with just a single Tcl script this time doesn't mean that it has to be done that way. It could also be many scripts, or shared libraries, or a mix of scripts and shared libraries. The user of the package shouldn't have to care about this.)

A: Maybe you just need an example to see how these commands are working.
Building reusable libraries is a good topic in the tcl tutorial which explaines how package ifneeded, provide and require fit in.
https://www.tcl.tk/man/tcl8.5/tutorial/Tcl31.html


text: Q: Extract 2D-image patches for training image and mask used in Semantic Segmentation I was wondering as to what would be my best approach to this problem. I have a 6000-by-6000 image with a 6000-by-6000 mask. I wanted to crop the image into several sub-images before training and came across Extract_Patches_2d in Scikit learn. Looks like the tool to get the job done but I have one issue. If I run this on a single image, how can I be sure that it will use the same patch as a blueprint for the image mask as well ?


text:
Q: Disable setter based on other field value. Annotation I'm trying to disable the value of some fields on a class based on other field value, I want to make it using some kind of annotation or Interceptor.
@Entity
public class Order{

    private String street;

    private boolean sent;

    public void setStreet(String street){
         if(!sent){
              this.street = street;
         }
    }
}

This kind of logic is used in several fields and I'm now looking for a more elegant and clear way of doing this via field or method annotation.
Something like:
@Entity
public class Order{

    @NotSent
    private String street;

    private boolean sent;

    //Or maybe @NotSent
    public void setStreet(String street){
         this.street = street;
    }
}

I think Interceptors may be the way to go but I don`t know how to access other fields values inside it, and also don't know if it is a good idea to surrownd almost every Entity setters with an interceptor because of performance or any other thing.
Sorry for possible spelling or grammar mistakes.


text:
Q: How do I know whether the compiler has ARC support enabled? I need to write a lib in my iOS app.
The statement should be pre-process define as :
myObject ...

#if ARC
   // do nothing
#else
   [myObject release]
#endif

or run-time process as:
if (ARC) {
   // do nothing
} else {
   [myObject release];
}

How can I do?
Please help me! Thank you.

A: You can do it using macros:
#if !defined(__clang__) || __clang_major__ < 3
    #ifndef __bridge
        #define __bridge
    #endif

    #ifndef __bridge_retain
        #define __bridge_retain
    #endif

    #ifndef __bridge_retained
        #define __bridge_retained
    #endif

    #ifndef __autoreleasing
        #define __autoreleasing
    #endif

    #ifndef __strong
        #define __strong
    #endif

    #ifndef __unsafe_unretained
        #define __unsafe_unretained
    #endif

    #ifndef __weak
        #define __weak
    #endif
#endif

#if __has_feature(objc_arc)
    #define SAFE_ARC_PROP_RETAIN strong
    #define SAFE_ARC_RETAIN(x) (x)
    #define SAFE_ARC_RELEASE(x)
    #define SAFE_ARC_AUTORELEASE(x) (x)
    #define SAFE_ARC_BLOCK_COPY(x) (x)
    #define SAFE_ARC_BLOCK_RELEASE(x)
    #define SAFE_ARC_SUPER_DEALLOC()
    #define SAFE_ARC_AUTORELEASE_POOL_START() @autoreleasepool {
    #define SAFE_ARC_AUTORELEASE_POOL_END() }
#else
    #define SAFE_ARC_PROP_RETAIN retain
    #define SAFE_ARC_RETAIN(x) ([(x) retain])
    #define SAFE_ARC_RELEASE(x) ([(x) release])
    #define SAFE_ARC_AUTORELEASE(x) ([(x) autorelease])
    #define SAFE_ARC_BLOCK_COPY(x) (Block_copy(x))
    #define SAFE_ARC_BLOCK_RELEASE(x) (Block_release(x))
    #define SAFE_ARC_SUPER_DEALLOC() ([super dealloc])
    #define SAFE_ARC_AUTORELEASE_POOL_START() NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    #define SAFE_ARC_AUTORELEASE_POOL_END() [pool release];
#endif

The above came from the site: http://raptureinvenice.com/arc-support-without-branches/; but I've pasted it to ensure it's not lost.

A: You can use __has_feature, like so:
#if __has_feature(objc_arc)
// ARC is On
#else
// ARC is Off
#endif

If you want to also build with GCC (Apple's GCC does not support ARC), you may also need the following to determine the compiler:
#if defined(__clang)
// It's Clang
#else
// It's GCC
#endif

Update
Combined, they would take the general form:
 #if defined(__clang)

 #if !defined(__has_feature)
 // idk when clang introduced this
 #error This version of clang does not support __has_feature
 #endif

 #define MON_IS_ARC_ENABLED_IN_THIS_TRANSLATION __has_feature(objc_arc)

 #else
 // for every compiler other than clang:

 #if defined(__has_feature)
 #error Another compiler supports __has_feature
 #endif

 #define MON_IS_ARC_ENABLED_IN_THIS_TRANSLATION 0

 #endif

Then just use MON_IS_ARC_ENABLED_IN_THIS_TRANSLATION in your sources or for further #defines.
If a compiler you use adds support, you would have to add a case for that (and compiler errors would likely catch the error in this case, since it would likely forbid use of ref count ops).
Note that this has extra checks to demonstrate how one can (and should) avoid defining reserved identifiers (based on a conversation in the comments). It's not exhaustive, but a demonstration. If you find yourself writing conditional __has_feature checks often, you may want to define a new macro for that to reduce and simplify definitions.

A: You generally do not want to do things like this:
#if ARC
   // do nothing
#else
   [myObject release]
#endif

Because it's a recipe for disaster, there are many subtle bugs lurking in such code. But if you do have a sane use case for that, you would perhaps be better off with a macro (I didn't know __has_feature, thanks Justin!):
#if __has_feature(objc_arc)
    #define MY_RELEASE(x) while (0) {}
#else
    #define MY_RELEASE(x) [x release]
#endif

But I would be quite nervous to use even this, the pain potential is huge :)


text:
Q: Is there anything I can do within Safari on macOS so that right-click opening a link within SE post to another SE post will open the tab as logged-in This question asks for help using the Safari browser and is not primarily about the Stack Exchange website, though that's part of the context.
When I use Safari in macOS for my Stack Exchange activities which often involve a dozen tabs or more, I'm frustrated that each new window I open by right-clicking on a link to an SE post within an SE post opens a new tag that's not logged in to SE, and I have to re-login again in each new window.
Curiously if I simply click on a linked question in a chat room that I'm already logged into (e.g. this one), it opens a new tab that is already logged in so I know this is possible.

*

*main meta: I can get an already-logged-in window clicking on a post link in chat, but not in another post. I have to re-login a lot; by design? (Safari private)
Question: Is there anything I can do within Safari on mac OS so that right-click opening a link within an SE post to another SE post will open the tab as logged-in?
note: I regularly clear my cookies and decline cookies when I login to SE, and I always use Private Window browsing in Safari. I have Safari 14.0, macOS 10.15.7

A: When you open a new tab, it will not share any cookies (and thus login status) with any other tabs.
When the website opens a new tab, a connection between those tabs exists that allows Javascript to execute across the tabs. This connection is preserved in Private Tabs and also means cookies are shared.
I'm not aware of documentation for this, but it's easy to confirm. If you open GMail and right click to open a new tab, it does not stay logged in. But if you click a link Google configures to open in a new tab, it will stay logged in.


text:
Q: AWS Lambda VPC ENI overflow My Lambda accesses resources on my VPC so as instructed in the documentation I've given the Lambda a role to create network interfaces. I was under the assumption that the ENI is reused but looks like every invocation is creating a new ENI which caused to throw an error
Lambda was not able to create an ENI in the VPC of the Lambda function because the limit for Network Interfaces has been reached.
My role has -ec2:* permissions like it said in the documentation.
Apart from manually deleting these ENIs periodically is there a better way?


text:
Q: Is there a way to avoid null check before the for-each loop iteration starts? Every time I have to iterate over a collection I end up checking for null, just before the iteration of the for-each loop starts. Like this:
if( list1 != null ){
    for(Object obj : list1){

    }
}

Is there a shorter way, so that we can avoid writing the "if" block ?
Note: I am using Java 5, and will be stuck with it for sometime.

A: If possible, you should design your code such that the collections aren't null in the first place.
null collections are bad practice (for this reason); you should use empty collections instead. (eg, Collections.emptyList())
Alternatively, you could make a wrapper class that implements Iterable and takes a collections, and handles a null collection.
You could then write foreach(T obj : new Nullable<T>(list1))

A: How much shorter do you want it to be? It is only an extra 2 lines AND it is clear and concise logic.
I think the more important thing you need to decide is if null is a valid value or not. If they are not valid, you should write you code to prevent it from happening. Then you would not need this kind of check. If you go get an exception while doing a foreach loop, that is a sign that there is a bug somewhere else in your code.

A: 1) if list1 is a member of a class, create the list in the constructor so it's there and non-null though empty.
2) for (Object obj : list1 != null ? list1 : new ArrayList())

A: public <T extends Iterable> T nullGuard(T item) {
  if (item == null) {
    return Collections.EmptyList;
  } else {
    return item;
  }
}

or, if saving lines of text is a priority (it shouldn't be)
public <T extends Iterable> T nullGuard(T item) {
  return (item == null) ? Collections.EmptyList : item;
}

would allow you to write
for (Object obj : nullGuard(list)) {
  ...
}

Of course, this really just moves the complexity elsewhere.

A: It's already 2017, and you can now use Apache Commons Collections4
The usage:

for(Object obj : CollectionUtils.emptyIfNull(list1)){
    // Do your stuff
}

A: I guess the right answer is that: there is no way to make it shorter. There are some techniques such as the ones in the comments, but I don't see myself using them. I think it's better to write a "if" block than to use those techniques. and yes.. before anybody mentions it yet again :) "ideally" the code should be desgined such that list should never be a null

A: Another Java 8+ way would be to create a forEach method that does not crash when using a null value:
public static <T> void forEach(Iterable<T> set, Consumer<T> action) {
    if (set != null) {
        set.forEach(action);
    }
}

The usage of the own defined foreach is close to the native Java 8 one:
ArrayList<T> list = null;

//java 8+ (will throw a NullPointerException)
list.forEach(item -> doSomething(...) );

//own implementation
forEach(list, item -> doSomething(...) );

A: In Java 8 there is another solution available by using java.util.Optional and the ifPresent-method.
Optional.ofNullable(list1).ifPresent(l -> l.forEach(item -> {/* do stuff */}));

So, not a solution for the exact problem but it is a oneliner and possibly more elegant.

A: Null check in an enhanced for loop
public static <T> Iterable<T> emptyIfNull(Iterable<T> iterable) {
    return iterable == null ? Collections.<T>emptyList() : iterable;
}

Then use:
for (Object object : emptyIfNull(someList)) { ... }

A: Apache Commons
for (String code: ListUtils.emptyIfNull(codes)) {

}

Google Guava
for (String code: Optional.of(codes).get()) {

}


text:
Q: runningApplications deprecated in Mavericks, or what? Compiling the same project under OSX 10.8.5 and 10.9, I have found that runningApplications does not work with the same function as mentioned below:
-(void)killProcessesNamed:(NSString*)appName
{
for ( id app in [[NSWorkspace sharedWorkspace] runningApplications] )
{
    if ( [appName isEqualToString:[[app executableURL] lastPathComponent]] )
    {
        [app terminate];
    }
}

}
Looking at NSRunningApplication.h I've found this:
- (NSArray *)runningApplications NS_AVAILABLE_MAC(10_6);

I do not know if it is really deprecated, but I get a warnings about multiple ambiguous method found in NSRunningApplication.h and also in NSTask.h both regarding:
- (BOOL)terminate; // in NSRunningApplication.h
- (void)terminate; // in NSTask.h

therefore the warning disappears if I change terminated in forceTerminate:
//[app terminate];
[app forceTerminate];

The problem is that in Mavericks does not want to kill the process/app indicated.
To be more clear, the above warning appears only if the project is under ARC.
thanks


text:
Q: How to create and add nested object into nested field in Elasticsearch? https://www.elastic.co/guide/en/elasticsearch/reference/current/nested.html
Consider:
PUT my_index
{
  "mappings": {
    "_doc": {
      "properties": {
        "user": {
          "type": "nested"
        }
      }
    }
  }
}

PUT my_index/_doc/1
{
  "group" : "fans",
  "user" : [
    {
      "first" : "John",
      "last" :  "Smith"
    },
    {
      "first" : "Alice",
      "last" :  "White"
    }
  ]
}

When I run a painless script like:
ctx._source.user.add({
    "first" : "Foo",
    "last" : "Bar"
})

It is not working. I tried but cannot find any related documents or discussion started by other.

A: POST my_index/_doc/1/_update
{
   "script": {
      "lang": "painless",
      "inline": "ctx._source.user.add(params.object)",
      "params": {
         "object": {
            "first" : "Foo",
            "last" : "Bar"
         }
      }
   }
}

A: https://www.elastic.co/guide/en/elasticsearch/reference/5.4/modules-scripting-painless-syntax.html#painless-maps
You can create a map like ['first': 'Foo', 'last': 'Bar', 'sthElse': 100] then add it.
So:
ctx._source.user.add([
    "first" : "Foo",
    "last" : "Bar"
])

Please note that map in painless can be mixed type.


text:
Q: Java Arrays to show only an exact value from 2 arrays Hello i'm a student and i've just started studying java, and i have a problem with an exercise, the first thing i had to make was two arrays to show how many days each month has, but now i have to make another exercise in which i only have to display the months that has 31 days. can you explain me how to display that?
class Main {
    public static void main(String[] args) {
        int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
        String months[] = {"Ianuarie ", "Februarie ", "Martie ", "Aprilie ", "Mai ", "Iunie ", "Iulie ", "August ", "Septembrie ", "Octombrie ", "Noiembrie  ", "Decembrie "};
        {
            int i;
            for (i = 0; i < 12; i++) {
                System.out.println(months[i] + month_days[i] + " zile.");
            }
        }
        {
            int i;
            for (i = 0; i < 12; i++) {
                System.out.println((month_days[i]));
            }
        }
    }
}

A: You should use an if condition to check which month has 31 days and print it accordingly.
Code
public class Main {
    public static void main(String[] args) {
         int month_days[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
         String months[] = {"Ianuarie ", "Februarie ", "Martie ", "Aprilie ", "Mai ", "Iunie ", "Iulie ", "August ", "Septembrie ", "Octombrie ", "Noiembrie  ", "Decembrie "};

         System.out.println("Printing all the Months and days for each months.....");
         int i;
         for (i = 0; i < 12; i++) {
                 System.out.println(months[i] + month_days[i] + " zile.");
         }

         System.out.println("printing Months having 31 days only .....");
         for (i = 0; i < 12; i++) {
             if(month_days[i] == 31) {
                 System.out.println(months[i] + " has " + month_days[i] + " days");
             }
         }
     }
}

Output :
Printing all the Months and days for each months.....

Ianuarie 31 zile.
Februarie 28 zile.
Martie 31 zile.
Aprilie 30 zile.
Mai 31 zile.
Iunie 30 zile.
Iulie 31 zile.
August 31 zile.
Septembrie 30 zile.
Octombrie 31 zile.
Noiembrie  30 zile.
Decembrie 31 zile.

printing Months having 31 days only .....

Mai  has 31 days
Iulie  has 31 days
August  has 31 days
Octombrie  has 31 days
Decembrie  has 31 days

A: I strongly recommend you learn java language from https://docs.oracle.com/javase/tutorial/java/nutsandbolts/index.html before you can understand what I have written.
These are having key concepts:
Control Flow Statements, Expressions, Statements, and Blocks
public class Main {
public static void main(String argv[]) {
        int month_days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
        String months[] = { "Ianuarie ",
                            "Februarie ",
                            "Martie ",
                            "Aprilie ",
                            "Mai ",
                            "Iunie ",
                            "Iulie ",
                            "August ",
                            "Septembrie ",
                            "Octombrie ",
                            "Noiembrie  ",
                            "Decembrie " };
        int i;
        System.out.println("Months with 31 zile.");
        for (i = 0; i < 12; i++) {
            if (month_days[i] == 31) {
                System.out.println(months[i] + month_days[i] + " zile.");
            }
        }
        System.out.println("Months with less than 31 zile.");
        for (i = 0; i < 12; i++) {
            if (month_days[i] != 31) {
                System.out.println(months[i] + month_days[i] + " zile.");
            }
        }
    }
}


text:
Q: Proof of theorem about direct sum
Let $W_1$ and $W_2$ be subspaces of a vector space $V$
Prove that $V$ is the direct sum of $W_1$ and $W_2$ if and only if each vector in $V$ can be uniquely written as $x_1+x_2$, where $x_1 \in W_1$ and $x_2 \in W_2$

Question 1
"If each vector in $V$ can be uniquely written as $x_1 + x_2$" = $\forall v \in V \exists ! x_1 \in W_1 \exists ! x_2 \in W_2(v=x_1+x_2)$
When $V = W_1 = W_2 = \{0\}$,
$\forall v \in V \exists ! x_1 \in W_1 \exists ! x_2 \in W_2(v=x_1+x_2)$ is true?
$0 \in V = 0 \in W_1 + 0 \in W_2$
$0 \in V = 0 \in W_2 + 0 \in W_1$
So I think it is false but it seems true so very confusing.

Question 2

If $V = W_1 \oplus W_2$ and some vector $y \in V$ can be represented as $y = x_1 + x_2 = x_1' + x_2'$, where $x_1, x_1′ \in W_1$ and $x_2, x_2' \in W_2$, then we have $x_1 − x_1′ \in W_1$ and $x_1 − x_1' = x_2 + x_2′ \in W_2$. But since $W_1 \cap W_2 = \{0\}$, we have $x_1 = x_1'$ and $x_2 = x_2'$
Conversely, if each vector in $V$ can be uniquely written as
$x_1 + x_2$, then $V = W_1 + W_2$. Now if $x \in W_1 \cap W_2$ and $x \neq 0$, then we have
that $x = x + 0$ with $x \in W_1$ and $0 \in W_2$ or $x = 0+x$ with $0 \in W_1$ and $x \in W_2$,
a contradiction.

I think this part

If each vector in $V$ can be uniquely written as
$x_1 + x_2$, then $V = W_1 + W_2$.

is wrong because of counterexample: $V=\{0, 1, 2\}, W_1=\{0, 1\}, W_2=\{0, 2\} (3 \notin V)$
I think that part is wrong because
$W_1+W_2=\{x+y:x \in W_1,y \in W_2\}, V=\{v:\forall v \exists ! x_1 \in W_1 \exists ! x_2 \in W_2(v=x_1+x_2)\}$
$W_1+W_2 \neq V$ because $W_1+W_2 \nsubseteq V$
Is this correct?


text:
Q: What is a "suburban valley (belly) street"? I heard in the movie description of the film The 40-Year-Old Virgin:

In a helmet, he pedals his mirror-equipped bike along a suburban belly street.

The scene shows the protagonist pedaling a bike in a quiet and scenic neighborhood, along a straight residential street lined with trees. It does not make much sense to me. Does belly street mean anything? It could also be "valley street". It doesn't sound like a proper name to me either. As far as I can find, the setting doesn't specify a city/state. I am putting the audio clip here for reference.

A: "Belly street" doesn't mean anything to me. She says "valley".
A suburban valley street
I thought it was a strange expression, but I guess they wanted you to imagine a street in a suburb in a valley.
A suburban Valley street
There is a possibility that it is, in fact, proper. Since you told us the movie, it turns out the movie was filmed mostly in the San Fernando Valley, according to IMDb. The San Fernando Valley is colloquially known as "the Valley". If the writers of the audio description were aware of this, they might have meant it as a suburban Valley street: a street in the (San Fernando) Valley typical of one of its suburbs.


text:
Q: Curl static compilation problem (X509_NAME) on Windows with BoringSSL 1.1.0 I have a recent problem when I try to compile Curl static lib on windows with BoringSSL. The above commands where working fine 6 months ago, but with latest versions of Curl and BoringSSL I came into an issue in the nmake command.
What I'm doing:
call buildconf.bat

cd "winbuild"

set RTLIBCFG=static
set _CL_=-MTd -Ob0 -Od -Zi -FS

call nmake /NOLOGO /X - /F MakeFile.vc VC=16 mode=static MACHINE=x64 DEBUG=yes WITH_PREFIX="C:/cpplibs/Curl" WITH_SSL=static SSL_PATH="C:/cpplibs/BoringSSL" ENABLE_SSPI=yes ENABLE_IPV6=yes ENABLE_IDN=yes ENABLE_WINSSL=no

What I face with in console output:
Generating prerequisite files
* C:\cpplibs\Sources\Curl\latest\Makefile
* C:\cpplibs\Sources\Curl\latest\src\tool_hugehelp.c
configuration name: libcurl-vc16-x64-release-static-ssl-static-ipv6-sspi

cl /O2 /DNDEBUG /MT /DCURL_STATICLIB /I. /I ../lib /I../include /nologo /W4 /EHsc /DWIN32 /FD /c /DBUILDING_LIBCURL /DUSE_OPENSSL /I"C:/cpplibs/BoringSSL"  /DUSE_WIN32_IDN /DWANT_IDN_PROTOTYPES  /DUSE_IPV6  /DUSE_WINDOWS_SSPI /Fo"..\builds\libcurl-vc16-x64-release-static-ssl-static-ipv6-sspi-obj-lib/altsvc.obj"  ..\lib\altsvc.c
altsvc.c

... 100+ successfull calls

cl /O2 /DNDEBUG /MT /DCURL_STATICLIB /I. /I ../lib /I../include /nologo /W4 /EHsc /DWIN32 /FD /c /DBUILDING_LIBCURL /DUSE_OPENSSL /I"C:/cpplibs/BoringSSL"  /DUSE_WIN32_IDN /DWANT_IDN_PROTOTYPES  /DUSE_IPV6  /DUSE_WINDOWS_SSPI /Fo"..\builds\libcurl-vc16-x64-release-static-ssl-static-ipv6-sspi-obj-lib/vtls/openssl.obj"  ..\lib\vtls\openssl.c
openssl.c

C:/cpplibs/BoringSSL/openssl/base.h(362): error C2059: syntax error: '<parameter-list>'
C:/cpplibs/BoringSSL/openssl/x509.h(154): error C2059: syntax error: '<parameter-list>'
C:/cpplibs/BoringSSL/openssl/x509.h(154): error C2143: syntax error: missing ')' before '('
C:/cpplibs/BoringSSL/openssl/x509.h(154): error C2059: syntax error: ')'
C:/cpplibs/BoringSSL/openssl/x509.h(154): error C2143: syntax error: missing ')' before 'constant'
C:/cpplibs/BoringSSL/openssl/x509.h(154): error C2091: function returns function
...
C:/cpplibs/BoringSSL/openssl/x509_vfy.h(508): error C2061: syntax error: identifier 'X509_STORE_get_lookup_crls'
C:/cpplibs/BoringSSL/openssl/x509_vfy.h(508): error C2059: syntax error: ';'
C:/cpplibs/BoringSSL/openssl/x509_vfy.h(508): error C2059: syntax error: '<parameter-list>'

C:/cpplibs/BoringSSL/openssl/x509_vfy.h(508): fatal error C1003: error count exceeds 100; stopping compilation

NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.26.28801\bin\HostX64\x64\cl.EXE"' : return code '0x2'
Stop.
NMAKE : fatal error U1077: '"C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\VC\Tools\MSVC\14.26.28801\bin\HostX64\x64\nmake.exe"' : return code '0x2'
Stop.

So I've investigated, and all the errors at the indicated lines seems to have in common the X509_NAME typedef usage, but the definition is correct in openssl/base.h:
typedef struct X509_name_st X509_NAME;

And in openssl/x509.h:
struct X509_name_st {
    STACK_OF(X509_NAME_ENTRY) * entries;
    int modified;  // true if 'bytes' needs to be built
    BUF_MEM *bytes;
    //  unsigned long hash; Keep the hash around for lookups
    unsigned char *canon_enc;
    int canon_enclen;
} /* X509_NAME */;

Furthermore the file ..\lib\vtls\openssl.c in Curl lib includes <openssl/x509v3.h> that includes <openssl/x509.h> that includes <openssl/base.h> ... So everything should be OK, but it's not.
Is there something missing in my commands ?


text:
Q: 2D FFT of a plane wave with changing spatial frequencies I was trying to simulate the frequency spectrum of a 2D tilted plane wave with changing spatial frequencies (looks like a grating). According to the property of 2D FFT: FFT(exp(j*2pi*(ax+by)))=δ(fX-a, fY-b) , if we change the frequency component a and b step by step, its FFT (looks like a focus spot) is supposed to scan in the spectrum plane.
The raster scanning of the focus spot is wanted. However, it looks like the scanning behaves not as wanted, although a and b changes in a two for-loop way. The attached gifenter image description here only shows a few frames of the simulation and you can run the attached code for complete result.
It seems that the actual center frequency of the grating should be consistent with the sampling frequency used here? Has anyone could help me to figure it out? Thanks in advance.
input_dim = 50;
input_num = input_dim^2;

[u, v] = meshgrid(1:input_dim, 1:input_dim);

Su = 1/input_dim:1/input_dim:1;  %sampling frequency
Sv =  1/input_dim:1/input_dim:1;

%% Grating: tilted plane wave

figure('position', [200 250,1000 400]),
G = zeros(input_dim, input_dim, input_num);

for i = 1:input_num
    [fvi, fui] = ind2sub([input_dim, input_dim], i);

    G(:, :, i) = exp(1i * (fui*u + fvi*v));
    F_G = fft2(G(:, :, i));
    subplot(121), imagesc(1:input_dim, 1:input_dim, real(G(:, :, i))), colormap(gray)
    subplot(122), imagesc(Su, Sv, abs(F_G)), colormap(gray)

    pause(0.1)
end


text:
Q: C functions with two round brackets pairs? I'm sorry for the bad title, but nothing better came to my mind apart from "I don't understand this code". Please, feel free to propose a modification.
I'm reading this code. I've never seen a C function like this one:
static void
VL_XCAT(_vl_vlad_encode_, SFX)
(TYPE * enc,
 TYPE const * means, vl_size dimension, vl_size numClusters,
 TYPE const * data, vl_size numData,
 TYPE const * assignments,
 int flags)
{
    // function body
}

In particular I'm confused by (_vl_vlad_encode_, SFX). Up to know, all the functions headers that I've seen had only one "pair of round brackets" (the function's parameters), while here there are two pairs.
What does it mean the first one? I think that this is linked to later calls _vl_vlad_encode_f and _vl_vlad_encode_d, which don't appears anywhere else in the library code, but I can't understand how they're connected.

A: VL_XCAT is a macro usually used to concatenate two tokens. (A ## B) which means it'll create a token from both arguments which is:
_vl_vlad_encode_
and
SFX - is probably define for type of floating point variable used (double/float)
I would say this'll choose between double and float function to use and use _vl_vlad_encode_f  or _vl_vlad_encode_d based on defines.
So if
#define SFX d

it'll create _vl_vlad_encode_d after processing this line.

A: The VL_XCAT and VL_CAT function-like macros are in vl/host.h (same directory as the vlad.c file you linked).
VL_CAT(x,y) simply concatenates its arguments and VL_XCAT(x,y) is the same, except its arguments are macro-eXpanded:
#define VL_CAT(x,y) x##y
#define VL_XCAT(x,y) VL_CAT(x, y)

VL_XCAT(_vl_vlad_encode_, SFX) results in _vl_vlad_encode_f or _vl_vlad_encode_d, depending on how SFX is defined.
So you end up with this, for example, when #define SFX d is used (note that #define TYPE double is active at the same time):
static void
_vl_vlad_encode_d
(double * enc,
 double const * means, vl_size dimension, vl_size numClusters,
 double const * data, vl_size numData,
 double const * assignments,
 int flags)
{
    // function body
}

Looks like a normal function definition now, doesn't it?


text:
Q: Setting up ivy local repository in eclipse I am having a little trouble setting up my ivy local repository in my eclipse workspace.
I have created the local repository in my ivysettings.
<property name="ivy.local.repo.dir" value="${ivy.default.ivy.user.dir}/local" override="false"/>

<resolvers>
...
<filesystem name="local" changingPattern="${changing.pattern}">
            <ivy pattern="${ivy.local.repo.dir}/${local.ivy.pattern}" />
            <artifact pattern="${ivy.local.repo.dir}/${local.artifact.pattern}" />
        </filesystem>

...

</resolvers>

I have IvyDE installed on my eclipse which creates an "ivy.xml" folder (similar to referenced libraries). If I want to create a local repository directory do I need to create the "local" folder within "ivy.xml" directory and put my jars in there?
I don't quite understand where I can put my private jars in my eclipse workspace so ivy can resolve them.

A: The filesystem resolver is very flexible.
I normally use it as follows, the "myrepo" directory is found relative to the location of the ivysettings file:
<filesystem name="myrepo1">
    <ivy pattern="${ivy.settings.dir}/myrepo/[organisation]/[module]/ivy-[revision].xml" />
    <artifact pattern="${ivy.settings.dir}/myrepo/[organisation]/[module]/[artifact]-[revision].[ext]" />
</filesystem>

In this second example the "myrepo" directory is relative to the ivy file:
<filesystem name="myrepo2">
    <ivy pattern="${ivy.basedir}/myrepo/[organisation]/[module]/ivy-[revision].xml" />
    <artifact pattern="${ivy.basedir}/myrepo/[organisation]/[module]/[artifact]-[revision].[ext]" />
</filesystem>

Notes:

*

*I like this explicit approach of naming the relative location of the directory used to host the repo. Relying on the ivy defaults can be confusing.

*Same point for the file patterns. Demonstrates how flexible ivy is for hosting artifacts.

*Using the first approach is more flexible because you can use the settings task within your build to specify an alternative location for the ivysettings file.


text:
Q: How to make a javascript link bookmarkable I have several links on a page whereby I will like them to be distinguishable and bookmark able. eg.
On if I have a contact.php on that page I have several jQuery click events bonded to a link such that www.mywebsite.com/contact.php#accountant , www.mywebsite.com/contact.php#developer. When I click the links jQuery works.
But when I enter the links in a browser www.mywebsite.com/contact.php#accountant it does not take me straight to the accountant's contact details, rather I'm having to click the accountants contact again.
The page I'm working with is here
I hope I was able to explain my problem. Thanks.
UPDATE
$('#contact' + $('a[href="'+window.location.hash+'"]').get(0).className.replace('contact', '') ).fadeIn(3000);

to main.js file on the website, but still not working

A: On page load read the window.location.hash, if it has a value, run your code.

A: For this, you need to capture the search string of your address. For this, you can do this way:
if(window.location.hash) {
  // Based on this, you need to activate the div.
  // This depends on the script you use.
} else {
  // Fragment doesn't exist
}

A: You can use the following code inside your $(document).ready(function(){...}); but not inside the any click event in your js/main.js file:
var numb = $('a[href="'+window.location.hash+'"]').get(0);
if (numb != undefined) {
  numb = numb.className.replace('contact', '');
  $('#contact' + numb).fadeIn(3000);
}

This is essentially the same as line 23 in your main.js file - apart from that it will look for an anchor with a href that contains the window.location.hash, uses .get(0) to grab the actual DOM element, grabs the className and cleans out the contact part, using the value in place of where you originally used the numb var, then fading it in.


text:
Q: APK does not install on device I've recently copy and paste an old android application project in Eclipse. Thereafter I made some changes to the project including refactor>rename the project, both the project name and the package name as well. All seems ok so far when running this modified duplicate project in the emulator without any problems.
But when I tried to run it on my device (from Eclipse), it does not work, as the original old android application project is installed on the device.
Eclipse prompts 'Re-Installation failed due to different application signatures. You must perform a full uninstall of the application. WARNING: This will remove the application data! Do you want to uninstall?'
I didn't.
But I exported an unsigned apk of the duplicate modified project and tried to install it on the device and it fails again. I uninstall the old application and tried reinstalling the duplicate modified project, and it fails again.
I'm not sure why as the project name and package names are different from the original. Also, I notice the duplicate modified project is nearly 40Mb compared to the original of only 8MB. If its a copy of the original (plus some minor changes, which are really reductions actually), how did it get so large? I checked that in the folders of the duplicate modified project, I saw that its dexlibs folder has the original APK of the original project (with the original project name and package name) in it. I did some research online and they say to ignore it.
In the APK of the duplicate modified project, surely enough, it is, as expected, smaller that the original version APK. But how come it doesn't install, and in installing, it still uses the name of the original projects package name instead of the new duplicate modified name?
Please help.

A: You have to remove the app from device and run again.

A: It appears you're trying to install a duplicate app with a different signature on the same device. You either need to make the app "different," that is, change the package name (in Eclipse, under Android Tools/Rename Application Package); or you need to find the same key you've used before to sign the app -- this may well be a debug key, and it's most likely expired now.
If you change the package name, the new version of the app will not have access to the data from the old version of the app. If you find the old key, and it's expired, you might be able to coax Android into accepting it by setting the date on the PC and the device back.

A: All you need is run below commands in your command shell
make sure adb path is set in your system PATH
adb uninstall your_package_name
adb install path_to_apk


text:
Q: Primefaces Filter outside tag  Please tell me, how to put the filter outside of the tag
I make so:
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
            xmlns:ui="http://java.sun.com/jsf/facelets"
            xmlns:h="http://java.sun.com/jsf/html"
            xmlns:f="http://java.sun.com/jsf/core"
            xmlns:p="http://primefaces.org/ui">

<h:form id="InventListForm">
    <p:panel header="#{myBundle.ListInventTitle}">
        <f:facet name="header">
            <p:outputPanel>
                <h:outputText value="Search: " />
                <p:inputText id="globalFilter" onkeyup="InventList.filter()" style="width:150px" />
            </p:outputPanel>
        </f:facet>
        <p:dataTable id="datalist" resizableColumns="true" value="#{inventController.items}" var="item"
                     widgetVar="InventList" selectionMode="single" selection="#{inventController.selected}"
                     rowKey="#{item.id}"
                     paginator="true"
                     rows="10"
                     rowsPerPageTemplate="10,20,30"
                     >

            <p:ajax event="rowSelect"   update="createButton viewButton editButton deleteButton"/>
            <p:ajax event="rowUnselect" update="createButton viewButton editButton deleteButton"/>

but the filter does not work
Table I generated by the Primefaces CRUD generator


text:
Q: Received "The process cannot access the file because it is being used by another process" when creating .zip file using ZipFile I am trying to create a large .zip file using the ZipFile library in C#.
Multiple music files are downloaded from URL by HttpClient and added in the zip loop.
For that, I follow for-loop > HttpClient to download music > add in zip > save zip.
Here, 30-35 music files will work perfectly. But i faced an issue when i have more than 35+ files. I want to create zip with minimum 500+ files.
I have an exception stored in logfile.txt.
The exception:
Action:The process cannot access the file because it is being used by another process.  Controller:   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.File.InternalMove(String sourceFileName, String destFileName, Boolean checkHost)
   at Ionic.Zip.ZipFile.Save()
   at Groove.Libraries.Api.DonwloadMusic.<>c__DisplayClass5_0.<DownloadMusicFilesByScheduler>b__2(StudioEventEntryDetailsResponseModel y)
   at System.Collections.Generic.List`1.ForEach(Action`1 action)
   at Groove.Libraries.Api.DonwloadMusic.<>c__DisplayClass5_0.<DownloadMusicFilesByScheduler>b__0(StudioMusicDetails x)
   at System.Collections.Generic.List`1.ForEach(Action`1 action)
   at Groove.Libraries.Api.DonwloadMusic.DownloadMusicFilesByScheduler()

Exception is thrown by zip.Save(string.Format("{0}/{1}", tempPath, archiveFileName)); line.
Is there any problem with WebRequest or ZipFile Library?.
    // Get list of music files url
    EventMusicList eventEntryList = _globLib.GetEventMusicList(dbEvent.Id);

    // zip file name
    string archiveFileName = string.Format("{0}-{1}-Music.zip", eventEntryList.SeasonName,eventEntryList.EventName);

    ZipFile zip;

    // if zip Exists then get zip and add new music in this file OR create new zip
    if (File.Exists(string.Format("{0}/{1}", tempPath, archiveFileName)))
    {
          zip = new ZipFile(string.Format("{0}/{1}", tempPath, archiveFileName));
    }
    else
    {
          zip = new ZipFile();
    }

    // Start : Looping of music files url
    eventEntryList.StudioList.ForEach(
        x => x.EntryList.ToList().Where(y => y.Document.Id != 0 && !y.Document.IsDownloaded).ToList().ForEach(y =>
        {

           // get music file url from dropbox.
           DBB.GenerateAccessToken();
           var _link = DBB.GetFileTemporaryLink(y.Document.RootPath, y.Document.FileName);

           if (!_link.Equals(string.Empty))
           {
               // Get Stream from music url - function is created at bottom
               Stream stream = GetStreamFromUrl(_link);

               string fileExtension = Path.GetExtension(y.Document.FileUrl);
               string fileName = y.EntryNumber != null
                   ? string.Format("{0}-{1}{2}", y.EntryNumber, y.Title, fileExtension)
                   : string.Format("{0}{1}", y.Title, fileExtension);
               if (zip.Entries.Where(z => z.FileName == fileName).Count() == 0)
               {
                   // add in zip
                   zip.AddEntry(fileName, stream);
               }
           }
           else
           {
               return;
           }

       // Check temporary path is exist or not, if not then create temporary folder
       if (!Directory.Exists(tempPath))
       {
           Directory.CreateDirectory(tempPath);
       }

       this.LogRequest("Save:-BeforeSave", "DownloadMusicLib");

       //Task t = Task.Run(() => { zip.Save(string.Format("{0}/{1}", tempPath, archiveFileName)); });
       //t.Wait();

       // Save zip file
       zip.Save(string.Format("{0}/{1}", tempPath, archiveFileName));

       this.LogRequest("Save:-AfterSave", "DownloadMusicLib");

    })); // END : Looping of music files url

    // New function to get stream from url
    public static Stream GetStreamFromUrl(string url)
    {
        byte[] imageData = null;
        Stream ms;
        ms = null;
        try
        {
            using (var wc = new System.Net.WebClient())
            {
                imageData = wc.DownloadData(url);
            }
            ms = new MemoryStream(imageData);
        }
        catch (Exception ex)
        {
            //forbidden, proxy issues, file not found (404) etc
        }
        return ms;
    }

Screenshot of zip folder location, some are currepted
Here, I am getting temporary music file url from dropbox and get stream by using HttpClient.
When error occurs, zip file is courrpt. like '2018 - 2019-Washington IL Regional Competition-Music.zip.ugmf5uat.1a4'


text:
Q: Registry Php Example I have this code which I came across in reading and when I view it in a browser it does not cause any errors. My question is how can the class call $this->registry without the property being set. In other words what is the $this->registry within the function referring to?
class Template{

public function __construct($registry){
    $this->registry = $registry;
}

}
this is how I instantiate the classes.
<?php
include 'registry.class.php';
include 'template.class.php';
$registry = new Registry();
$template = new Template($registry);
?>

A: You're basically referencing the Registry object. Look at it this way:
function __construct(Registry $registry) {
    $this->registry = $registry;
}

Referencing $this->registry is calling the Templates "copy" of the Registry object. So when you pass the $registry object to the Template with:
$template = new Template($registry);

You're basically "giving" the Template class its own $registry object.
I've used a similar registry before. Where you can instantiate it like this:
$registry = new registry();
$registry->template = new template($registry);

Allowing you to access Template methods/vars/etc via the registry:
$registry->template->method();

There will be somebody who can explain the exact happenings a lot better than I can right now, but remember, the best way to learn is by trial and error. Learn from your mistakes :-)

As per the comments, your Template class should look like this:
class Template {

    var $registry;

    function __construct($registry) {
        $this->registry = $registry;
    }
}

That will allow you to access it throughout the class.
Example:
function link($url){
    return $this->registry->site->link($url);
}

The above is a fictional function and the reference to site is also fictional but shows how you could use this class and/or registry.

A: -> is for accessing object fields. So you are setting an object field called registry in the constructor for Template to the value of $registry, which is passed to the constructor. Think for this->registry as referring to a variable registry in the object Template.


text:
Q: What's $\nabla \cdot [k \cdot \nabla T]$ formulation in Laplace's eq. really? What's $\nabla \cdot [k \cdot \nabla T]$ formulation in Laplace's eq. really?
(https://en.wikiversity.org/wiki/Introduction_to_finite_elements/Weak_form_of_heat_equation)
I read that this is like
$$\left(\frac{d}{dx_1}, \frac{d}{dx_2}, ...\right) \cdot \bigg[ k \cdot \bigg(\frac{dT}{dx_1}, \frac{dT}{dx_2},... \bigg) \bigg]$$
The inner dot product can be expanded as:
$$k\frac{dT}{dx_1}+k\frac{dT}{dx_2}+...$$
Then one takes the outer dot product to get:
$$\frac{d}{dx_1}k\frac{dT}{dx_1}+\frac{d}{dx_2}k\frac{dT}{dx_2}+...$$
Since $k$ is constant and $\frac{d}{dx_i}$ is the conventional derivative. Then since derivative is linear operator, then one can move the constant to the front?
And then then this formulation is actually equivalent to:
$$k\nabla^2T$$
Am I right?
But what's the reason for using the formulation $\nabla \cdot [k \cdot \nabla T]$?

A: In the more general problem, $k$ can be a function of space, at which point $\nabla\cdot[k\nabla T] \ne k\nabla^2T$
It's also possible that $k$ is meant to be a tensor quantity (and thus should be written $\mathbf{k}$), so $\nabla\cdot[\mathbf{k}\cdot\nabla T]$ is really the only way of writing it. In particular, your statement that the inner dot product can be expanded as
$$
k\frac{dT}{dx_1}+k\frac{dT}{dx_2}+...
$$
is incorrect. For starters, it is clear this is wrong because this is a scalar quantity, not a vector one, and the divergence operator takes a vector argument. The correct expansion, taking into account $\mathbf{k}$'s tensor nature, is
$$
\left(k_{11}\frac{\partial T}{\partial x_1} + k_{12}\frac{\partial T}{\partial x_2} + ...\right)\hat{\mathbf{x}}_1 + \left(k_{21}\frac{\partial T}{\partial x_1} + k_{22}\frac{\partial T}{\partial x_2} + ...\right)\hat{\mathbf{x}}_2 + ...
$$
If $\mathbf{k}$ is constant, then the divergence can be expanded as
$$
k_{11}\frac{\partial^2 T}{\partial x_1^2} + k_{12}\frac{\partial ^2T}{\partial x_1\partial x_2} + ... + k_{21}\frac{\partial T}{\partial x_2 \partial x_1} + k_{22}\frac{\partial T}{\partial x_2^2} + ... + ...
$$
which is not equal to $k\nabla^2T$ for any scalar $k$.

A: Eyeballfrog has a good answer. K (or $\bf \kappa$) is likely a tensor of conduction, especially as it is bold and other non-scalar quantities also seem to be. The tensor contains information like in which orientation is there how much conductance at this point and (complementarily) which orientation do we have good heat insulation.

I would also like to add that $\nabla^2$ is not very good notation. We need to know if gradient is applied as inner or outer product. If it is outer+inner (expansion+contraction) then it is Laplacian, but it can also be outer+outer and then it would be more like a Hessian.


text:
Q: React GET form data on submit I'm new to React and I've been facing a problem since few hours now. Even if I found some topics on Stackoverflow or Google that seems equivalent to my issue, I'm unable to solve it...
I'm using react-select to create a simple form. For now, I have only one multi-select input. I am able to use it as expected but when I press "Submit" I want to retrieve the values selected. I tried with refs, with onChange without success. onChange is never fired, that might be an other issue as well.
var MultiSelect = React.createClass({
    onLabelClick: function (data, event) {
        console.log(data, event);
    },

    render: function() {
      var ops = []

      this.props.categories.forEach(function(category) {
      ops.push({ label: category.name, value: category.id });
    });

        return (

                <Select
                    name = {this.props.name}
                    delimiter=" "
                    multi={true}
                    allowCreate={true}
                    placeholder = {this.props.label}
                    options={ops} />

        );
    }
});

var ProductForm = React.createClass({
  submit: function () {
    console.log("Categories: " + this.state.categories);
  },

  onCategoryChange: function(e) {
    console.log("CATEGORY CHANGED !!!!!!")
    this.setState({categories: e.target.value});
    },

  render: function () {
    return (
      <form onSubmit={this.submit}>
        <MultiSelect label="Choose a Category" name="categories" categories={this.props.categories} onChange={this.onCategoryChange}/>
        <button type="submit">Submit</button>
      </form>
    );
  }
});

PS : data categories comes from a Rails controller.

A: I believe your internal Select component should receive onChange from the props provided to MultiSelect, assuming your intention is to listen to changes on the Select component.
Try something like this inside your MultiSelect's render() method:
return (

        <Select
            name = {this.props.name}
            delimiter=" "
            multi={true}
            allowCreate={true}
            placeholder = {this.props.label}
            options={ops}
            onChange={this.props.onChange} />

);

Side note, I don't think e.target.value is going to work inside onCategoryChange, since react-select doesn't send standard events.


text:
Q: How can I set up my iphone to play sounds only when plugged in or an alarm is going off? I just got an iPhone 5 with iOS 6 and am struggling with all the different sound/vibration settings.  It seems like there are so many different ways to control this (up/down buttons on the left of the phone, the on/off toggle on the left, Settings --> Sound, and individual in-app settings).
Ideally what I want is for the phone to be silent (vibrate only) all of the time, except when:

*

*I do something explicit to turn the volume on (e.g. I am playing a game or listening to music or something)

*It is plugged in

*An alarm goes off

What I specifically do NOT want:

*

*The ringer to ever ring while the phone is in my pocket (i.e. 100% of the time it is not plugged in)

*The alarm to ever NOT make a audible sound, regardless of any other volume/sound settings (e.g. if the answer is "flip the toggle switch on before you go to sleep and flip it off when you wake up," that's not good enough because I know I'll forget to do that and miss my alarm)

Is what I want possible?  What settings should I use?  Does this depend on the choice of alarm clock app?

A: Sound on iPhone is reasonably complicated when you get down and start "taking it apart". This is because it is managed on a very much case-by-base basis.
For example, if you call up Siri, and adjust the volume, it will only be adjusting the volume for Siri, not something like the ringer volume.
So to divide things up and try to answer your question, I'll start with the basics.
If you turn on Vibration mode (orange position) using the switch on the side of the phone it will turn off almost all sounds. Unlock, keyboards and such sounds will no longer be on. Notifications and phone calls will vibrate but not be heard. You will have to turn the switch off (no orange) in order to hear normal sounds while in apps - (i.e. games). When alternating vibration mode versus normal mode, iPhone remembers your previous state, and will set the volume to what it was before vibration mode was active.
Exception: alarms set in the Clock.app are still heard. In fact, there is no way to turn off Clock.app's alarms from being heard unless you turn off the alarm(s) itself. As for other alarm clock style apps (for example, Sleep Cycle), it is up to the developer to make it behave like Clock.app. That is the case with Sleep Cycle, but it would be worth verifying with any other alarm style app.
If you turn down the volume in the Music.app (or double tap home button and swipe to the right twice), or while watching a video, or in Settings.app, that is the volume that is applied across the board, mostly. That volume reflects the volume for videos, music, and apps that in general make noise - as in, games. Note that iPhone remembers your settings when you have headphones plugged in vs. not.
When iPhone is unlocked and you are on the home screen and you adjust the volume, you are adjusting ringer volume. In other words if the vibration switch is off (no orange) then that would be the volume it would ring at.
Do-not-disturb suppresses basically all notifications (there are some configuration options there). Again, alarms (from Clock.app, and other properly set up apps like SleepCycle) will stay play.
The only thing you can't do is have it toggle sound settings when it is plugged into the wall vs. when it is not. I think you will find it becomes habit, however, to throw the vibration switch.

A: A jailbroken iPhone can manipulate a lot of these settings you desire as they are not options included in the stock iOS. Remember though, while jailbreaking may be beneficial, it has its flaws also.
*edit
Vibrate Things is an application tweak that allows you to customize a bunch of things to vibrate. It can be found in cydia after jailbreaking.
If you like to know you are in vibrate you can install muteicon which shows a mute symbol in the status bar.
The app Auto Silent will disable the ringer switch but I believe it isn't updated yet for iOS6. This becomes in handy when you accidentally flip the switch and not realize it...
There are many more application that do similar things ^^ googled those in seconds to edit this post to answer the comment.


text:
Q: contenScriptFile : Do we always need jQuery? This tutorial  https://developer.mozilla.org/en-US/Add-ons/SDK/Tutorials/Modifying_Web_Pages_Based_on_URL is showing how to use scripts in order to modify web pages. It is possible to load scripts from another script file using contentScriptFile. My question is what would be the content of the contentScriptFile ? The tutorial is giving the example of :
$("body").html("
Page matches ruleset
");

But isn't this line using jQuery ? Is it necessary to add jQuery whenever we use contentScriptFile ? In this case shouldn't we add jQuery to the add-on directory, as shown in the tutorial :  contentScriptFile: [self.data.url("jquery-1.7.min.js"), self.data.url("my-script.js")] ?

A: jQuery is just a layer on top of the regular DOM/Web APIs. So you don't really need it.
Actually, the first example on that tutorial page gives the same example without jQuery:
// Import the page-mod API
var pageMod = require("sdk/page-mod");

// Create a page mod
// It will run a script whenever a ".org" URL is loaded
// The script replaces the page contents with a message
pageMod.PageMod({
  include: "*.org",
  contentScript: 'document.body.innerHTML = ' +
                 ' "
Page matches ruleset
";'
});

You can just stuff the contentScript into a contentScriptFile instead, of course.
So no, you don't need to use jQuery. In fact, and this is my personal opinion, you should probably avoid jQuery if you can, as most of the time the performance hit of loading jQuery in the first place doesn't outweigh the added benefits, in particular since you don't really have to deal with cross-browser incompatibilities, which is one of the major benefits of jQuery.


text:
Q: what's the correct form of breaking a case with an if statement inside? would you write it like this:
// This is just something a came up to explain my question

switch(a)
{
case 2:
    if(x >= 1)
    {
        dosomething();
        break;
    }
    else
    {
        dosomethingelse();
        break;
    }
default:
break;
}

or like this:
switch(a)
{
case 2:
    if(x >= 1)
    {
        dosomething();
    }
    else
    {
        dosomethingelse();
    }
    break;
default:
break;
}

Should the break be inside of the if/else statements or outside of these? is there a correct way or it doesn't matter?

A: I would go for the second option, tends to be a lot clearer that the case statement does have a break.
If you have the break in the if, usually it's to short circuit the case statement so it doesn't keep executing.  Though, be careful with short circuiting, as it can make things more confusing / error prone, and often is a symptom of doing too much in the switch.

A: Both are correct, but it's better to do it like the second one, as you should do the break right after each case statement. Also it tends to have a more readable and manageable code, as you may change the if sections later and thus lose the breaks.
So you can do it just like this:
switch(a){

    case 1:

       if( a > b ){
       // do something
       }else{
       //do some other thing
       }

       break;

    case 2:

       if( a > c ){
       // do something
       }else{
       //do some other thing
       }

       break;

    default

       break;

}

A: In general second option will be preferred, some times that is all depends on your business test case. Switch case will be used if there is more than one if else ladder, to increase efficiency and readability of your code. Now to answer your question break be inside of the if/else statements or outside?
Scenario 1: If your have only if and else in your block, then break doesn't matter where it is. Anyhow only one bock will execute.
Scenario 2: You have some code to execute irrespective of condition inside the case block, then you have to put break at end.Ex.

    switch(a)
        {
        case 2:
            if(a >= 1)
            {
                dosomething();
            }
            else
            {
                dosomethingelse();
            }
             doSomethingForthisCase();
            break;
        default:
          break;
      }

Many more scenario also you can think, like put break inside both else and last. In this case, if condition satisfies then doSomethingForthisCase(); will execute, else only else block will execute, etc..

A: As already mentioned in the above answers, second option would be preferable as the repeating breaks could be avoided. However, I would also like to suggest that break for default is not necessary. As default tends to be be the last option executed.

A: Generally, you want 1 exit point, so an if/else chain of equal weight should have the break at the bottom.
if(a >= 1)
{
    dosomething();
}
else
{
    dosomethingelse();
}
break;

A common exception is pretesting for error conditions and breaking out before performing the operation.
if(a < 1)
{
    handle_error();
    break;
}

dosomething();
break;

A: Both of them would work, but definetely the second option is the way to do it. The first one it breaks a logic structure, and that's never a good practice.


text:
Q: Cannot login with the Firebase CLI I have a problem when I try to login to Firebase using the CLI. I installed firebase-tools using npm -g install firebase-tools with admin rights. The steps I do are (from a cygwin terminal on Windows 10 Professional):
firebase login --no-localhost

After this I get the message:
Visit the URL on any device....
Paste authentication code here:

Then, on my browser, I see Google asking if I give Firebase CLI access rights, I say yes and then I get an authorization code displayed on the browser.
I copy this code into the cygwin console and then:
Error: Authentication Error.

I'm at a total loss for this and it's completely stalling my efforts to get to know Firebase. All help gratefully appreciated.

A: Try:
firebase login --interactive

it will open up a browser window to authenticate.

A: In my case was bug in terminal in Visual Studio Code. On CMD terminal it start works.

A: On windows 10, I had issues with my firebase login through cli. I had to run my command line as the administrator and it worked.

A: I got the same issue today and it was because back in the day I used firebase and didn't remove this define from my bash_profile
FIREBASE_TOKEN
try echo $FIREBASE_TOKEN if something shows up try deleting, open new terminal and re-authenticating
This works for me.

A: my FIREBASE_TOKEN was FIREBASE_TOKEN=' '. I logged out of all my terminal sessions and tried again and that worked.

A: Just run the cmd wit administrator privilege...! Happy coding

A: If you really can't log in with firebase CLI using the "firebase login" command
Then, use GitBash instead of PowerShell in the VS code or any other code editor terminal.
First, download Git SCM then use gitbash in the terminal for any kind of Firebase hosting command terminal image using gitBash
It does work actually!!

A: I used with cmd, it was worked.

A: I copy pasted the link into an incognito window, and somehow it worked.

A: After running across this problem I tried multiple different things to solve this:

*

*Used firebase login --reauth

*Used firebase login --no-localhost

*Turned off proxy settings

*Ran command from within windows/system32

*Turned off my security settings in Firefox

All these options listed above worked for others but not for me
Finally the way it worked was to install google chrome and run the command from from chrome instead of firefox

A: Check your firebase version. if firebase version is "8.15.0" this, then its okay, if not: uninstall firebase-tools globally and globally install it again with 'version'
npm i --global firebase-tools@8.15.0
then after check which terminal u r using, make sure to use cmd terminal. go to your directory and fire command
firebase login.
Check if its working


text:
Q: Recovering original UTF8/Kanji/Chinese text from  random/garbage ASCII I know this may not be possible but wanna give it a shot anyway.
So I have some data as results of html form submissions. Users originally typed in Kanji in some of the fields. But all I got were random ascii letters like this:

æŽå°çŽ²

I already fixed the encoding issue (so that new form submissions handle utf8 fine) but would like to see if I can recover the old data (the correct kanji letters) from before the fix.
Thanks for the help.
UPDATE:
Guess a little clarification is needed. As I said, I have already fixed the encoding problem for the html form. The actual question is whether or not one can recover the original kanji from the "garbage" data that I already received.
For example, I'm trying to "reverse-engineer" the following
ôüÒýR
å¼µå¥éºŸ
冉榆平
·¨¶vÚ¬

Every line is supposed to be someone's name in Kanji or Chinese. I tried all the sensible encodings such as GBK, gb18030, and Big5-HKSCS. No luck so far.
Last UPDATE:
Having some luck with BIG5 encoding now. It didn't work for all the garbage data, but it worked for about 2/3 of them.

A: Use Character set converter - online tool

*

*Input encoding should be UTF8

*For Output encoding, try out all the sensible encodings for oriental characters.

*Remember to check the 2nd checkbox.
Most if not all of the garbage letters should be recovered.

A: Those letters aren't ASCII. No ASCII letters have accents of any kind.
It's unclear how you're reading this data - is it from a file, a database, something else? Anyway, it's possible that it's already in UTF-8 - so you should just try to read it using that encoding. You haven't told us what platform you're using, but you should ensure that whatever you are using, you get to find out what Unicode characters you've read by number - that's a lot more reliable than printing out the values as characters.

A: FYI, the java String class is backed by 2 byte chars, and was designed back when unicode was only 2 bytes.  Thus it doesn't handle the 3 byte Japanese and Chinese characters.  See http://java.sun.com/developer/technicalArticles/Intl/Supplementary/


text:
Q: Android week number wrong for phone but not Emulator I have a program where it relies heavily on identifying the week number for the year.  I have done the leg work and figured out all the problems that will cause and settle with this method.  I works perfect for years that have 53 weeks and such.  My only issue is that when I run it on my emulator for 2.2 it works perfect, like this is week 19 and its correct.  when I run it on my phone a G1, the week shows 20.  How do I fix this?
Here is my week code:
/**
 * Format the date into a number that is the year*100 plus the week i.e. 2008 and its week 11
 * would show as 811
 * @param - String of a date to create a week id, must be in format of 2011-01-31 (YYYY-MM-DD)
 * @return returns next weeks id
 */
public static int getWeekId(String date){

    // Set the first day of week to Monday and set the starting new year weeks
    // as a full first week in the new year.
    Calendar c = Calendar.getInstance();
    c.setFirstDayOfWeek(Calendar.MONDAY);
    c.setMinimalDaysInFirstWeek(7);

    if (!date.equalsIgnoreCase("")) {
        String[] token = date.split("-", 3);
        int year = Integer.parseInt(token[0]);
        int month = Integer.parseInt(token[1])-1; // months are 0-11 stupid..
        int day = Integer.parseInt(token[2]);
        c.set(year, month, day);
    }

    int yearWeek = ( (c.get(Calendar.YEAR) - 2000)*100 + (c.get(Calendar.WEEK_OF_YEAR)));

    Log.d("getWeekId()"," WEEK_OF_YEAR: " + c.get(Calendar.WEEK_OF_YEAR));

    return yearWeek;

}

A: (I'd leave this in a comment, but my account does not yet have commenting permissions.)
When called with 2011-01-01, the code currently returns 1152.  Is this as intended?

A: For what it's worth, there is likely more intricacy to it than you've written. I don't say this to be mean, it's just that there are probably lots of interesting weird cases that you haven't considered. There is a good Java library that knows a ton of stuff about times, and may have this code written already, Check it out: http://joda-time.sourceforge.net/

A: Apparently its a bug in the android phone...so watch out for this when using android 1.6.


text:
Q: php $output .= include code from file Just trying to tidy up a little bit of code here. I have a php command to output some html. However, one of my comands is quite a large amount of html, I was wondering if it's possible to output code referenced in a different file?
For example, my current php looks like this:
$output .= '
';
$output .= '
'.$title.'
';
$output .= 'SOME VERY LONG CODE'

Is it possible to do something like this:
$output .= include('file_with_long_code.html');

instead? I aven't tested this, but am curious to know if it works or what the proper way of doing it is

A: you can instead use getfilecontent function of php
 $output .=  file_get_contents('file_with_long_code.html');

A: You could do something like this:
    ob_start();
       include('somefile.php');
    $output = ob_get_contents();

Read more about output buffering in the docs:
http://php.net/manual/en/function.ob-start.php
I recommend using a PHP Framework, most of them have a very good functionality for these Kinds of "Problems".

A: html file.tpl.php:
<div class="contact-form <?=$css_class; ?>" >

<?=$title; ?>

SOME VERY LONG CODE

main file:
<?php

ob_start();
include('file.tpl.php');
$output = ob_get_contents();
ob_end_clean();

?>

A: $output .= file_get_contents('file_with_long_code.html');
Yes, it is possible.