text:
Q: Python theleton add text to message I have such a code:
@client.on(events.NewMessage(chats=ID))
async def handler_new_message(event):
    try:
        await client.send_message(ID, event.message)
        print('Сообщение:',event.message)
    except Exception as e:
        print(e)

How can I add my text to the message body?
To be for example so

My text: Message that I got from another channel

A: The event.message object is a string, put it in a variable and add the text you want to it
Now put this variable to the send_message function
@client.on(events.NewMessage(chats=ID))
async def handler_new_message(event):
    try:
        message = event.message
        message += ": Message that I got from another channel"
        await client.send_message(ID, message)
        print('Сообщение:',event.message)
    except Exception as e:
        print(e)


text:
Q: Why does homebrew link to ../Cellar and not /usr/local/Cellar? I have:

*

*MacOS 10.12.2

*homebrew 1.1.5

*maven 2.0.8

I am trying to install maven 3
before running brew, which mvn reports /usr/local/apache-maven-2.0.8/bin/mvn as we would expect.
after running brew install maven without errors which mvn now reports ../Cellar/maven/3.3.9/bin/mvn and mvn -v still reports 2.0.8.
I'm new to brew. brew doctor does not report any errors. What am I doing wrong?

A: Because users might install Homebrew in a different path (e.g. ~/.homebrew). In order to support any install path Homebrew uses relative paths when symlinking binaries and other files.

after running brew install maven without errors which mvn now reports ../Cellar/maven/3.3.9/bin/mvn and mvn -v still reports 2.0.8.

This is a different issue; this time due to your shell which checks the full path of an executable only the first time you use it. That is, the first time you typed mvn -v it did the equivalent of which mvn and remembered that path. The second time you typed mvn -v it used that path instead of re-checking it. Type hash -r to reset its memory or start a new shell.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Replace multiple charcter using regex substitution I am trying to perform a regex substitution on the output of acpi command. My perl one liner for this is:
acpi | perl -F/,/ -alne 'print $F[1] if ($F[1]=~s!\s|%!!)'

The output of the above one liner is 87% whereas my required output is just 87 so it is not replacing % in the string.
Now the output of acpi command is
Battery 0: Discharging, 87%, 05:54:56 remaining

and the output of print $F[1] is
ronnie@ronnie:~$  acpi | perl -F/,/ -alne 'print $F[1]'
 87%   #space followed by 87%#
ronnie@ronnie:~$

Now the strange this is if I try the same perl one-liner on:
echo " 86%" | perl -nle 'print if s!\s|%!!g'

It works fine and outputs 86.
So, why it is not working with acpi command.
PS: I am aware this can be achieved by using sed/awk but I am interested why my solution is not working.

A: Your one-liner does not work as you expect because
s!\s|%!!

replaces either a whitespace or a percent sign, not both.
If you want it to replace both, add the global /g modifier:
s!\s|%!!g

Just as you coincidentally did in your other example.
You might also consider using a character class instead of alternator:
s![\s%]!!g

If your output follows the format you showed, you might be better off using a simple regex:
echo Battery 0: Discharging, 87%, 05:54:56 remaining|perl -nlwe 'print /(\d+)%/'
87

A: This one works as expected:
echo " 86%" | perl -F/,/ -alne 'print $F[1] if ($F[1]=~s!\s*(\d+)%!$1!)'

A: You're missing the g modifier
acpi | perl -F/,/ -alne 'print $F[1] if ($F[1]=~s!\s|%!!g)'
                                                    ____^

A: Your s!...!...! matches the space first and then does nothing else. Try adding the g modifier as in ... s!\s|%!!g.

A: I tried this and it works perfectly.
echo "Battery 0: Discharging, 87%, 05:54:56 remaining" | perl -F, -alne '$F[1]=~s/\s|%//g;print $F[1]'
87

Problem is with the g modifier.
g actually says to replace all the occurrences in the line, but default behaviour is to replace only the first occurrence.
So since there is space at the beginning of $F[1], only space is replaced and rest of the characters in the line are ignored.


text:
Q: Getting dependency error in rust Cargo.toml I am getting some dependencies version errors in rust.
I am fairly new to rust so I do not have any idea how to check for compatible updates between multiple dependencies.
It will be great if someone can resolve this issue and let me know how to manage dependencies.
Cargo.toml:
[package]
name = "chatbot"
version = "0.2.3"
authors = ["Joe Wilm <joe@jwilm.com>"]
license = "MIT"
description = "An extensible chatbot"
documentation = "https://docs.rs/chatbot"
repository = "https://github.com/jwilm/chatbot"
keywords = ["chat", "bot", "extensible"]
readme = "README.md"

[package.metadata.docs.rs]
all-features = true

[dependencies]
regex = "0.1"
rustc-serialize = "0.3"
getopts = "0.2"
irc = { version = "0.12", optional = true }
slack = { version = "0.18.0", optional = true }

[features]
default = []
irc-adapter = ["irc"]
slack-adapter = ["slack"]

I tried with versions suggested by VS Code but it did not work.
Error which I am getting after I do cargo-run is:
failed to select a version for the requirement `security-framework
= "^0.1.13"`
candidate versions found which didn't match: 2.8.2, 2.8.1, 2.8.0, ...
location searched: crates.io index
required by package `native-tls v0.1.2`
    ... which satisfies dependency `native-tls = "^0.1.2"` of package `tungstenite v0.2.0`
    ... which satisfies dependency `tungstenite = "^0.2.0"` of package `slack v0.18.0`
    ... which satisfies dependency `slack = "^0.18.0"` of package `chatbot v0.2.3

A: You are using old versions of the slack and irc crates. Both depend on an old version of native-tls (v0.1) in their dependency trees. native-tls v0.1 depends on a very old version of the security-framework crate (v0.1). All versions of security-framework v0.1 have been yanked from crates.io, see here: https://crates.io/crates/security-framework/versions. I assume this is due to a security issue in those versions. Because the v0.1 version of security-framework is yanked, you can't download it from crates.io anymore, causing the dependency error during compilation.
You can fix this by updating your irc and slack dependencies to their latest versions:
[package]
name = "chatbot"
version = "0.2.3"
authors = ["Joe Wilm <joe@jwilm.com>"]
license = "MIT"
description = "An extensible chatbot"
documentation = "https://docs.rs/chatbot"
repository = "https://github.com/jwilm/chatbot"
keywords = ["chat", "bot", "extensible"]
readme = "README.md"

[package.metadata.docs.rs]
all-features = true

[dependencies]
regex = "0.1"
rustc-serialize = "0.3"
getopts = "0.2"
irc = { version = "0.15", optional = true }
slack = { version = "0.25", optional = true }

[features]
default = []
irc-adapter = ["irc"]
slack-adapter = ["slack"]

Be aware that updating these dependencies is likely to break your code, since there are probably API changes in between your current and the latest version of these crates.

A: Just update your dependencies especially
[dependencies]
irc = { version = "0.15.0", optional = true }
slack = { version = "0.25.0", optional = true }

seem to be troublesome.


text:
Q: Sum of independent random variables We know that the sum of two independent normal random variables is again a normal random variable. But is the reverse right? If $X$ and $Y$ are independent random variables satisfying $X+Y$~$N(\mu,\sigma^2)$ for some $\mu$ and $\sigma$, can we conclude that both $X$ and $Y$ obey normal distribution? or under some conditions added on $p_X$ and $p_Y$ (the density functions of $X$ and $Y$)?

A: Yes, and the same holds for Poisson, and for mixtures of Gauss and Poisson.
All these are special cases of the general question: if $X_j$ are independent
and we know the distribution of their sum, what can be said about the distributions of the $X_j$. This general question is addressed in the book
Linnik, Ostrovskii, Decomposition of random variables and vectors, AMS 1977
(translation from the Russian).

A: Yes, they are normally distributed.  This is the Lévy-Cramér theorem.


text:
Q: sending multiple emails fails for the last email address We are facing an issue with VB.net which automates email being send with text file attachments to more than one email address.
The strange part is if we send the mail to 2 persons, then first person receives the email but not the second.
If we add three email address, then email is received by first two email addresses but no to the third one. it keeps going this way when adding more email addresses.
Also, while executing the script a second time, email does goes to all recipients. To be precise, emails are received by all recipients on alternate execution of the script only.
Does this have anything to do with the time taken by mail server etc?
finally what we did to make it work is run the send email command for the last email address two times. I know this is not a permanent solution.
Any help is highly appreciated.
Thanks in advance.
    public void Main()
    {
        SmtpClient client = new SmtpClient("1.1.1.1", 25);

        client.DeliveryMethod = SmtpDeliveryMethod.Network;

        client.Credentials = new NetworkCredential("support", "support");

        MailMessage EM1= new MailMessage("support@domain.com", "user1@domain.com ",
           "This is my subject" + " " + "  ", "Hello,");

        EM1.Attachments.Add(new Attachment(@"F:\WebData\TxtFiles\1.txt"));
        client.Send(EM1);

        Dts.TaskResult = (int)ScriptResults.Success;

        MailMessage EM2 = new MailMessage("support@domain.com", "user2@domain.com",
           "This is my subject" + " " + " ", "Hello,");

        EM2.Attachments.Add(new Attachment(@"F:\WebData\TxtFiles\1.txt"));
        client.Send(EM2);

        Dts.TaskResult = (int)ScriptResults.Success;

        MailMessage EM3 = new MailMessage("support@domain.com", "user3@domain.com",
        "This is my subject" + " " + " ", "Hello,");

        EM3.Attachments.Add(new Attachment(@"F:\WebData\TxtFiles\1.txt"));
        client.Send(EM3);
        client.Send(EM3);

        Dts.TaskResult = (int)ScriptResults.Success;

    }
}

}

A: The first place you should check are the logs of the mail server. They should tell you what's happening with the submitted messages (accept/reject, next-hop delivery, etc.).
However, sending the same message multiple times to different recipients is bad practice anyway. Doing that is the mail server's job. Submit the message just once for all intended recipients. You can specify all recipients with a comma-separated string:
MailMessage EM = new MailMessage("support@example.com", _
  "user1@example.com,user2@example.com,user3@example.com", _
  "This is my subject", "Hello,");

EM.Attachments.Add(new Attachment(@"F:\WebData\TxtFiles\1.txt"));
client.Send(EM);
or add additional recipients like this:
MailMessage EM = new MailMessage("support@example.com", _
  "user1@example.com", "This is my subject", "Hello,");

EM.To.Add("user2@example.com");
EM.To.Add("user3@example.com");

EM.Attachments.Add(new Attachment(@"F:\WebData\TxtFiles\1.txt"));
client.Send(EM);
If you don't want the recipient to know about the other recipients, send the message to a default recipient (e.g. the sender address) and add the other recipients as BCC addresses:
MailMessage EM = new MailMessage("support@example.com", _
  "support@example.com", "This is my subject", "Hello,");

EM.Bcc.Add("user1@example.com");
EM.Bcc.Add("user2@example.com");
EM.Bcc.Add("user3@example.com");

EM.Attachments.Add(new Attachment(@"F:\WebData\TxtFiles\1.txt"));
client.Send(EM);


text:
Q: Jasper Reports: how to add own Functions to Expression Editor I am using Jaspersoft Studio 6.6 and try to add own functions to the Expression Editor.
Therefore i follow the tutorial Jaspersoft Studio Expression Editor: how to extend it and contribute your own functions (part 2) - updated for version 5.5 (i was not able to find a more current version so i guess this one should be still correct)
All works fine but i had to replace the language of the generated report (SampleFunctionsReport.jrxml) from groovy to java to get rid of class not found exceptions
Finally the following Errors are remaining:
Description    Resource    Path    Location    Type
The method HELLO_WORLD_MSG() is undefined for the type SampleFunctions_1541665022158_603382    SampleFunctionsReport.jrxml    /MyFunctions    line 37    JRXML Problem
The method HELLO_WORLD_MSG() is undefined for the type SampleFunctions_1541665022158_603382 value = HELLO_WORLD_MSG( );     SampleFunctionsReport.jrxml    /MyFunctions    line 0    JRXML Problem
The method REPEAT_MSG(String, int, boolean) is undefined for the type SampleFunctions_1541665022158_603382    SampleFunctionsReport.jrxml    /MyFunctions    line 52    JRXML Problem
The method REPEAT_MSG(String, int, boolean) is undefined for the type SampleFunctions_1541665022158_603382 value = REPEAT_MSG("A message that will be probably repeated",5,true);     SampleFunctionsReport.jrxml    /MyFunctions    line 0    JRXML Problem

I checked the points of the tutorial a couple of times...
can someone reproduce my problem?
What am i missing?

A: <import value="test.customfunctions.*"/>

this is the code from my jrxml, which is fine.
when i tried to enter the full class name - i got an error, that the package cannot be added.
today i tried the same again - and its working. even the resulting XML is identical!


text:
Q: Disable span does not work on firefox how to disable a span using jquery/javascript. The script
$('#spanid').attr("disabled", 'disabled');

works fine on IE but doesnt work on firefox.

A: You cannot disable a <span>. The disabled attribute only works for input elemens. What are you trying to achieve there ?
The only thing I can imagine is that you've got some event bindings on that <span>, to remove those you can call jQuerys .unbind(), .die() and/or .undelegate().
$('#spanid').unbind().undelegate().die();

That would remove any event handler (bound directly or via delegation). The only problem here is, that you would to manually store the event handler functions if you want to "enable" it later on again.

A: add this to your css
[disabled] {
    pointer-events: none;
}

check out MDN for browser support. Although IE has only recently supported pointer events, adding disabled to a span in IE makes the span not emit click events.


text:
Q: How to get an object identifier in fabricjs? How to get an object identifier in fabricjs?
For example
var text = new fabric.IText('hello world', { left: mouse1X, top: mouse1Y });

ID = text.get???

This identifier should be present in
JSON.stringify(canvas)
canvas.loadFromJSON()

identifier should be present in the JSON.stringify(canvas) canvas.loadFromJSON()

A: There are not id attributes on the objects, but you can create your own.
like this:
var msg = 'hello world';
var myId = 1;

var text = new fabric.IText(msg,
{
    left: mouse1X,
    top: mouse1Y,
    id: myId } //my custom property
);

canvas.add(text);

//get id value
console.log(text.get('id'));
//OR
console.log(text.id));

//change id value
text.set('id',5);
//OR
text.id = 5;
canvas.renderAll();

A: When you create an object, pass along the options an id attribute:
var obj = fabric.Object({id: 'myid'});

or add at runtime:
obj.id = 'myid';

When saving to JSON use the propertiesToInclude parameter to specify you want to save it:
obj.toJSON(['myid', 'others...']);

or
canvas.toJSON(['myid', 'others...']);

Loading back will be automatic.

A: Add an id when creating any object like this:
// functions that generates an id
function generateId(type) {
    return `${type}-${Math.random().toString(36).substr(2, 9)}`;
}

const rectangle = new fabric.Rect({
    id: generateId('rect'),
    left: 150,
    top: 45,
});

So, you can reset ids by passing the reviver callback to loadFromJSON.
// function to be passed as reviver callback
function resetObjectsIds(o, object) {
    object.set({ id: generateId(object.get('type')) });
}

// when loading json...
canvas.loadFromJSON(
    canvasJson,
    canvas.renderAll.bind(canvas),
    resetObjectsIds, // here is the reviver callback function
);

Now, every time you save or load the canvas, it will have ids.


text:
Q: Kafka Streams (KStream-Ktable) Join partially joined When (left) joining a Kstream with a Ktable some messages produce join pairs which do not have a matching Ktable message.
But when taking a look at the topics this should have succeeded:
KStream message:
+------------------------------------------------------+
|       Key  | Timestamp  | Partition  | Offset        |
+------------------------------------------------------+
| "1000002547"  | 2020-12-11T12:18:47.67Z  |  9 | 1249 |
+------------------------------------------------------+

KTable messages:
+--------------------------------------------------+
|     Key  | Timestamp  | Partition  | Offset      |
+--------------------------------------------------+
| "2120103"  | 2020-11-27T12:14:23.488Z  |  4 | 27 |
| "2120103" |  2020-12-08T07:59:38.066Z |  4 | 56  |
+--------------------------------------------------+

Internal repartition topic:
+-----------------------------------------------+
|    Key  | Timestamp  | Partition  | Offset    |
+-----------------------------------------------+
| "2120103" |  2020-12-11T12:18:47.67Z | 4  | 0 |
+-----------------------------------------------+

Additional information:

*

*all topics only have the clean up strategy compact

*joining is done on String values since all keys are string (see " " in tables)

*The timestamps show that the timestamps of the Ktable are smaller than the ones of the stream

As the example shows the Ktable message exists and the Kstream message was correctly repartitioned.


text:
Q: Is a GUID a good key for (temporary) encryption? I'm generating an encryption key to encrypt some sensitive data with the Rijndael (AES) encryption algoritm. I'm using a guid as key generator. Are these keys "strong" enough?
Note: it is only sensitive for 20 minutes.

A: No. The GUID keys can be predicted, at least those generated by .NET / WinAPI. Also keep in mind that the GUID does not even have a true 128bit randomness, because the version number is fixed. This gives you a very weak key in the first place.
To make matters worse, several versions of the GUID algorithm suffer from predictability. The point is that GUIDs are not created at random, but they follow certain rules to make it practically impossible for GUIDs to collide.
As discussed in the comments, GUID V1 suffered from privacy issues (or, the other way around, weaker keys) because the MAC address was used to generate them. With GUID V4, there are still ways to predict the sequence according to the (russian) source below.
Fortunately, .NET has cryptographically strong random generators on board. The RNGCryptoServiceProvider is your friend:
RNGCryptoServiceProvider _cryptoProvider = new RNGCryptoServiceProvider();
int fileLength = 8 * 1024;
var randomBytes = new byte[fileLength];
_cryptoProvider.GetBytes(randomBytes);

You might want to refer to:
How can I generate a cryptographically secure pseudorandom number in C#? -- shows alternatives and in a comment, the link to Wikipedia is given:
http://en.wikipedia.org/wiki/Globally_Unique_Identifier
In there, it is claimed (according to wikipedia, the page is in Russian)that one can predict previous and future numbers generated:
http://www.gotdotnet.ru/blogs/denish/1965/

A: No, GUIDs are not cryptographically secure. They follow an extremely predictable and well-documented pattern, and they're fairly short as far as truly secure keys go. But more to the point, you're misusing GUIDs by doing this. This is not what they were designed for. They're globally unique identifiers. The only guarantee you get is that each of them is unique. A sophisticated hacker will make child's play of reverse engineering a GUID.
Use the functions provided by the System.Security.Cryptography namespace, instead. That's what they're designed for. Read up on cryptographically secure pseudo-random number generators.

A: I would not use a GUID for the key to encrypt data. Look at some of the implementations of the UUID protocol: UUID they can be predicted as they're computed to be unique, not random. I'd look into the using System.Security.Cryptography namespace for objects like "TripleDESCryptoServiceProvider" for sensitive data personally.

A: Consider using this, or an equivalent random string generator: http://msdn.microsoft.com/en-us/library/aa379942%28VS.85%29.aspx


text:
Q: [Converting Activity code to fragment]Dynamically adding images to LinearLayout in Fragment I Have already done this in activity and I will provide part of that code as well. Basically I have a linear layout inside HorizontalScroll View and I want to add imageViews to it dynamically. The activity code for this is below and it works perfectly fine all I want is to have exact same functionality for 1 of my fragments as well. XML for the code is given below:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingTop="5dp"
tools:context="com.example.scrolls_tabs.OneFragment"
android:background="@drawable/wooden_back">

<HorizontalScrollView
    android:id="@+id/HorizontalScrollView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginBottom="5dp"
    android:background="#00ffffff"
    android:scrollbars="none">

    <LinearLayout
        android:id="@+id/MainLayout"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <LinearLayout
            android:id="@+id/imgLayout1"
            android:layout_width="wrap_content"
            android:layout_height="110dp"
            android:orientation="horizontal">

        </LinearLayout>

    </LinearLayout>
</HorizontalScrollView>

and code for this that works perfectly in activity:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    RelativeLayout layout =(RelativeLayout)findViewById(R.id.activity_main);
    layout.setBackgroundResource(R.drawable.wooden_back);

    // Bitmap bdrawable = new Bitmap(this.getResources().getIdentifier("drawable/wood_back", "id", getPackageName()));
    DisplayMetrics displaymetrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
    int screenHeight = displaymetrics.heightPixels;
    int screenWidth = displaymetrics.widthPixels;
    int imgHeight = (int) (screenHeight* 0.30);
    int imgWidth = (int) (screenWidth* 0.25);

    for (int j=1; j<10; j++)
    {
        final int b1=j;
        create_img1("drawable/a"+j, b1, imgHeight, imgWidth);
        ImageView drag = (ImageView)findViewById(b1);
        dragAndDropImage(drag, "drawable/c"+j);
    }

    ImageView imgh=(ImageView)findViewById(R.id.bottomlinear);
    imgh.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            Bundle localBundle = new Bundle();
            localBundle.putInt("Item #1", item1);
            localBundle.putInt("Item #2", item2);
            localBundle.putInt("Item #3", item3);
            localBundle.putInt("Item #4", item4);
            localBundle.putInt("Item #5", item5);
            localBundle.putInt("Item #6", item6);
            localBundle.putInt("Item #7", item7);
            localBundle.putInt("Item #8", item8);
            localBundle.putInt("Item #9", item9);

            Intent i = new Intent(getApplicationContext(),test_activity.class);
            i.putExtras(localBundle);
            startActivityForResult(i, 1);
        }
    });

}

void create_img1(String ss, int ID, int H, int W)
{
    LinearLayout linearLayout = (LinearLayout) findViewById(R.id.imgLayout1);
    LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(340, 340);
    parms.gravity = Gravity.CENTER;
    parms.setMargins(20, 0, 20, 0);
    final ImageView imageView = new ImageView(this);
    imageView.setLayoutParams(parms);

    int id = getResources().getIdentifier(ss, "id", getPackageName());
    imageView.setImageResource(id);
    linearLayout.addView(imageView);
    imageView.setId(ID);

    imageView.getLayoutParams().height = H;
    imageView.getLayoutParams().width = W;
}

This is basically me looking for a solution where I get to do the same thing in fragments that I have already done in activity. I'm very new to android so anything helpful is appreciated.
Current Fragment code which is not working.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState)
{
    // Inflate the layout for this fragment

    fa = super.getActivity();
    ll = (LinearLayout) inflater.inflate(R.layout.fragment_one, container, false);

    int imgHeight = 50;
    int imgWidth = 50;

    for (int j=1; j<10; j++)
    {
        final int b1=j;
        create_img1("drawable/a"+j, b1, imgHeight, imgWidth);
    }

    return ll;
}

void create_img1(String ss, int ID, int H, int W)
{
    LinearLayout linearLayout = (LinearLayout) ll.findViewById(R.id.imgLayout1);
    LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(340, 340);
    parms.gravity = Gravity.CENTER;
    parms.setMargins(20, 0, 20, 0);
    final ImageView imageView = new ImageView(getActivity());
    imageView.setLayoutParams(parms);

    //int id = getResources().getIdentifier(ss, "id", getPackageName());
    imageView.setImageResource(R.drawable.a1);
    linearLayout.addView(imageView);
    imageView.setId(ID);

    //imageView.getLayoutParams().height = H;
    //imageView.getLayoutParams().width = W;
}

}

A: you should add img view to linear layout like below
 void create_img1(String ss, int ID, int H, int W)
      {
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.imgLayout1);
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(340, 340);
parms.gravity = Gravity.CENTER;
parms.setMargins(20, 0, 20, 0);
final ImageView imageView = new ImageView(this);
imageView.setLayoutParams(parms);

int id = getResources().getIdentifier(ss, "id", getPackageName());
imageView.setImageResource(id);

imageView.setId(ID);

imageView.getLayoutParams().height = H;
imageView.getLayoutParams().width = W;

 **linearLayout.addView(imageView);**
     }


text:
Q: Evaluation of $\lim_{n\rightarrow \infty}\binom{2n}{n}^{\frac{1}{n}}$
Evaluation of $$\lim_{n\rightarrow \infty}\binom{2n}{n}^{\frac{1}{n}}$$
without using Limit as a sum and stirling Approximation.

$\bf{My\; Try:}$ Using $$\binom{2n}{n} = \sum^{n}_{r=0}\binom{n}{r}^2$$
Using $\bf{Cauchy\; Schwarz}$ Inequality
$$\left[\sum^{n}_{r=0}\binom{n}{r}^2\right]\cdot \left[\sum^{n}_{r=0}1\right]\geq \left(\sum^{n}_{r=0}\binom{n}{r}\right)^2 = 2^{2n} = 4^n$$
So $$\frac{4^n}{n+1}<\sum^{n}_{r=0}\binom{n}{r}^2=\binom{2n}{n}$$
But i did not understand how can i calculate upper bound such that i can apply the Squeeze theorem.

A: We can use the fact that if $a_n>0$ for all $n\ge1$ and the sequence $\frac{a_{n+1}}{a_n}$ converges in $[0,\infty]$, then
$$
\lim_{n\to\infty}a_n^{1/n}=\lim_{n\to\infty}\frac{a_{n+1}}{a_n}
$$
(see this answer).
We have that
$$
\frac{{2n+2\choose n+1}}{{2n\choose n}}=\frac{(2n+2)!}{((n+1)!)^2}\frac{(n!)^2}{(2n)!}=\frac{(2n+2)(2n+1)}{(n+1)^2}\to4
$$
as $n\to\infty$. Hence, the limit is $4$.

A: The upper bound is way more trivial than the lower bound through the CS inequality:
$$ \binom{2n}{n}\leq \sum_{k=0}^{2n}\binom{2n}{k} = 2^{2n} = 4^n.$$

A: $\newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$

By "$\textsf{using limits}$", the Stoltz-Ces$\grave{a}$ro Theorem yields:

\begin{align}
\lim_{n \to \infty}{1 \over n}\,\ln\pars{{2n \choose n}} & =
\lim_{n \to \infty}{\ln\pars{{2\bracks{n + 1} \choose n + 1}} -
\ln\pars{{2n \choose n }} \over \pars{n + 1} - n} =
\lim_{n \to \infty}\ln\pars{{2n + 2 \choose n+1} \over {2n \choose n}}
\\[5mm] & =
\lim_{n \to \infty}\ln\pars{\bracks{2n + 2}\bracks{2n + 1} \over
\bracks{n + 1}\bracks{n + 1}} = \ln\pars{4}
\end{align}

$$
 \color{#f00}{\lim_{n \to \infty}{2n \choose n}^{1/n}} = \color{#f00}{4}
$$


text:
Q: General validity of separation of variables Let $L$ be any differential operator (not necessarily linear).
Given initial conditions and boundary conditions (of any type), I am interested in  general statements of the form:
Given a boundary value problem on some domain $\Omega$.  If $L$, the initial condition, and the boundary are of a certain form, then separation of variables will yield the solution to the boundary value problem.
Do such general statements exist, and if they do, where can I find them? I am interested in statements about strong (classical) solutions and weak (distributional) solutions.
I am aware that questions similar to this one are already posted on this site, however, all of them consider specific differential operators and then they focus on separability of the domain. I am interested in statements about general differential operators.

A: The short answer is No. A major problem is that there is no single universal definition for what it means for an equation to be solvable by separation of variables. This defect in the theory, as well as the lack of general statements of the form that you would like to see, was highlighted a while ago in this BAMS book review:

Tom H. Koornwinder. "Review: Willard Miller, Jr., Symmetry and separation of variables." Bull. Amer. Math. Soc. (N.S.) 1 (6) 1014 - 1019, November 1979.

Unfortunately, the situation has not changed so much since then. Koornwinder himself proposed a general definition for an equation to be separable and you can find a few papers that refer to it or extend it by looking up papers that cite this review. But there are no really general results, as far as I am aware.


text:
Q: Scraping Tables on a Web page with BeautifulSoap I need to do a DataFrame in Python with the information of Top 500 Americas Companies:
https://www.americaeconomia.com/negocios-industrias/estas-son-las-500-mayores-empresas-de-america-latina-2021
I tried to do web scraping and when I print(tabla) it said [] or None...
from bs4 import BeautifulSoup
import requests

url = 'https://www.americaeconomia.com/negocios-industrias/estas-son-las-500-mayores-empresas-de-america-latina-2021'
page = requests.get(url)

soup = BeautifulSoup(page.text, 'html.parser')

tabla = soup.find('table', {"id":"awesomeTable"})
print(tabla)

A: What happens?
Always look in your soup first - therein lies the truth. The content can always be slightly to extremely different from the view in the development tools.
You won't find the table in your soup, cause it is in iframe.
How to fix?
Use the url of the iframe source to perform your request:
https://rk.americaeconomia.com/display/embed/500-latam/2021

Example
import requests
from bs4 import BeautifulSoup
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36'}
r = requests.get('https://rk.americaeconomia.com/display/embed/500-latam/2021',headers=headers)
soup = BeautifulSoup(r.text,'lxml')
data = []
for row in soup.select('#awesomeTable tbody tr.dataRow'):
    data.append(list(row.stripped_strings))

pd.DataFrame(data, columns=list(soup.select_one('#awesomeTable tr').stripped_strings))

Output

RK 2021
EMPRESA
PAÍS

1
PETROBRAS
BRA

2
JBS
BRA

3
AMÉRICA MÓVIL
MX

4
PEMEX
MX

5
VALE
BRA

...
...
...


text:
Q: When using Channels with SignalR server-to-client streaming, is the server-side Complete guaranteed to be delivered to the client? I'm doing SignalR server-to-client streaming using System.Threading.Channel with a .NET client. The usage is fairly basic, similar to what is described in the introductory docs.
The hub code is similar to this:
public ChannelReader<byte[]> Retrieve(Guid id, CancellationToken cancellationToken)
{
    var channel = Channel.CreateBounded<byte[]>(_limit);
    _ = WriteItemsAsync(channel.Writer, id, cancellationToken);
    return channel.Reader;
}

private async Task WriteItemsAsync(ChannelWriter<byte[]> writer, Guid id, CancellationToken cancellationToken)
{
    Exception localException = null;
    try
    {
        //loop and write to the ChannelWriter until finished
    }
    catch (Exception ex)
    {
        localException = ex;
    }
    finally
    {
        writer.Complete(localException);
    }
}

And client similar to this:
var channel = await hubConnection.StreamAsChannelAsync<byte[]>("Retrieve", _guid, cancellationTokenSource.Token);

while (await channel.WaitToReadAsync())
{
    while (channel.TryRead(out var data))
    {
        //handle data
    }
}

When my hub method is done streaming, it calls Complete() on its ChannelWriter. SignalR, presumably, internally sees the Complete call on the corresponding ChannelReader, translates that into an  internal SignalR message and delivers that to the client. The client's own ChannelReader is then marked as complete by SignalR and my client code wraps up its own work on the stream.
Is that "completed" notification, from server to client, guaranteed to be delivered? In other cases where the hub is broadcasting non-streaming messages to clients, it generally "fires and forgets", but I've got to assume that calling Complete on the streaming Channel has acknowledged delivery, otherwise the client could be in a state where it is holding a streaming ChannelReader open indefinitely while the server sees the stream as closed.
Less important to the question, but the reason I ask is that I am trying to narrow down just such a scenario where a data flow pipeline that consumes a SignalR streaming interface very occasionally hangs, and it seems that the only point where it is hanging is somewhere in the SignalR client.

A: I asked the devs over on github: https://github.com/dotnet/aspnetcore/issues/30128.
Here is a quick summary:
"Messages over SignalR are as reliable as TCP. Basically what this means is that either you get the message, or the connection closes. In both cases the channel on the client side will be completed."
And:
"Right it should never hang forever. It'll either send the complete message or disconnect. Either way, a hang would be a bug in the client"


text:
Q: Plotting a histogram for categorical data I have a dataset with two columns like as follows:
    index   Year
0   5   <2012
1   8   >=2012
2   9   >=2012
3   10  <2012
4   15  <2012
... ... ...
171 387 >=2012
172 390 <2012
173 398 <2012
174 403 >=2012
175 409 <2012

And I would like to plot it in a histogram. I tried with
plt.style.use('ggplot')

df.groupby(['Year'])\
      .Year.count().unstack().plot.bar(legend=True)

plt.show()

but I have got an error: AttributeError: 'CategoricalIndex' object has no attribute 'remove_unused_levels' for
df.groupby(['Year'])\
          .Year.count().unstack().plot.bar(legend=True)

I think this is because I am using categorical values. Any help would be appreciated it.

A: Try:
plt.style.use('ggplot')
df.groupby(["Year"])["Year"].agg("count").plot.bar();

Alternatively:
plt.hist(df["Year"]);


text:
Q: Java read CSV file ,contents not write in new CSV file package com;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Arrays;
import com.opencsv.CSVWriter;
import com.opencsv.CSVReader;

public class Sample2 {
    public static void main(String args[]) throws IOException
    {
        CSVReader csvReader = null;
        String[] employeeDetails ;
        CSVWriter  csvWriter = new CSVWriter(new FileWriter("D:\\sample\\myfile.csv",true));
        csvReader = new CSVReader(new FileReader("D:\\sample\\source.csv"));
        try
        {

            employeeDetails = csvReader.readNext();
            while ((employeeDetails = csvReader.readNext()) != null ) {

                    System.out.println(Arrays.toString(employeeDetails));
                    csvWriter.writeNext(employeeDetails);
                }

        }catch(Exception ee)
            {
                ee.printStackTrace();
            }
        }
}

I have my above java code
It read data from source.csv file and also display in the console .
It created myfile.csv ,but same contents it didn't write in the csv file
Anyone have any idea on this

A: CSVWriter implements Flushable.Working Solution is already present in @Stephan Hogenboom's answer. I will answer why didn't it write in your case,
From the javadocs of Flushable interface,

A Flushable is a destination of data that can be flushed. The flush
  method is invoked to write any buffered output to the underlying
  stream.

For performance reasons, all data is to be written into a Buffer instead of File temporarily. Once you call the flush() method, it flushes the data already present in the buffer into your file(this is where disk I/O happens, not when you call writeNext() ).
As mentioned on doc of flush() in java.io.Writer.

Flushes the stream.  If the stream has saved any characters from the
  various write() methods in a buffer, write them immediately to their
  intended destination.

A: The issue is that you don't close your output resources, try this code:
public static void main(String args[]) throws IOException {
String[] employeeDetails;

try (CSVWriter csvWriter = new CSVWriter(new FileWriter("D:\\sample\\myfile.csv", true));
    CSVReader csvReader = new CSVReader(new FileReader("D:\\sample\\source.csv"));
    ) {

  while ((employeeDetails = csvReader.readNext()) != null) {

    System.out.println(Arrays.toString(employeeDetails));
    csvWriter.writeNext(employeeDetails);
  }
}
catch (Exception ee) {
  ee.printStackTrace(); //perhaps you should also log the error?
}
}

Also take a look at this question Is closing the resources always important?


text:
Q: Angular build Failing with "Data path '.sourceMap' should be object." I am building my angular application using the angular CLI command
ng test --source-map=false
Everything was working fine, but suddenly I have started encountering the below error
Schema validation failed with the following errors:
Data path ".sourceMap" should be object.
Data path ".sourceMap" should be boolean.
Data path ".sourceMap" should match exactly one schema in oneOf.

On some inspection, the issue seems to originate from the --source-map parameter, but not sure about the exact cause.

A: There was a bug with the --source-map flag that would throw those errors. The latest version of the @angular-devkit/build-angular has a fix for this (0.13.6).

A: The parameter for source maps is
--sourceMap=true|false

See : https://angular.io/cli/test

A: For the latest version,the cmd params is like this " ng build --prod --source-map ".
https://angular.io/guide/deployment#inspect-the-bundles

A: For me the problem was that i used ngx-build-plus which is not yet based on the Angular CLI 7.2 style config for "sourceMap". The temporary workaround that I used is described here https://github.com/manfredsteyer/ngx-build-plus/issues/88#issuecomment-490433864

A: Is your command correct.I think it should be ng test --sourcemaps=false


text:
Q: How do I configure GeoWebCache to read a TMS (GoogleMaps or OSM)
Possible Duplicate:
geoserver support to proxy other tiling services?

Probably a newbe question, with a simple answer, but I can't find enough detail in the GWC documentation.
I would like to set up GWC so that it reads a TMS (At the moment, just GoogleMap or OSM) and then makes this available as a WMS layer through GWC.
Is this possible, and if so, where do I configure it? I have been looking through the documentation on how to edit and add layers in geowebcache.xml, but I can't see the extact syntax for adding a TMS.
Any help would be greatly appreciated!
Thanks


text:
Q: How can i set two marginBottom for one component in react native I am going to run an animation via animated.sequence, There is two marginBottom with different values in this animation (for one component), but react native ignore second marginBottom and always run first marginBottom.
How can i set two marginBottom with diffrent values for one component?


text:
Q: How to disable default archive name mask in batch WinRAR has the option "Generate archive name by mask". I Set this option to " - yyyy.mm.dd - hh.mm.ss". This is fine for most of the cases.
However, I have a windows batch file which creates zip archives using WinRAR:
Example command: winrar a -afzip -m3 -ep1 -y "E:\myarchive.zip" "E:\Temp\"
The result file is "myarchive - 2014.07.03 - 10.05.09.zip".
Is there any switch to ignore/disable the "Generate archive name by mask" option in the batch file? I found the switch "-ag" but I didn't manage to remove the archive name mask.
Thanks in advance :)

A: Use in the batch file either
WinRAR.exe a -afzip -ag- -m3 -ep1 -y "E:\myarchive.zip" "E:\Temp\"

or
WinRAR.exe a -afzip -cfg- -m3 -ep1 -y "E:\myarchive.zip" "E:\Temp\"

With switch -ag- the archive name mask in the default compression profile is disabled.
With switch -cfg- the default compression profile is completely ignored.
I tested both suggestions with WinRAR.exe v4.20 and v5.10 after changing first the default compression profile to ZIP compression with archive name mask - yyyy.mm.dd - hh.mm.ss and verifying by execution of your command line that indeed the ZIP file is created with name according to the mask in default compression profile.


text:
Q: Media Query not taking effect I have never had a problem with a media query like this before. Normally, it just does something unexpected, but not nothing. I don't need help with the actual effect, just as to why it isn't seeing the query. If you inspect the code, it is just not there. I referenced several other posts, but I have it formatted the same as far as I can tell, syntax wise.
Here is my HTML:

See who's online:

News and Announcements

First and formost, welcome to CommonRoomGaming.com. If you are new here, just find a game you have that you want to play with others, and just jump onto one of our servers! You can find detailed connection instructions on each games page.

ECO Server Woes

New Server Incoming!

2/14/17 - Site Launched

Not playing your favorite game?

Here at CommonRoomGaming.com we don't discriminate against any games. If you want to play a game, odds are others have it and want to play it too! So with that said, if you don't see your favorite game listed, feel free to suggest it by letting us know in the below form.

            <FORM action="emailit.html" method="POST">

                    Your name and/or handle:

                        <INPUT type="text" size="30" maxlength="40" name="name"></INPUT>

                    Your email address:

                        <INPUT type="text" size="30" maxlength="127" name="email"></INPUT>

                    Your message:

                    <TEXTAREA name="message" rows="4" cols="50" style="width:300px" ></TEXTAREA>

                <INPUT type="submit" value="Make it so."></INPUT>

            </FORM>

And here is my media query:
@media screen and (max-width:500px){
#bottom {
    width:350px;
    display:block;
    margin-right:auto;
    margin-left:auto;
}

}
Here is my codepen of the whole document link
Again, I only need to know what I am doing wrong with the media query. Ignore anything unrelated, as it is all changing.

A: Problem was related to DNS Caching.


text:
Q: Validity of taking the limit quotient rule here : This was a problem from the BMT 2020 calculus portion:

Let $f: \mathbb{R}_{>0}\rightarrow \mathbb{R}$ (where $\mathbb{R}_{>0}$ is the set of all positive real numbers) be differentiable and satisfy the equation
$f(y)-f(x)=\frac{x^{x}}{y^{y}} f\left(\frac{y^{y}}{x^{x}}\right)$ for all real $x, y>0$. Furthermore, $f^{\prime}(1)=1$. Compute $\frac{f(2020^{2})}{f(2020)}$.

*

*My method(progress) was exactly as did in the official solution https://www.ocf.berkeley.edu/~bmt/wp-content/uploads/2022/04/calculus-solutions-1.pdf but i got stuck on how to evaluate the expression of $f'(x)$ which they (dont know why) did by taking the denominator limit to the other side from the given value of f'(1) and subsituting the expression from there to the f'(x) expression,

My question is actually why we can do so since the limit of quotient is quotient of N (numerator) and D (denominator) limits provided both exists and D limit is non zero , here its zero isnt ? So why can we do that ? I mean that limit law uses here

*

*This was the step i didnt quite get at all (that is shifting of denominator to the other side even though its limit is zero, so we cannot use limit quotient law)

$\begin{aligned} f^{\prime}(1) &=\lim _{h \rightarrow 0} \frac{f\left(\frac{(x+h)^{x+h}}{x^{x}}\right)-f(1)}{\frac{(x+h)^{x+h}}{x^{x}}-1} \\ &=1.
  \\ \lim _{h \rightarrow 0}\left(\frac{(x+h)^{x+h}}{x^{x}}-1\right) &=\lim _{h \rightarrow 0}\left(f\left(\frac{(x+h)^{x+h}}{x^{x}}\right)-f(1)\right) \end{aligned}$


text:
Q: Android in-app billing API v3: getting started This has been asked many times, but in all the questions there wasn't any guide complete enough.

*

*All the guides recycle the Sample project bundled with the billing
library, even if on Android Developers it's clearly said that the
util package should be written from scratch/heavily edited instead of just copying
the stock one.

*There are no directions on which data send to and how to verify on a personal server if the purchase is legitimate.

*There's no hint, basically, on how to make the sample code stronger,i.e. on how to secure the key in a serverless environment, on how to generate and check a purchase payload and so on.

Maybe I've missed some line or I'm just a bit scared and confused, but I'm asking for some complete resource to consult and some clarification on the three doubts I wrote above.

A: Since nobody is answering, I'll make an answer with useful resources for people unable to implement IAB.
New Sample references
This library is very lightweight and essential, it just works with managed products, but a fork also adds support for subscription products. Both the libraries don't offer any kind of support for querying the inventory, they just handle the purchase process, which is a better approach for my forma mentis. This library paired with the guides on Android Developers makes everything clearer.
This video shows the very basic implementation, this also just implements the purchase request and not the verification/inventory query.
Remote Server Verification
This article shows a simple method to verify purchase data with your public key, so you're not forced to insert it inside your own application.
This guide shows the necessary steps to achieve validation with a PHP backend using Laravel.


text:
Q: Simulate memory warnings from the code, possible? I know i can simulate a memory warning on the simulator by selecting 'Simulate Memory Warning' from the drop down menu of the iPhone Simulator. I can even make a hot key for that.
But this is not what I'd like to achieve. I'd like to do that from the code by simply, lets say doing it every 5 seconds. Is that possible?

A: It is pretty easy actually, however it relies on an undocumented api call, so dont ship your app with it (even if it is in a inaccessible code path).  All you have to do is use [[UIApplication sharedApplication] _performMemoryWarning];.
This method will have the app's UIApplication object post the UIApplicationDidReceiveMemoryWarningNotification and call the applicationDidReceiveMemoryWarning: method on the App Delegate and all UIViewControllers.
-(IBAction) performFakeMemoryWarning {
  #ifdef DEBUG_BUILD
    SEL memoryWarningSel = @selector(_performMemoryWarning);
    if ([[UIApplication sharedApplication] respondsToSelector:memoryWarningSel]) {
      [[UIApplication sharedApplication] performSelector:memoryWarningSel];
    }else {
      NSLog(@"Whoops UIApplication no loger responds to -_performMemoryWarning");
    }
  #else
    NSLog(@"Warning: performFakeMemoryWarning called on a non debug build");
  #endif
}

A: I wrote an apple script that will hammer the simulator with memory errors, it is a bit extreme but if your code survives, then you can be more confident...
on run
repeat 100 times
    tell application "System Events"
        tell process "iOS Simulator"
            tell menu bar 1
                tell menu bar item "Hardware"
                    tell menu "Hardware"
                        click menu item "Simulate Memory Warning"
                    end tell
                end tell
            end tell
        end tell
    end tell
    delay 0.5
end repeat
end run

A: Post a UIApplicationDidReceiveMemoryWarningNotification notification to the default notification center:
[[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidReceiveMemoryWarningNotification object:nil]

A: Just alloc-init big objects in a loop, and never release them. That should trigger a memory warning pretty quickly, I'd imagine.


text:
Q: ProcessBuilder not executing program correctly in java eclipse luna I have created a program in ProcessBuilder in java. Below is the program. I have created the program in Eclipse IDE. While executing the program is showing errors.
//Demonstrate ProcessBuilder.
public class ProcessBuilder
{
    public static void main(String[] args)
    {
        ProcessBuilder proc=new ProcessBuilder("notepad.exe","testfile");
        try
        {
            proc.start();
        }
        catch(Exception e)
        {
            System.out.println("Error executing notepad.");
        }

        ProcessBuilder pb = new ProcessBuilder("java", "MyTest");
        try
        {
            pb.start();
            System.out.println("Process has been started.");
        }
        catch(IOException e)
        {
            e.printStackTrace();

        }
    }

The system is displaying the constructor ProcessBuilder is undefined. I have java 7 installed, jre 1.7 installed. Still I am unable to find the solution.

A: As other suggested, the best option would be rename your class name, other option would be to
java.lang.ProcessBuilder proc=new java.lang.ProcessBuilder("notepad.exe","testfile");

and
java.lang.ProcessBuilder pb = new java.lang.ProcessBuilder("java", "MyTest");

So you are explicitly telling your javac to use ProcessBuilder from java.lang package.

A: You called your own class ProcessBuilder, so it hides the library class. Call your own class something else.

A: Your class ProcessBuilder doesn't have a constructor ProcessBuilder(String...command). My guess is that you wanted to write a demo for java.lang.ProcessBuilder. Using the same name for the demo and the class which you try to use makes things confusing.
I suggest to rename your class to ProcessBuilderDemo. That will make java.lang.ProcessBuilder visible in the code.


text:
Q: Automating Maven Settings file I have artifactory setup on our local network, and we are currently looking to put alot of our projects onto a Hudson box for CI purposes.
Currently to get a project working the user has to checkout the project they are working on, then go to their maven settings.xml file and change it. I would ideally like to streamline these procedures so when you checkout your code you can as part of the build put in the right settings file.
The project im currently refactoring has external dependencies that are pulled in through artifactory, and hudson wont build it as it cannot pull in the external dependencies...
Im still not 100% sure if this is the best course to take, but I want to remove as many manual steps as possible for project setup, and so far this seems to be a major one...

A: I think the best way is that your pom.xml inherit from a common parent pom.xml where stuff like dependencies to some third pary repos are defined.


text:
Q: Are metric tensors (or even pseudo-metric tensors) really metrics? In some discussions of metric tensors $g : TM_p \times TM_p \rightarrow \mathbb R$ (and even of pseudo-metric tensors, for instance in this answer), and of the corresponding first fundamental forms ${\rm d}s^2$,
these (mathematical) objects are referred to as "metric".
Is this serious and correct terminology?
Is it really true that metric tensors, or (even) pseudo-metric tensors, and/or the corresponding first fundamental forms are metrics (in the specific well-known sense),
by which accordingly $g : X \times X \rightarrow \mathbb R$ for some suitable set $X$, such that $\forall x, y, z \in X$:

*

*$g[~x, y~] \neq 0 ~ ~\Leftrightarrow ~ ~ x \not\equiv y ~$ (distinguishability of distinct elements),

*$g[~x, y~] = g[~y, x~]$ (symmetry),

*$g[~x, z~] \le g[~x, y~] + g[~y, z~]$ (subadditivity; triangle inequality)
?

A: From the metric we get a curve length, if the manifold is connected we can define a distance function as the infimum of curve lengths between two points (this exists if the metric is positive definite). It is easily checked that this defines a metric in the usual sense.
A Lorentzian metric does not define a metric in the usual sense, as points may be connected by a zero length curve.

A: Yes, it is true, but note that the metric tensor $g$ defines the distance function on $TM$ and hence a norm, it is not itself the distance function.
In particular, for $TM$ we can define
$$d(\vec{x}, \vec{y}) \equiv \sqrt{g(\vec{x} - \vec{y}, \vec{x} - \vec{y})}
  \quad\forall \vec{x}, \vec{y} \in TM$$
It's relatively easy to show that if $g$ is a metric (as opposed to a pseudometric) this definition of $d$ works as you would expect.
Note that I am answering about the relationship between $g$ and $d$ on $TM$: $g$ also makes $M$ a metric space, but that's a slightly different argumentt.

A: It works if the metric has only positive eigenvalues. It is not the case, for example, for Minkowski space where $g(V,V)=0$ for some vectors (light-like ones).


text:
Q: Wordpress: how to show a list of pages with a meta value under any hierarchy I am coding a website where i have following page structure
1. -university
--India
---Delhi
----north delhi
-----university of delhi
-----Indra prastha university
---Mumbai
----south mumbai
-----university of maharashtra
--Sri lanka
--USA
---California
----University of california

Some of the pages have a custom field 'IsOrganization' with value 'yes'. Such pages are basically child pages of some parent page. in above example, i have all 'university' page meta value 'IsOrganization' set to 'yes'.
Now if some person is on page 'India', I need to display all pages with 'IsOrganization' with value 'yes'.
so if a person is on Page India it should give following list irrespective of hierarchy
*university of delhi
*Indra prastha university
*university of maharashtra

if someone is browsing USA page then it should output
*University of california

I have following code but it outputs the list only if the page is an immediate child.
wp_list_pages( array(
    // Only pages that are children of the current page
    'child_of' => $post->ID,
    'meta_key' => 'Is organization',
    'meta_value' => 'yes',
) );

A: I have got this problem solved by this code.
for those who may need the solution:
<?php

$mypages = get_pages(array( 'child_of' => $post->ID ));
foreach( $mypages as $mypage )
{
    $args = array('meta_key' => 'Is organization',
        'meta_value' =>'yes',
        'post_type' => 'page',
        'post_parent' => $mypage->ID,
        'orderby' => 'date',
        'order' => 'DESC'
    );
    $the_query = new WP_Query( $args );
    while ( $the_query->have_posts() ) : $the_query->the_post();?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

    <?php endwhile;
    wp_reset_postdata();
}
wp_reset_postdata();?>


text:
Q: FastAPI with uvicorn: TLS connection dropped after Client Hello I do run a simple FastAPI server listening on https:
uvicorn main:app --reload --ssl-keyfile=./certs/app-key.pem --ssl-certfile=./certs/full.chain.pem --port 9063 --host 192.168.2.201 --ssl-version=2

It works fine, i can use Postman to access the app via https://192.168.2.201:9063.
But my client is actually a network device (using exactly same API as Postman) and that is failing to establish TLS connection. Device is configured correctly to trust CA certificate. When troubleshooting i have found out what is happening:

*

*network device establishing TCP connection to 192.168.2.201:9063

*network device sends TLS Client Hello (TLS envelope is version 1.0, but inner Client Hello is version 1.2)

*FastAPI app sends empty ACK and then FIN

So it looks like uvicorn does not like that TLS proposal: version or ciphers (my guess). This is what is happening:

I have tried all version uvicorn with --ssl-version=1 but got error invalid or unsupported protocol version 1.
When testing with nmap i can see uvicorn is supporting only TLS 1.2 and 1.3:
michal@certs % nmap --script ssl-enum-ciphers -p 9063 192.168.2.201
Starting Nmap 7.93 ( https://nmap.org ) at 2022-12-27 12:27 CET
Nmap scan report for ise.example.com (192.168.2.201)
Host is up (0.00024s latency).

PORT    STATE SERVICE
443/tcp open  https
| ssl-enum-ciphers:
|   TLSv1.2:
|     ciphers:
|       TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA (ecdh_x25519) - A
|       TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA (ecdh_x25519) - A
|     compressors:
|       NULL
|     cipher preference: server
|   TLSv1.3:
|     ciphers:
|       TLS_AKE_WITH_AES_256_GCM_SHA384 (ecdh_x25519) - A
|       TLS_AKE_WITH_CHACHA20_POLY1305_SHA256 (ecdh_x25519) - A
|       TLS_AKE_WITH_AES_128_GCM_SHA256 (ecdh_x25519) - A
|     cipher preference: server
|_  least strength: A

Is there any way to troubleshoot it ? How to confirm why uvicorn is finishing that TLS session ?
Update: i was able to pass uvicorn argument --ssl-version=3 which looks like is TLS1.0, but still the network device proposal is rejected by uvicorn.
Thanks,
Michal

A: OK, solved the issue, the problem was in the incompatible ciphers used by default by uvicorn (no match between very specific network device proposal and uvicorn).
Once i have discovered all supported ciphers:
import ssl

ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23)
ciphers = ctx.get_ciphers()

v12ciphers = ":".join([cipher['name'] for cipher in ciphers if cipher['protocol'] =='TLSv1.2'])
print(v12ciphers)

And used all of those when starting uvicorn all started to work fine (using TLS 1.2):
--ssl-version=5 --ssl-ciphers="ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256:DHE-RSA-AES256-GCM-SHA384:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-SHA256:DHE-RSA-AES128-SHA256"


text:
Q: async module with c++ v8 for node js,error associated with the types in the structure I am writing asynchronous module, but I can not pass an array structure. Please help. That's the error appears. How to avoid it?
error C2440: '=' : cannot convert from 'v8::Handle' to 'v8::Array *'
struct Async {
    Handle<v8::Array> result;
}
void wmiWorker(uv_work_t* req) {
    Async* request = (Async*)req->data;
    *(request->result) = getArray(1);
}
Handle<Array> getArray(int x) {

  HandleScope handle_scope;
  Handle<Array> array = Array::New(3);

  if (array.IsEmpty())
    return Handle<Array>();

  array->Set(0, Integer::New(x));
  return handle_scope.Close(array);
}

A: Your line
*(request->result) = getArray(1);

assigns a Handle<Array> to *(Handle<Array>) (which means Array*), which is not valid.
However even with that, there is an important factor that you are not taking into account. Your wmiWorker function is running in a separate thread. NodeJS and V8 only allow a single thread of execution for JS, and what you are attempting to do is create a JS array inside of a separate thread.
Instead you will need to create a vector or something, and generate the V8 array from that inside of the work callback's after_work callback.


text:
Q: Python 3.3 Mysql Connector
Possible Duplicate:
MySQL-db lib for Python 3.0?

I use python3.3 and can't connect to MySQL, because I don't find module for MySQL connector.
How do I connect to MySQL with python3.3?

A: As far as I know, nobody has ported the C extension module for mysql to Python 3, but there are at least two pure-Python modules that work just fine with Python 3 (and also with PyPy, etc.):

*

*PyMySQL

*MySQL Connector/Python
A quick google for python3 mysql turns up a few more (as well as various pointers to these two projects, including previous SO questions that ask exactly the same thing).

A: There is a module called Pymysql which you may like:
"""This pure Python MySQL client provides a DB-API to a MySQL database by talking directly to the server via the binary client/server protocol."""

import pymysql
conn = pymysql.connect(host='127.0.0.1', unix_socket='/tmp/mysql.sock', user='root', passwd=None, db='mysql')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
for response in cur:
    print(response)
cur.close()
conn.close()


text:
Q: "BindException: Address already in use" exception when transferring file using java socket in a same pc I am very new to java network programming. I am trying to write a program that can transfer file over the network. I have write two separate program for sender and receiver. And run that two programs in two separate Intellij window in my pc. I have put the same port number in server socket as well as receiver socket. And the IP Address is the localhost. When I run that two program either of that two throws exception.
After some googling I found Java sockets: multiple client threads on same port on same machine? question where people said that it is legitimate to run two program in same port. I haven't to test this code from two different from two PC.
So my question what am I missing ? Can I run this two program in my PC simultaneously?
here is my written code -
for Sender--
public class Sender {
public static void main(String[] args) throws IOException
{
    String fileLocation;
    int portNo;
    portNo = 6000;
    fileLocation = "/files/A.cpp";
    Sender.send(portNo,fileLocation);
}
public static  void send(int portNo,String fileLocation) throws IOException
{

    FileInputStream fileInputStream = null;
    BufferedInputStream bufferedInputStream = null;

    OutputStream outputStream = null;
    ServerSocket serverSocket = null;
    Socket socket = null;
    try {
        serverSocket = new ServerSocket(portNo);
        System.out.println("Waiting for receiver...");
        try {
            socket = serverSocket.accept();
            System.out.println("Accepted connection : " + socket);

            File file = new File (fileLocation);
            byte [] byteArray  = new byte [(int)file.length()];
            fileInputStream = new FileInputStream(file);
            bufferedInputStream = new BufferedInputStream(fileInputStream);
            bufferedInputStream.read(byteArray,0,byteArray.length); // copied file into byteArray

            //sending file through socket
            outputStream = socket.getOutputStream();
            System.out.println("Sending " + fileLocation + "( size: " + byteArray.length + " bytes)");
            outputStream.write(byteArray,0,byteArray.length);
            outputStream.flush();
            System.out.println("Done.");
        }
        finally {
            if (bufferedInputStream != null) bufferedInputStream.close();
            if (outputStream != null) bufferedInputStream.close();
            if (socket!=null) socket.close();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if (serverSocket != null) serverSocket.close();
    }
}
}

for Receiver --
public class Receiver {

public static void main (String [] args ) throws IOException {

    String fileLocation,ipAddress;
    int portNo;
    ipAddress = "localhost";
    portNo = 6000;
    fileLocation = "/files/A.cpp";
    Receiver.receiveFile(ipAddress, portNo, fileLocation);

}
public static void receiveFile(String ipAddress,int portNo,String fileLocation) throws IOException
{
    int bytesRead=0;
    int current = 0;
    FileOutputStream fileOutputStream = null;
    BufferedOutputStream bufferedOutputStream = null;
    Socket socket = null;
    try {
        socket = new Socket(ipAddress,portNo);
        System.out.println("connected.");

        byte [] byteArray  = new byte [6022386];
        System.out.println("Please wait downloading file");

        InputStream inputStream = socket.getInputStream();
        fileOutputStream = new FileOutputStream(fileLocation);
        bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        bytesRead = inputStream.read(byteArray,0,byteArray.length);

        current = bytesRead;
        do {
            bytesRead =inputStream.read(byteArray, current, (byteArray.length-current));
            if(bytesRead >= 0) current += bytesRead;
        } while(bytesRead > -1);
        bufferedOutputStream.write(byteArray, 0 , current);

        System.out.println("File " + fileLocation  + " downloaded ( size: " + current + " bytes read)");
    } catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        if (fileOutputStream != null) fileOutputStream.close();
        if (bufferedOutputStream != null) bufferedOutputStream.close();
        if (socket != null) socket.close();
    }
}
}

Thank you.

A: Your receiver does not need to specify a port to use, leave that to the OS (it will automatically assign a free ephemeral port number; the port number is not important).
Instead, use the Socket.connect(SocketAddress) method to connect the client socket to the server. Specifiy the socket address using the IP/Name of the server plus the port number used, e.g:
InetAddress iadr = InetAddress.getByName("localhost");
SocketAddress sadr = new InetSocketAddress(iadr, portNo);
Socket socket = new Socket();
socket.connect(sadr);

This is how you normally connect to a server at a specfied port. The local (client) endpoint is not explicitly specified.
Of course, the server must already be running for this to succeed.
Edit: Since the client endpoint is automatically assigned, the OS will assign a free endpoint for every client, thus you can run multiple clients (receivers) on the same machine without any conflicts.

A: First it's impossible to use the same port for two serverSockets so your code should work if you don't run the Sender Class twice, you need to correct the name of your class Receiver_ to be Receiver then the steps for your code to be working are :

*

*First you run Receiver Class (always start by the server)

*Then you run Sender Class (which  is the Client here)

*if it doesn't work it might be because another program is using the port 6000, try to change it to another one like 9010 in both of your classses


text:
Q: Получить периоды из таблицы Есть таблица (много строк)
------------------------------------
| id |  cId  |        time         |
------------------------------------
| 1  |   5   | 2017-06-01 10:00:00 |
| 2  |   5   | 2017-06-01 10:01:00 |
| 3  |   5   | 2017-06-01 10:06:00 |
| 7  |   5   | 2017-06-01 10:08:00 |
| 4  |   2   | 2017-07-01 10:05:00 |
| 5  |   2   | 2017-07-01 10:06:00 |
| 6  |   2   | 2017-07-01 10:07:00 |
------------------------------------

Как получить периоды, продолжительность которых больше 180 секунд.
---------------------------------------------------
| cId |        begin        |         end         |
---------------------------------------------------
|  5  | 2017-06-01 10:01:00 | 2017-06-01 10:06:00 |
---------------------------------------------------

A: select cId,min(time) begin,max(time) end
  from `Table5`
 group by cId
having time_to_sec(timediff(max(time),min(time)))>180

A: SELECT b.cid, MIN(b.time) begin, MIN(e.time) end
    FROM foo b INNER JOIN foo e ON (b.cid = e.cid AND b.id < e.id)
    GROUP BY b.cid, b.id
    HAVING TIME_TO_SEC(TIMEDIFF(MIN(e.time), MIN(b.time))) > 180;

Рабочий пример на SQLFiddle


text:
Q: parse.com How to use query limit with query each? I need to order and limit my query, then I need to iterate on the result but is not possible.
Cannot iterate on a query with sort, skip, or limit.

How can I make ?
This is my query, I want my publish post, with tags user and limit to 100 last post:
var query = new Parse.Query('post');
    query.equalTo('publish', true);
    query.descending('createdAt');
    query.containedIn('tags', request.user.get('tags'));
    query.limit(100);
    query.each(function(post) {

        var postJSON = JSON.parse(JSON.stringify(post));
        var promises = [];

        var promise1 = getPseudo(post.get('author').id).then(function(user) {
                postJSON.pseudo = user.get('pseudo');
            }, function(error) {});

        var promise2 = isCertified(post.get('author').id).then(function(result) {
                postJSON.isCertified = !!result;
            }, function(error) {});

        promises.push(promise1, promise2);
        promisesAll.push(promise1, promise2);

        Parse.Promise.when(promises)
            .then(function() {
                posts.push(postJSON);
            }, function(error) {});

    }, {
        success: function() {
            Parse.Promise.when(promisesAll)
                .then(function() {
                    response.success(postsOrdered);
                });
        }
    });

A: You need to load underscore, like so:
var _ = require('underscore');
After you can loop each result like so:
var query = new Parse.Query('post');
    query.equalTo('publish', true);
    query.descending('createdAt');
    query.containedIn('tags', request.user.get('tags'));
    query.limit(100);
    query.find({
        success: function(posts) {

            _.each(function(post) {
                // What you want
            }

        }
    });


text:
Q: Network Interfaces list, abstract type or interface I have program which list HDD drives and Network interfaces like in this picture:

If I click on HDD name I can see drive type in text box. This is working fine.
However if I try this code on network interface its not working. It gave error CS0144: Cannot create an instance of the abstract type or interface 'NetworkInterface'
Here is code:
 private void button2_Click(object sender, EventArgs e)
        {
            listBox1.Items.Clear();
            textBox1.Text = "";
            DriveInfo[] Drives = DriveInfo.GetDrives();
            foreach (DriveInfo drv in Drives)
            {
                listBox1.Items.Add(drv.Name);
            }
        }
        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
            String strDrive = (string)listBox1.SelectedItem;
            DriveInfo drive = new DriveInfo(strDrive);

            textBox1.Text = drive.DriveType.ToString();
        }

And here is not working network interfaces:
private void button3_Click(object sender, EventArgs e)
        {
            listBox2.Items.Clear();
            textBox2.Text = "";
            NetworkInterface[] adapters = NetworkInterface.GetAllNetworkInterfaces();
            foreach (NetworkInterface adapter in adapters)
            {
                listBox2.Items.Add(adapter.Name);
            }
        }

        private void listBox2_SelectedIndexChanged(object sender, EventArgs e)
        {
            String strInterface = (string)listBox2.SelectedItem;
            NetworkInterface adapter = new NetworkInterface(strInterface);
            textBox2.Text = adapter.Description.ToString();
        }

This line is wrong: NetworkInterface adapter = new NetworkInterface(strInterface);

A: From the NetworkInterface docs:

You do not create instances of this class; the GetAllNetworkInterfaces method returns an array that contains one instance of this class for each network interface on the local computer.

So you can call GetAllNetworkInterfaces again and filter the results:
var adapter = NetworkInterface.GetAllNetworkInterfaces()
    .FirstOrDefault(ni => ni.Name == strInterface);
// if not null ...

Or store results of previous call in some field/property and use those for search. Or just use the result array as datasource for listBox2 itself.

A: You can store the NetworkInterface instances directly in the list box items:
listBox2.Items.Add(adapter);

And set listBox2.DisplayMember = nameof(NetworkInterface.Name) to make the list box display their names.
Then you can access the selected adapter as:
var adapter = (NetworkInterface)listBox2.SelectedItem;;


text:
Q: Finding the average of option values containg object in a list I'm new to Scala and I have been struggling with Option and Lists. I have the following object:
object Person {

    case class Person(fName: String,
                      lName: String,
                      jeans: Option[Jeans],
                      jacket: Option[Jacket],
                      location: List[Locations],
                      age: Int)

    case class Jeans(brand: String, price: Int, color: String)
...
}

And I'm trying to write the function that takes as input list of type person and return the average price of their jeans:
def avgPriceJeans(input: List[Person]): Int

A: When you have a list of values and want to reduce all of them to a single value, applying some kind of operation. You need a fold, the most common one would be a foldLeft.
As you can see in the scaladoc. This method receives an initial value and a combination function.
It should be obvious that the initial value should be a zero. And that the combination function should take the current accumulate and add to it the price of the current jeans.
Nevertheless, now we have another problem, the jeans may or may not exists, thus we use option. In this case we need a way to say if they exists give me their price, if not give a default value (which in this case makes sense to be another zero).
And that is precisely what Option.fold give us.
Thus we end with something like:
val sum = input.foldLeft(0) {
  (acc, person) =>
    acc + person.jeans.fold(ifEmpty = 0)(_.price)
}

Now that you need the average, you only need to divide that sum with the count.
However, we can do the count in the same foldLeft, just to avoid an extra iteration.
(I changed the return type, as well as the price property, to Double to ensure accurate results).
def avgPriceJeans(input: List[Person]): Double = {
  val (sum, count) = input.foldLeft((0.0d, 0)) {
    case ((accSum, accCount), person) =>
      (
        accSum   + person.jeans.fold(ifEmpty = 0.0d)(_.price),
        accCount + 1
      )
  }
  sum / count
}

A: As @SethTissue points out, this is relatively straightforward:
val prices = persons.flatMap(_.jeans.map(_.price))
prices.sum.toDouble / prices.length

The first line needs some unpicking:
Taking this from the inside out, the expression jeans.map(_.price) takes the value of jeans, which is Option[Jeans], and extracts the price field to give Option[Int]. The flatMap call is equivalent to map followed by flatten. The map call applies this inner expression to the jeans field of each element of persons. This turns the List[Person] into a List[Option[Int]]. The flatten call extracts all the Int values from Some[Int] and discards all the None values. This gives List[Int] with one element for each Person that had a non-empty jeans field.
The second line simply sums the values in the List, converts it to Double and then divides by the length of the list. Adding error checking is left as an exercise!

A: One approach consist in calculate the value of the jeans price for each element of the list.
After that you can sum all the values (with sum method) and divide by the list size.
I managed the case when jeans is None with 0 as price value (so I consider it for the sum).
Here the code:
def avgPriceJeans(input: List[Person]): Int =
    input.map(_.jeans.map(_.price).getOrElse(0)).sum / input.size


text:
Q: Excel- Average days between group of dates I'm trying to use excel to calculate the average frequency of delivery for a set of parts. I have a data set that has two columns- part number and delivery date. I'm trying to figrue out out oftne parts get delivered, on average, in terms of days. I tried using nested ifs like averageif(a2=a2:b9999,datedif(xx)) etc, but to no avail. I'm looking for this:
Input:
Part A    8.1
Part A    8.8
Part A    8.15

Output: Part A Average Delivery - Every 7 Days
etc etc. Any ideas?

A: If your dates are in ColumnB:
=(MAX(B:B)-MIN(B:B)--1)/COUNT(B:B)

or:
=(MAX(B:B)+1-MIN(B:B))/COUNTA(B:B)

should serve.
Edit
If you have multiple parts (the above assumed only one) and the list is in no particular order then a PivotTable may be best (say with its top left-hand corner in D1), in Tabular form with Part for Row Labels and Delivery three times for Σ Values (the first as MAX, the second as MIN and the third as COUNT). Then  =(1+E3-F3)/G3 copied down should give you the average bumber of days between deliveries. For example 5 in your example (3 deliveries in 15 days).


text:
Q:  in JSF 2.0 breaks methods execution order I have very simple JSF 2.0 application (see below). The problem is that when ui:repeat is present, execution order (I check it using breakpoints in debugger) is strange.
After I submit form, SecondBean.initSomething() is called before FirstBean.setFirstFormField(). If I change type of something to String and delete ui:repeat from index.jsf and use just h:outputText then everything works as expected, FirstBean.setFirstFormField() is called before SecondBean.initSomething().
What I'm doing wrong?
I'm using JDeveloper Studio Edition 11.1.2.2.0 and its stack (WebLogic 10.3.5.0, Java 6 and JSF 2.0).
Here's the code:
index.jsf:
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<f:view xmlns:f="http://java.sun.com/jsf/core" xmlns:h="http://java.sun.com/jsf/html" xmlns:ui="http://java.sun.com/jsf/facelets">
    <html xmlns="http://www.w3.org/1999/xhtml">
        <h:head></h:head>
        <h:body>
            <h:form>
                <h:panelGrid columns="1">
                    <h:inputText value="#{firstBean.firstFormField}" />
                    <h:commandButton action="#{firstBean.processForm}" value="Submit" />
                </h:panelGrid>
            </h:form>
            <ui:repeat value="#{secondBean.something}" var="variable" >
                <h:outputText value="#{variable}" />
            </ui:repeat>
        </h:body>
    </html>
</f:view>

FirstBean.java:
package test.backing;

import javax.faces.bean.*;
import javax.faces.context.FacesContext;

@ManagedBean
@RequestScoped
public class FirstBean {
    private String firstFormField;
    public FirstBean() {
        super();
    }

    public String processForm() {
        FacesContext facesContext;

        facesContext = FacesContext.getCurrentInstance();

        return facesContext.getViewRoot().getViewId();
    }

    public void setFirstFormField(String firstFormField) {
        this.firstFormField = firstFormField;
    }

    public String getFirstFormField() {
        return this.firstFormField;
    }
}

SecondBean.java:
package test.backing;

import java.util.*;

import javax.annotation.PostConstruct;

import javax.faces.bean.*;

@ManagedBean
@RequestScoped
public class SecondBean {
    private List<String> something;

    public SecondBean() {

    }

    @PostConstruct
    public void initSomething() {
        this.something = Arrays.asList("abc", "cde");
    }

    public void setSomething(List<String> something) {
        this.something = something;
    }

    public List<String> getSomething() {
        return this.something;
    }
}

faces-config.xml:
<?xml version="1.0" encoding="UTF-8"?>
<faces-config version="2.0" xmlns="http://java.sun.com/xml/ns/javaee">

</faces-config>

web.xml:
<?xml version = '1.0' encoding = 'UTF-8'?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">
  <context-param>
    <param-name>javax.faces.FACELETS_VIEW_MAPPINGS</param-name>
    <param-value>*.jsf;*.xhtml</param-value>
  </context-param>
  <servlet>
    <servlet-name>Faces Servlet</servlet-name>
    <servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Faces Servlet</servlet-name>
    <url-pattern>/faces/*</url-pattern>
  </servlet-mapping>
</web-app>

A:
What I'm doing wrong?

Nothing. It's working as specified. It's just invoked during restoring the view.
If this is causing a specific problem for you, which is unfortunately not described in detail in the question at all, then a solution needs to be sought in a different direction than depending/relying on some specific execution order of bean construction or getter calls relative to the view. At least, that is what you seem to be targeting at for some reason.

Unrelated to the concrete problem, in that processForm() action method you can also just return null to navigate back to the current view. That's much simpler than the current clumsy approach.

A: This is how the JSF cycle works. The order is correct...
You need to change the manner you are doing agreeing with the rules of the JSF framework.
Learn the phases of the JSF cycle, may this can help you.

A: You can use h:dataTable it does not populate the values during restore phase, it populates the after the updateModel pahse


text:
Q: Best way to initialize a class from files (async)? I have a class I want to initialize with bunch of Strings in my flutter app. It then has to ba async. What is the best way to initialize it ?
Thanks.

A: Yiou can follow the following way to perform your work,
String str1,str2,str3;

    void main() async{
      await initialiseStrings();
      runApp(MyApp());
    }

    initialiseStrings() async{
       // do your async work
       str1="";
       str2="";
       str3="";
    }

runApp() method will be called after initialiseStrings() will be executed. You can initialise the strings inside it and then you can access those strings from any class just by importing the corresponding file


text:
Q: Conversion of datatypes - Javascript I'm confused about how I can implement conversion of different data types in my code below. Conversion includes (int to string, string to int, float to int, etc.) My teacher said this can be easily done when I am reading/writing files, but I'm still confused. I would appreciate any help or suggestions, thank you! Here's my code:
//files
var fs = require("fs");
//reading files
fs.readFile('sources.txt', (err, data) => {
  console.log("File output: " + data.toString());
  //writing files
      fs.writeFile('written.txt',data,(err, result) => {
        if(err) console.log('error', err);
      });
});

// planet class
class Planet{
    constructor(name, numberOfMoons, size) {
        this.name = name;
        this.numberOfMoons = numberOfMoons;
        this.size = size;
    }
    orbit(){
        //return value
        return `${this.name} is a planet and therefore orbits around the sun.`
    }
}

//inheritance class
class DwarfPlanet extends Planet{
    constructor(name, numberOfMoons, size, orbitalNeighbourhood) {
        super(name, numberOfMoons, size);
        this.orbital = orbitalNeighbourhood;
    }

    getOrbital(){
        //return value
        return `${this.name} is a dwarf planet because it doesn't have a clear orbital neighnourhood "`
    }

}

let earth = new Planet('Earth', 1 , 6371);
console.log(earth.orbit());

let pluto = new DwarfPlanet("Pluto", 5 , 1188, 'Kuiper Belt');
console.log(pluto.getOrbital());

//Array of Objects (anonymous option)
var stars = [
    {
        name: 'Sun',
        temperature: 5778,
        colour: 'White'
    },
    {
        name: 'Pistol',
        temperature: 11800,
        colour: 'Blue'
    },
    {
        name: "Antares",
        temperature: 3500,
        colour: "Red"
    }
];

// Array of Objects (using Planet Class)

var planets = [
  new Planet('Earth', 'One moon', '6,371 km'),
  new Planet('Mars', 'Two mooons', '3,389 km'),
  new Planet('Uranus', 'Twenty-seven moons', '25,362 km'),
  new Planet('Saturn', 'Fifty-three moons', '58,232 km'),
];

console.log("Fun Fact: the biggest star isn't the sun, instead it is a blue star called 'Pistol'. Here's some information about it: ");
console.log(stars[1]);

console.log('Here are some planets and their properties:');
console.log(planets);

A: The most straightforward way to read and write files is to use their synchronous counterparts: readFileSync() and writeFileSync(). In order to work with JSON neatly, you can define your functions as:
const filePath = 'planets.json';

function readPlanets() {
    const json = fs.readFileSync(filePath);
    const planets = JSON.parse(json);

    return planets.map(planet => new Planet(
        planet.name,
        planet.numberOfMoons,
        planet.size
    ));
}

function writePlanets(planets) {
    const json = JSON.stringify(planets, null, 4);

    fs.writeFileSync(filePath, json);
}

Then, you can populate your planets.json file:
const planets = [
    new Planet('Earth', 1, 6371),
    new Planet('Mars', 2, 3389),
    new Planet('Uranus', 27, 25362),
    new Planet('Saturn', 53, 58232),
];

writePlanets(planets);

To read it back, you use the readPlanets() function:
const storedPlanets = readPlanets();

Notice how I manually map() data to Planet instances in readPlanets(). JSON itself has no idea of the class - the objects created by JSON.parse() are basic JavaScript objects.
Also notice how I changed the format of your data a bit. Instead of using values like 'Twenty-seven moons' or '6,371 km', I just put a simple number in JSON: 27 and 6371. That's because you usually want to keep your data as raw as possible, because display format is something that you could want to change anytime. The data should persist. If you want to translate these raw numbers to your format, I'd suggest adding methods to your Planet class to return the formatted numbers of the moons and the sizes.


text:
Q: astropy.table.write() IOError: File exists: I am using astropy.table.write(filename, path=run_dir) to write an astropy table to the file named dat.h5. But I am receiving the error that the file exists, which I've shown below with a pdb trace that it does not. What is going on?
(Pdb) run_dir
'/Users/ms/run0'

(Pdb) os.system("ls " + run_dir)
param.txt    temp_in.dat  temp_out.dat
0

(Pdb) os.path.exists(run_dir + '/dat.h5')
False

(Pdb) dat_cube.write('dat.h5', format='hdf5', path=run_dir)
*** IOError: File exists: dat.h5

A: The path variable is meant to be a path within the hdf5 file (see http://docs.astropy.org/en/stable/api/astropy.io.misc.hdf5.write_table_hdf5.html#astropy.io.misc.hdf5.write_table_hdf5; you can see in the source that the path variable is not used for the exists check).  It is not a filesystem path, so your os.path.exists check seems to be looking in the wrong place.
So, (1) check os.getcwd and see if dat.h5 exists there, and (2) try dat_cube.write(os.path.join(runpath, 'dat.h5'), format='hdf5', path="mypath").


text:
Q: API Platform related entities on resource creation Is there a way of passing array of ids of already created related entities on entity creation resource? The default docs say about creating everything on post request.
Some data.
I have Squad entity:
/**
 * @ApiResource(iri="http://schema.org/Squad")
 * @ORM\Table(name="squads")
 * @ORM\Entity()
 */
class Squad
{
    use IdentityAutoStrategy, Timestamps;

    /**
     * @var string
     * @ORM\Column(type="string", length=25, unique=true)
     */
    private $name;

    /**
     * @var Collection|User[]|null
     * @ORM\OneToMany(targetEntity="User", mappedBy="squad")
     * @ApiProperty(
     *     attributes={
     *         "swagger_context"={
     *             "$ref"="#/definitions/User",
     *         }
     *     }
     * )
     * @ApiSubresource(max_depth=1)
     */
    private $users;

And User entity:
/**
 * @ApiResource()
 * @ORM\Table(name="users")
 * @ORM\Entity(repositoryClass="GPL\Repository\UserRepository")
 */
class User implements UserInterface, Serializable
{
    use Timestamps, IdentityAutoStrategy;

    /**
     * @ORM\Column(type="string", length=25, unique=true)
     */
    private $username;

    /**
     * @ORM\Column(type="string", length=64)
     */
    private $password;

    /**
     * @ORM\Column(type="string", length=254, unique=true)
     */
    private $email;

    /**
     * @ORM\Column(name="is_active", type="boolean")
     */
    private $isActive;

    /**
     * @var Squad
     * @ORM\ManyToOne(targetEntity="Squad", inversedBy="users")
     * @ORM\JoinColumn(name="squad_id", referencedColumnName="id")
     * @ApiProperty(
     *     attributes={
     *         "swagger_context"={
     *             "$ref"="#/definitions/Squad",
     *         }
     *     }
     * )
     */
    private $squad;

The main thins I want to achieve is to send POST /api/squads with "users": [1,2,3] where 1, 2, 3 is id of existing users and links them to created Squad entity. Is this available using some default annotations from api-platform? Or how can i do this?

A: For JSON-LD you can use IRIs like this:
users: ["users/1", "users/2"]

Keep in mind, that this won't work if you disable GET item operation in your users resource.
You can also enforce this and disable embedded data to prevent your clients from creating new users by excluding all your user field groups.
/**
 * @ApiResource(attributes={
 * "normalization_context"={"groups"={"squad", "squad:user", "user"}},
 * "denormalization_context"={"groups"={"squad", "squad:user"}}
 * })
 */
class Squad
{

...

/**
 * ...
 * @Groups("squad")
 */
private $name;

/**
 * ...
 * @Groups("squad:user")
 */
private $users;

...
class User
{

 /**
  * ...
  * @Groups("user")
  */
 private $username;
...


text:
Q: How to groupby one column in ndarray but then print whole rows I've got an array that looks like:
sna =
[[      5376       5562 1487764215          7]
 [      5000       5101 1487764215          8]
 [      3305       3510 1487764215          9]
 [      3511       3642 1487764240          3]
 [      9748      10320 1487764240          4]
 [      9202       9747 1487764260          7]
 [      6793       7173 1487764260         14]...]

I want to group those that have consecutive numbers in col3 and same number in col2 together.
I've got something that groups them together correctly but only prints out col4:
for k, g in groupby(enumerate(sna[:,3]), lambda(i, x): i-x):
    print map(itemgetter(1), g)

With this method is it even possible to print out the whole rows, or do I need to go about this some other way?
The output I'm looking for is something like this:
[[      5376       5562 1487764215          7]
 [      5000       5101 1487764215          8]
 [      3305       3510 1487764215          9]]
[[      3511       3642 1487764240          3]
 [      9748      10320 1487764240          4]]

A: For anyone who is having the same problem, I ended up putting it into a panda dataframe:
columns = ['one','two','three','four']
df = pd.DataFrame(sna,columns=columns)
kar = []
[[kar.append(h) for m,h in g.groupby(g['four'] -
np.arange(g.shape[0])) if len(h) > 1] for k,g in
df.groupby(df['three'])]


text:
Q: OSError when loading txt file in numpy I have a problem loading a txt file from a Google drive to numpy. It got OSError. I put all the .py file and txt file in the same folder but it didn't work. I read through some similar topics and it seems like it may be because the file is made from OS user (if I understand correctly).
My code is just simple like this:
import numpy as np
data = np.loadtxt("weight_height_1.txt", delimiter=",")
Error message:
https://i.stack.imgur.com/dgOFJ.png
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Users\Long Le\AppData\Local\Programs\Python\Python38\lib\site-packages\numpy\lib\npyio.py", line 1065, in loadtxt
    fh = np.lib._datasource.open(fname, 'rt', encoding=encoding)
  File "C:\Users\Long Le\AppData\Local\Programs\Python\Python38\lib\site-packages\numpy\lib\_datasource.py", line 194, in open
    return ds.open(path, mode, encoding=encoding, newline=newline)
  File "C:\Users\Long Le\AppData\Local\Programs\Python\Python38\lib\site-packages\numpy\lib\_datasource.py", line 531, in open
    raise IOError("%s not found." % path)
OSError: weight_height_1.txt not found.

A: You put the .txt file and .py file in the same directory, so the problem is most likely an error in the name.
Check if the txt file is named exactly weight_height_1.txt, Python is case-sensitive so care about capitalization!


text:
Q: How to add extra item in asp .net mvc dropdownlist from controller I am using ViewModel to create view in my asp .net MVC application. In this view I need to bind a dropdownlist (Successfully binded).
Problem: I want to add extra items with value in dropdownlist like "select","0"
Here is my Viewmodel:
 public class PagesViewModel
{
    public int Id { get; set; }

    [Required]
    [Display(Name = "Page Name")]
    public string PageName { get; set; }

    [Display(Name = "Parent Page")]
    public IEnumerable<Page> Page { get; set; }
}

My Controller:
 public ActionResult Create()
    {
        var model = new PagesViewModel
        {
            Page = db.Pages.Where(s => s.IsActive == true).OrderBy(r => r.PageName)

        };
        //--- Here I need to add extra items manually
        return View(model);
    }

My View:
  @Html.DropDownListFor(model => model.Id, new SelectList(Model.Page, "Id", "PageName"), "Select Parent Page", htmlAttributes: new { @class = "form-control" })

A: There is an overload for the DropDownListFor helper that allows you to specify an option label - I assume that is what you are after.
@Html.DropDownListFor(m => m.SomeID, Model.SomeSelectList, "Select one...", new { @class="your-class-here" })

This will render a <option> element with a value="" attribute:
<select id="SomeId" name="SomeId" class="your-class-here">
    <option value="">Select one...</option>
    <!-- ... the rest of the items from the SelectList -->
</select>

Otherwise, your Pages property needs to be something that derives from ICollection (like a List), which will allow you to add items:
Model:
public class PagesViewModel
{
    public int Id { get; set; }

    [Required]
    [Display(Name = "Page Name")]
    public string PageName { get; set; }

    [Display(Name = "Parent Page")]
    public ICollection<Page> Page { get; set; }
}

Controller:
public ActionResult Create()
{
    var model = new PagesViewModel
    {
        Page = db.Pages.Where(s => s.IsActive == true)
            .OrderBy(r => r.PageName)
            .ToList()
    };

    model.Pages.Add(new Page{ /* ... object initializers here */ });

    return View(model);
}

A: try this
     var model = new PagesViewModel
            {
                Page = db.Pages.Where(s => s.IsActive == true).OrderBy(r => r.PageName)

            };
model.Page.Add(new Page{ Name='ABC' ... }) // You can define your properties here

A: public ActionResult Create()
    {
        var model = new PagesViewModel
        {
            Page = db.Pages.Where(s => s.IsActive == true).OrderBy(r => r.PageName)

        };
List<SelectListItem> listItem = new List<SelectListItem>();
foreach(var item in Model)
{
    listItem.Add(new SelectListItem{Text = item.PageName, Value=item.Id});
}
listItem.Add( new SelectListItem{Text = "SomeText", Value="Some Value"});
        //--- Here I need to add extra items manually
        return View(model);
    }

you can also insert your optional text at top by linq extension method Insert(index, ValueToBeInserted). index will be zero if you want insert at top.
Please mark as anser if helped.


text:
Q: Как после отправки формы перенаправить пользователя на текущую страницу без зацикливания? пробую исправить так но все равно на главной оказываюсь
подскажите пожалуйста ,у меня есть форма в личном кабинете,но с нее бросает на главную
global $user_ID, $user_LK;
if($user_ID == $user_LK): ?>
<form method="POST" action="/" class="premium-form">
    <input type="hidden" name="premium-form_nonce" value="<?php echo wp_create_nonce("premium-form_nonce")?>">
    <input type="submit" value="Премеум" title="premium" style="background-color:#b93228;color:#fff;width: 90%;">
</form>
<?php endif; ?>

вот ее обработчик в function.php
 if (isset( $_POST['premium-form_nonce'])) {

        $user_ID = get_current_user_id();

     if( wp_verify_nonce( $_POST['premium-form_nonce'], 'premium-form_nonce' )  &&  rcl_get_user_rating($user_ID) > 100) {

         $args = array(
          'rating_value' => -10,
          'object_author' => $user_ID
          );

         update_user_meta( $user_ID, 'premeum', 1);
         update_user_meta( $user_ID, 'premeum-time',current_time('timestamp', 1));

// тут редирект на текущюю
        global $wp;
        wp_redirect(home_url(add_query_arg(array($_GET), $wp->request)));
      }
    }

A: Изменить адрес в форме
изменить
<form method="POST" action="/" class="premium-form">

на
<form method="POST" action="" class="premium-form">

Также обработчик должен быть в хуке 'init'
add_action('init',  'processForm');

function processForm() {
    if (isset( $_POST['premium-form_nonce'])) {

        $user_ID = get_current_user_id();

     if( wp_verify_nonce( $_POST['premium-form_nonce'], 'premium-form_nonce' )  &&  rcl_get_user_rating($user_ID) > 100) {

         $args = array(
          'rating_value' => -10,
          'object_author' => $user_ID
          );

         update_user_meta( $user_ID, 'premeum', 1);
         update_user_meta( $user_ID, 'premeum-time',current_time('timestamp', 1));

// тут редирект на текущюю
        global $wp;
        wp_redirect(home_url(add_query_arg(array($_GET), $wp->request)));
      }
    }
}