text:
Q: I want to generate a unique id in Oracle, it contains alphanumerics and length is 9-digits.please help me out I want to generate a unique id in Oracle, it contains alphanumerics and length is 9-digits.
I tried,
==> select substr(sys_guid(),5,9) guid from dual;
will it have the unique nature?
please anyone help me out.
Thank u.

A: No, this approach will not have the unique nature.

A: if you want auto increment in your column value you can use Sequence for the this.
CREATE OR REPLACE SEQUENCE dept_seq
INCREMENT BY 1
START WITH 100000000
NOMAXVALUE
NOCYCLE
CACHE 10;

after creating sequence you can use After Insert Trigger to insert identical value.
here is trigger example...
CREATE OR REPLACE TRIGGER dep_ins_trig
BEFORE INSERT ON <table_name>
FOR EACH ROW

BEGIN
  SELECT dept_seq.NEXTVAL
  INTO   :new.emp_id
  FROM   dual;
END;
/

---------------------------------------------------------------------------------------
Trigger and Sequence can be used when you want serialized (Auto Increment) number that anyone can easily read/remember/understand. But if you don't want to manage ID Column (like emp_id) by this way, and value of this column is not much considerable, you can use SYS_GUID() at Table Creation to get Auto Increment like this.
CREATE TABLE <table_name>
(emp_id RAW(16) DEFAULT SYS_GUID() PRIMARY KEY,
name VARCHAR2(30));

Now your emp_id column will accept "globally unique identifier value".
you can insert value in table by ignoring emp_id column like this.
INSERT INTO <table_name> (name) VALUES ('name value');

So, it will insert unique value to your emp_id Column.

A: Seems to be overcomplicated when you cound just use a numeric sequence but you could do:
SQL Fiddle
Oracle 11g R2 Schema Setup:
CREATE OR REPLACE FUNCTION numberToAlnumString(
 n IN NUMBER
) RETURN VARCHAR2
AS
 i NUMBER := n;
 s VARCHAR2(9);
 r NUMBER(2,0);
BEGIN
  WHILE i > 0 LOOP
    r := MOD( i, 36 );
    i := ( i - r ) / 36;
    IF ( r < 10 ) THEN
      s := TO_CHAR(r) || s;
    ELSE
      s := CHR( 55 + r ) || s;
    END IF;
  END LOOP;
  RETURN LPAD( s, 9, '0' );
END;
/

CREATE SEQUENCE test__id__seq INCREMENT BY 1 START WITH 1
/

CREATE TABLE test (
  id CHAR(9) NOT NULL,
  name VARCHAR2(20)
)
/

CREATE OR REPLACE TRIGGER test_ins_trig
BEFORE INSERT ON test
FOR EACH ROW
BEGIN
  :new.id := numberToAlnumString( test__id__seq.NEXTVAL );
END;
/

INSERT INTO test ( name )
SELECT TO_CHAR( LEVEL )
FROM DUAL
CONNECT BY LEVEL < 100
/

Query 1:
SELECT * FROM test

Results:
|        ID | NAME |
|-----------|------|
| 000000001 |    1 |
| 000000002 |    2 |
| 000000003 |    3 |
| 000000004 |    4 |
| 000000005 |    5 |
| 000000006 |    6 |
| 000000007 |    7 |
| 000000008 |    8 |
| 000000009 |    9 |
| 00000000A |   10 |
| 00000000B |   11 |
| 00000000C |   12 |
| 00000000D |   13 |
| 00000000E |   14 |
| 00000000F |   15 |
| 00000000G |   16 |
| 00000000H |   17 |
| 00000000I |   18 |
| 00000000J |   19 |
| 00000000K |   20 |
| 00000000L |   21 |
| 00000000M |   22 |
| 00000000N |   23 |
| 00000000O |   24 |
| 00000000P |   25 |
| 00000000Q |   26 |
| 00000000R |   27 |
| 00000000S |   28 |
| 00000000T |   29 |
| 00000000U |   30 |
| 00000000V |   31 |
| 00000000W |   32 |
| 00000000X |   33 |
| 00000000Y |   34 |
| 00000000Z |   35 |
| 000000010 |   36 |
| 000000011 |   37 |
| 000000012 |   38 |
| 000000013 |   39 |
| 000000014 |   40 |
| 000000015 |   41 |
| 000000016 |   42 |
| 000000017 |   43 |
| 000000018 |   44 |
| 000000019 |   45 |
| 00000001A |   46 |
| 00000001B |   47 |
| 00000001C |   48 |
| 00000001D |   49 |
| 00000001E |   50 |
| 00000001F |   51 |
| 00000001G |   52 |
| 00000001H |   53 |
| 00000001I |   54 |
| 00000001J |   55 |
| 00000001K |   56 |
| 00000001L |   57 |
| 00000001M |   58 |
| 00000001N |   59 |
| 00000001O |   60 |
| 00000001P |   61 |
| 00000001Q |   62 |
| 00000001R |   63 |
| 00000001S |   64 |
| 00000001T |   65 |
| 00000001U |   66 |
| 00000001V |   67 |
| 00000001W |   68 |
| 00000001X |   69 |
| 00000001Y |   70 |
| 00000001Z |   71 |
| 000000020 |   72 |
| 000000021 |   73 |
| 000000022 |   74 |
| 000000023 |   75 |
| 000000024 |   76 |
| 000000025 |   77 |
| 000000026 |   78 |
| 000000027 |   79 |
| 000000028 |   80 |
| 000000029 |   81 |
| 00000002A |   82 |
| 00000002B |   83 |
| 00000002C |   84 |
| 00000002D |   85 |
| 00000002E |   86 |
| 00000002F |   87 |
| 00000002G |   88 |
| 00000002H |   89 |
| 00000002I |   90 |
| 00000002J |   91 |
| 00000002K |   92 |
| 00000002L |   93 |
| 00000002M |   94 |
| 00000002N |   95 |
| 00000002O |   96 |
| 00000002P |   97 |
| 00000002Q |   98 |
| 00000002R |   99 |


text:
Q: how to close network stream connection properly? I have an application that is connecting to some network server (tcp) and is connected using a network stream:
if (!SSL)
{
     _networkStream = new System.Net.Sockets.TcpClient(Server, Port).GetStream();
     _StreamWriter = new System.IO.StreamWriter(_networkStream);
     _StreamReader = new System.IO.StreamReader(_networkStream, Encoding.UTF8);
}

if (SSL)
{
     System.Net.Sockets.TcpClient client = new System.Net.Sockets.TcpClient(Server, Port);
     _networkSsl = new System.Net.Security.SslStream(client.GetStream(), false,
                    new System.Net.Security.RemoteCertificateValidationCallback(Protocol.ValidateServerCertificate), null);
     _networkSsl.AuthenticateAsClient(Server);
     _StreamWriter = new System.IO.StreamWriter(_networkSsl);
     _StreamReader = new System.IO.StreamReader(_networkSsl, Encoding.UTF8);
}

///// since now I working with both reader and writer globally in multiple threads

I am using reader and writer asynchronously (in 2 threads) and I need to have both of these streams globally available (they are defined as public references on class level), so I don't know if using statement can be used here.
How should I properly close this connection? All objects (NetworkStream, stream writer and reader) have the Close() method. Should I call it for all of them? Or only 1 of them? Is there any need to release some resources?

A: Put them in a using block.  It will close and dispose of each stream appropriately after the operation has been completed.
using (StreamReader reader = new StreamReader(_networkStream, Encoding.UTF8))
{

}

A: Use using() {} blocks. This way all Connections/streams are properly closed after usage.
using(_networkStream = new System.Net.Sockets.TcpClient(Server, Port).GetStream())
{
    using(_StreamWriter = new System.IO.StreamWriter(_networkStream))
    {
      //do stuff
    }
    using(_StreamReader = new System.IO.StreamReader(_networkStream, Encoding.UTF8))
    {
       //do stuff
    }
 }

A: When they are disposed of, StreamReader and StreamWriter each dispose of the underlying NetworkStream automatically by default.  Because of this, if you are using both a reader and a writer, you might get an "object already disposed" type of exception when you try to close the second one.  I prefer to dispose of the stream itself but not the reader/writer since it's pointless in that case.
using stream = tcpClient.GetStream();
var reader = new StreamReader(stream);
var writer = new StreamWriter(stream);
// <use reader and writer>
// <the using statement ensures the stream is disposed of>

If you insist on disposing of the reader and writer, you can disable their default auto-close-the-stream behavior via the leaveOpen parameter:
new StreamReader(stream, leaveOpen: true)
new StreamWriter(stream, leaveOpen: true)

Making use of using is ideal if possible, but the other way to accomplish the same is to manually call the stream's Close() method or, equivalently, its Dispose() method.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Python time.sleep() not sleeping I'm coding a game, and the fight function seems to be tripping me up. Here's the combat snippet of my code:
def combat(player, enemy, dun):
  print("\n"*100 + "A " + enemy.name + " has attacked you!")
  while player.health > 0 and enemy.health > 0:
    print(enemy.name[:1].upper() + enemy.name[1:], "health:", enemy.health)
    print("Your health:", player.health)
    cmd = input(">")
    if cmd == "attack":
      enemy.health -= player.atk(enemy)
    if cmd == "run":
      coin = random.choice(["heads", "tails"])
      if coin == "heads":
        break
      else:
        print("You couldn't escape.")
    if cmd == "equip":
      target = input("Which item?\n>")
      print(player.equip(target))
    player.health -= enemy.atk(player)

  if enemy.health <= 0:
    print("You defeated the", enemy.name + "!")
    if enemy.drop != None:
      return "Enemy defeated.\nThe " + enemy.name + " dropped a " + enemy.drop + "!"
      dun.data[dun.pos][2].append(enemy.drop)
    else:
      return "Enemy defeated."
    time.sleep(1.5)
    out = 1
  elif player.health <= 0:
    print("You died fighting %s..." % enemy.name)
    dun.pos == (0, 0)
    player.inventory == []
    return "You reawaken in the same room you started in, pack empty..."
    time.sleep(3)

I have imported the random module and the time module, it's just not in the snippet.
When the sequence ends, it does not sleep and goes right away into the main game loop (which I can give if needed).
Apart from being messy, what am I doing wrong?

A: The return statement immediately exits your function. Any code after it will not run. You can sleep before your return:
example:
time.sleep(1.5)
return "Enemy defeated."

But it probably makes a lot more sense to just sleep after you call your function:
combat(...)
time.sleep(5)


text:
Q: Can I name a JavaScript function and execute it immediately? I have quite a few of these:
function addEventsAndStuff() {
  // bla bla
}
addEventsAndStuff();

function sendStuffToServer() {
  // send stuff
  // get HTML in response
  // replace DOM
  // add events:
  addEventsAndStuff();
}

Re-adding the events is necessary because the DOM has changed, so previously attached events are gone. Since they have to be attached initially as well (duh), they're in a nice function to be DRY.
There's nothing wrong with this set up (or is there?), but can I smooth it a little bit? I'd like to create the addEventsAndStuff() function and immediately call it, so it doesn't look so amateuristic.
Both following respond with a syntax error:
function addEventsAndStuff() {
  alert('oele');
}();

(function addEventsAndStuff() {
  alert('oele');
})();

Any takers?

A:
There's nothing wrong with this set up (or is there?), but can I smooth it a little bit?

Look at using event delegation instead. That's where you actually watch for the event on a container that doesn't go away, and then use event.target (or event.srcElement on IE) to figure out where the event actually occurred and handle it correctly.
That way, you only attach the handler(s) once, and they just keep working even when you swap out content.
Here's an example of event delegation without using any helper libs:
(function() {
  var handlers = {};

  if (document.body.addEventListener) {
    document.body.addEventListener('click', handleBodyClick, false);
  }
  else if (document.body.attachEvent) {
    document.body.attachEvent('onclick', handleBodyClick);
  }
  else {
    document.body.onclick = handleBodyClick;
  }

  handlers.button1 = function() {
    display("Button One clicked");
    return false;
  };
  handlers.button2 = function() {
    display("Button Two clicked");
    return false;
  };
  handlers.outerDiv = function() {
    display("Outer div clicked");
    return false;
  };
  handlers.innerDiv1 = function() {
    display("Inner div 1 clicked, not cancelling event");
  };
  handlers.innerDiv2 = function() {
    display("Inner div 2 clicked, cancelling event");
    return false;
  };

  function handleBodyClick(event) {
    var target, handler;

    event = event || window.event;
    target = event.target || event.srcElement;

    while (target && target !== this) {
      if (target.id) {
        handler = handlers[target.id];
        if (handler) {
          if (handler.call(this, event) === false) {
            if (event.preventDefault) {
              event.preventDefault();
            }
            return false;
          }
        }
      }
      else if (target.tagName === "P") {
        display("You clicked the message '" + target.innerHTML + "'");
      }
      target = target.parentNode;
    }
  }

  function display(msg) {
    var p = document.createElement('p');
    p.innerHTML = msg;
    document.body.appendChild(p);
  }

})();

Live example
Note how if you click the messages that get dynamically added to the page, your click gets registered and handled even though there's no code to hook events on the new paragraphs being added. Also note how your handlers are just entries in a map, and you have one handler on the document.body that does all the dispatching. Now, you probably root this in something more targeted than document.body, but you get the idea. Also, in the above we're basically dispatching by id, but you can do matching as complex or simple as you like.
Modern JavaScript libraries like jQuery, Prototype, YUI, Closure, or any of several others should offer event delegation features to smooth over browser differences and handle edge cases cleanly. jQuery certainly does, with both its live and delegate functions, which allow you to specify handlers using a full range of CSS3 selectors (and then some).
For example, here's the equivalent code using jQuery (except I'm sure jQuery handles edge cases the off-the-cuff raw version above doesn't):
(function($) {

  $("#button1").live('click', function() {
    display("Button One clicked");
    return false;
  });
  $("#button2").live('click', function() {
    display("Button Two clicked");
    return false;
  });
  $("#outerDiv").live('click', function() {
    display("Outer div clicked");
    return false;
  });
  $("#innerDiv1").live('click', function() {
    display("Inner div 1 clicked, not cancelling event");
  });
  $("#innerDiv2").live('click', function() {
    display("Inner div 2 clicked, cancelling event");
    return false;
  });
  $("p").live('click', function() {
    display("You clicked the message '" + this.innerHTML + "'");
  });

  function display(msg) {
    $("<p>").html(msg).appendTo(document.body);
  }

})(jQuery);

Live copy

A: Your code contains a typo:
(function addEventsAndStuff() {
  alert('oele');
)/*typo here, should be }*/)();

so
(function addEventsAndStuff() {
  alert('oele');
 })();

works. Cheers!
[edit] based on comment: and this should run and return the function in one go:
var addEventsAndStuff = (
 function(){
  var addeventsandstuff =  function(){
    alert('oele');
  };
  addeventsandstuff();
  return addeventsandstuff;
 }()
);

A: You might want to create a helper function like this:
function defineAndRun(name, func) {
    window[name] = func;
    func();
}

defineAndRun('addEventsAndStuff', function() {
    alert('oele');
});

A: Even simpler with ES6:
var result = ((a, b) => `${a} ${b}`)('Hello','World')
// result = "Hello World"
var result2 = (a => a*2)(5)
// result2 = 10
var result3 = (concat_two = (a, b) => `${a} ${b}`)('Hello','World')
// result3 = "Hello World"
concat_two("My name", "is Foo")
// "My name is Foo"

A: There is a good shorthand to this (not needing to declare any variables bar the assignment of the function):
var func = (function f(a) { console.log(a); return f; })('Blammo')

A: If you want to create a function and execute immediately -
// this will create as well as execute the function a()
(a=function a() {alert("test");})();

// this will execute the function a() i.e. alert("test")
a();

A: There's nothing wrong with the example you posted in your question..  The other way of doing it may look odd, but:
var addEventsAndStuff;
(addEventsAndStuff = function(){
    // add events, and ... stuff
})();

There are two ways to define a function in JavaScript.  A function declaration:
function foo(){ ... }

and a function expression, which is any way of defining a function other than the above:
var foo = function(){};
(function(){})();
var foo = {bar : function(){}};

...etc
function expressions can be named, but their name is not propagated to the containing scope.  Meaning this code is valid:
(function foo(){
   foo(); // recursion for some reason
}());

but this isn't:
(function foo(){
    ...
}());
foo(); // foo does not exist

So in order to name your function and immediately call it, you need to define a local variable, assign your function to it as an expression, then call it.

A: Try to do like that:
var addEventsAndStuff = (function(){
    var func = function(){
        alert('ole!');
    };
    func();
    return func;
})();

A: For my application I went for the easiest way. I just need to fire a function immediately when the page load and use it again also in several other code sections.
function doMyFunctionNow(){
    //for example change the color of a div
}

var flag = true;
if(flag){
    doMyFunctionNow();
}


text:
Q: Syntax error when using date format options Running on MacOS.
Learning bash so bear with me. I have a simple bash script that looks like this:
#!/bin/bash

RUN_DATE=`date +%Y_%m_%d`
python3 /path/to/some/builder.py --date=$RUN_DATE

Where I have a program called builder.py and it takes an date input. I want to write a bash script that sets $RUN_DATE to whatever the date it is at the time of the run. It will be read in Python as a string input. However, I get the following error:
RUN_DATE=`date +%Y_%m_%d`
         ^
SyntaxError: invalid syntax

Is there something obvious I'm overlooking to get this to work?


text:
Q: android scrollview not working with cardView and with noActionBar theme Below xml contains a ScrollView and a Cardview but scrolling is not working for the ScrollView. I have added below line in manifest for below layout:
<activity android:windowSoftInputMode="adjustPan"
        android:name=".activities.RegisterActivity" />

Can anyone help me to fix this issue?
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/white"
    android:fillViewport="true">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
          <RelativeLayout
            android:id="@+id/relative"
            android:layout_width="match_parent"
            android:layout_height="@dimen/margin_400dp"
            android:layout_margin="@dimen/margin_10dp">
 <android.support.v7.widget.CardView
                android:id="@+id/cardview"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:visibility="visible"
                app:cardBackgroundColor="@color/white"
                app:cardCornerRadius="@dimen/margin_5dp"
                app:cardElevation="@dimen/margin_20dp"
                app:cardPreventCornerOverlap="true"
                app:cardUseCompatPadding="true">

                <LinearLayout
                    android:id="@+id/linearLayout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_margin="@dimen/margin_10dp"
                    android:orientation="vertical">

                    <ImageView
                        android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:layout_gravity="center"
                        android:layout_marginTop="@dimen/margin_10dp"
                        android:src="@drawable/user_default" />

                    <android.support.design.widget.TextInputLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_marginTop="@dimen/margin_10dp"
                        android:textColorHint="@color/blue">

              <android.support.design.widget.TextInputEditText
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/margin_50dp"
                            android:hint="@string/Email"
                            android:inputType="textEmailAddress"
                            android:textColor="@color/blue"
                            android:textColorHint="@color/blue"
                            android:theme="@style/MyEditTextTheme" />
                    </android.support.design.widget.TextInputLayout>

                    <android.support.design.widget.TextInputLayout

                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"

                        android:textColorHint="@color/blue">

              <android.support.design.widget.TextInputEditText
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/margin_50dp"
                            android:hint="@string/Name"
                            android:inputType="text"
                            android:textColor="@color/blue"
                            android:textColorHint="@color/blue"
                            android:theme="@style/MyEditTextTheme" />
                    </android.support.design.widget.TextInputLayout>

                    <android.support.design.widget.TextInputLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:hint="@string/Password"
                        android:textColorHint="@color/blue"
                        app:passwordToggleEnabled="true"
                        app:passwordToggleTint="@color/blue">

              <android.support.design.widget.TextInputEditText
                            android:layout_width="match_parent"
                            android:layout_height="@dimen/margin_50dp"
                            android:hint="@string/Password"
                            android:inputType="textPassword"
                            android:textColor="@color/blue"
                            android:textColorHint="@color/blue"
                            android:theme="@style/MyEditTextTheme" />
                    </android.support.design.widget.TextInputLayout>

                </LinearLayout>

            </android.support.v7.widget.CardView>

        </RelativeLayout>

        <android.support.v7.widget.AppCompatButton
            android:id="@+id/btn_signup"
            android:layout_width="@dimen/margin_120dp"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:layout_below="@+id/relative"
            android:layout_gravity="bottom|center"
            android:layout_marginRight="@dimen/margin_60dp"
            android:layout_marginTop="@dimen/margin_m65dp"
            android:background="@drawable/rounded_textview"
            android:gravity="center"
            android:padding="@dimen/margin_10dp"
            android:text="@string/Sign_up"
            android:textColor="@color/white"
            android:textSize="18sp"
            android:textStyle="bold" />

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/relative"
            android:layout_centerHorizontal="true"
            android:layout_marginBottom="@dimen/margin_10dp"
            android:orientation="vertical">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:padding="@dimen/margin_10dp"
                android:text="@string/already_have_an_account"
                android:textSize="16sp" />

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:gravity="center"
                android:padding="@dimen/margin_5dp"
                android:text="@string/Login"
                android:textColor="@color/blue"
                android:textSize="18sp"
                android:textStyle="bold" />

        </LinearLayout>
    </RelativeLayout>
</ScrollView>

A: Use android.support.v4.widget.NestedScrollView instead of ScrollView.


text:
Q: Javascript/Php - Redirect when action form page typed directly in URL I am wanting to know if it is possible to redirect a page (to a home page) if the Url is typed directly in the address box, without it affecting my form action page.
When the user logs in, it redirects to separate page (cust_login). However, if the user is redirected to the cust_login page and then presses the refresh button (or goes to the cust_login page directly), my css is messed up and it all looks a shambles.
If anyone can help me on this, I would be grateful.
Example
<form action="localhost/cust_login.php" method="post" name="login_form">
<input type="text" name="username" class="box" value="Email Address"/>
<input type="text" name="password" class="box" value="Password"/>
<input type="submit" class="submit" value="Login" />
</form>

This login form would be included on every page.

A: Okay, I figured this out using PHP (Thanks to @HarshaBhat who made me realise that this could be PHP too).
Basically my form action would be included in each page, therefore trying to use php header to send user to home page would inevitably cause a redirect loop.
Therefore on each page except the cust_login.php I have included a $login_check set to true.
Then on the cust_login.php I have put the following:
if(isset($_POST['username']))
{ //
}elseif(isset($login_check)){
//
}else{
header("Location: localhost/home.php");
exit;
} –


text:
Q: Connection to local MySQL server succeeds with wrong connection details? I use MySQL within my application and I just tried to connect to my local MySQL server.
First I tried to connect using the right connection details (localhost, user: root, no password). It succeeds.
Then I tried to connect using the wrong connection details (localhost, user: root1, password: 123). It failed.
But if i leave the password blank then it succeeds? I dont know why but everytime i leave the password blank and only provide a username (whatever username you can imagine) it succeeds!
Can anyone help me with this crazy error? Dont know why the server doesn't reject my connection attempt.
Thanks in advance!

A: I would suggest you to changed the root password to something it hasn't been before. Then, FLUSH PRIVILEGES. Problem solved. You won't be able to log in locally with a blank password (same through PhpMyAdmin).
For more details, you can visit this link: http://dev.mysql.com/doc/refman/5.0/en/default-privileges.html


text:
Q: Is it possible to create relationship with data in array Laravel + MongoDB I have a collection with Data1 like
{
  _id : "1",
  total_amount : 5876,
  date: "20-Jun-2018"
},
{
  _id : "2",
  total_amount : 5776,
  date: "20-Jun-2018"
}

I want to store these data in another collection Data2 as follows :
{
   name : "XYZ",
   adjustments : [
   {
         data1_id : "1",
         adjust_amount : 675

   },
   {
         data1_id : "2",
         adjust_amount : 6785

   }

  ]
}

Storing this data isn't a problem in an array of Objects form. But is there any way I can create a relationship with the data within the array adjustments?
At the time of listing, I want adjustments with adjust_amount and all the related data.


text:
Q: Parsing a nameless JSON array in Java I'm trying to parse a nameless JSONArray returned from a POST request this format:
[{"key": value},
{"key": value},
{"key": value}]

I assumed I would just be able to call the array using this segment of code:
JSONArray resArr = result.getJSONArray("");

where result is the JSONObject returned by the POST, but I'm getting
Cannot parse json request result: org.json.JSONException: A JSONObject text must begin with '{' at 1 [character 2 line 1]

Is there some other way to call getJSONArray so that I can get an JSONArray without a key?

A: The correct way:
Parse this as an array using JSONArray(String)1:
JSONArray myJsonArray = new JSONArray(resultAsString);

The hacky way:
As a quick hack for this, you could consider building a valid JSON object. Simply concatenate {"wrappedArray": to the beginning of the string you have, and } to the end. You should then be able to parse this and call getJSONArray("wrappedArray") to get this array.
1 This is a link to a javadoc that you can use to get more details on how to use your JSON library.

A: The default JSON package refuses to accept [ as it's initial character. Therefore, result cannot be stored as a JSONObject. What you (well, I) need to do, is store result as a JSONArray as soon as it it stored locally. Any attempt to access or modify the Array will return the [ parsing error. So, in order to access the JSONArray, you'll need to re-write your POST method to be able to return JSONArrays as well (practically, copy and paste the method, changing types and names). This should solve the type issue, as [ is the expected starting character for a JSONArray.


text:
Q: Рефакторинг программы Я написал программу,которая рандомным образом выбирает глагол на русском языке из текстового документа и показывает нам его. Задача пользователя состоит в том,что он должен ввести в текстбоксы этот же глагол в 1,2,3 формах английского языка.
Собственно сам код:
namespace Verbs2
{
   public partial class MainWindow : Window
    {
        int randomNum = 0;
        int counterWin = 0;
        int counterLose = 0;
        bool ifChecked = false;
        public MainWindow()
        {
            InitializeComponent();
        }

        public class Verbs
        {

            /*класс создан для работы над глаголами и текстового файла*/

            string[] readText = File.ReadAllLines(@"C:\Users\Рустем\Desktop\проекты\Verbs2\Verbs2\verbs.txt",
                System.Text.Encoding.GetEncoding(1251));//считываем все строки в массив
            List<string[]> res = new List<string[]>();
            public Verbs()
            {
                foreach (var line in readText)//перебираем строки массива
                {
                    res.Add(line.Split('.'));//Каждую строку сплитим и помещаем в список массивов.
                }
            }
            public string GetVerb(int a)//метод позволяет достать из листа глагол на русском языке(в 3 столбце находятся русские глаголы)
            {
                return res[a][3];
            }
            public string GetVerb(int a, int b)
            {
                return res[a][b];
            }
            public bool CheckVerbs(string a, string b, string c, int d)//проверяем соответствуют ли введенные данные,той строке что мы выбрали
            {
                if ((a.Equals(res[d][0])) && (b.Equals(res[d][1])) && (c.Equals(res[d][2])))
                    return true;
                else return false;
            }
        }

        public void SetRandom()
        {
            /*в нашем текстовом документе 68 глаголов,поэтому мы выбираем один рандомный глагол из 68*/
            Random rnd = new Random();
            randomNum = rnd.Next(0, 68);
        }

        public int GetRandom()
        {
            return randomNum;
        }

        private void btnstart_Click(object sender, RoutedEventArgs e)
        {
            /*при нажатии на кнопку "начать" создаем объект класса verb, выбираем рандомной глагол, вставляем его в lblverb2 и делаем доступной кнопку btncheck*/
            Verbs verb = new Verbs();
            SetRandom();
            lblverb2.Content = verb.GetVerb(GetRandom());
            btncheck.IsEnabled = true;
            counterWin = 0;
            counterLose = 0;
        }

        private void btncheck_Click(object sender, RoutedEventArgs e)
        {
            /* в лэйблы 4-6 вставляем глаголы на английском языке
             проверяем соответсвуют ли введенные в текстбоксы глаголы,выбранному глаголу
             делаем доступной кнопку btnnext*/
            Verbs verb = new Verbs();
            lblverb4.Content = verb.GetVerb(GetRandom(), 0);
            lblverb5.Content = verb.GetVerb(GetRandom(), 1);
            lblverb6.Content = verb.GetVerb(GetRandom(), 2);
            if (verb.CheckVerbs(textverb1.Text, textverb2.Text, textverb3.Text, GetRandom()))
            {
                lborder.BorderBrush = Brushes.Green;
                counterWin++;
                lblcw.Content = counterWin.ToString();
            }
            else
            {
                lborder.BorderBrush = Brushes.Red;
                counterLose++;
                lblcl.Content = counterLose.ToString();
            }
            btnnext.IsEnabled = true;
            btncheck.IsEnabled = false;
            ifChecked = true;
        }

        private void btnnext_Click(object sender, RoutedEventArgs e)
        {
            /*по сути повторяет действия кнопки btnstart,но при этом очищает лэйблы и текстбоксы*/
            Verbs verb = new Verbs();
            SetRandom();
            lblverb2.Content = verb.GetVerb(GetRandom());
            btncheck.IsEnabled = true;
            if (ifChecked == false)
                counterLose++;
            lblcl.Content = counterLose.ToString();
            ifChecked = false;
            lblverb4.Content = "";
            lblverb5.Content = "";
            lblverb6.Content = "";
            textverb1.Text = "";
            textverb2.Text = "";
            textverb3.Text = "";
            lborder.BorderBrush = Brushes.White;
        }
    }
}

Код XAML:
<Window x:Class="Verbs2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Неправильные глаголы" Height="350" Width="360">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="25"/>
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="120*" />
            <ColumnDefinition Width="120*" />
            <ColumnDefinition Width="52*" />
            <ColumnDefinition Width="24*" />
            <ColumnDefinition Width="15*" />
            <ColumnDefinition Width="24*" />
        </Grid.ColumnDefinitions>

        <Menu  Grid.Column="0" Grid.ColumnSpan="3" Background="White">
            <MenuItem Header="File">
                <MenuItem Header="New Project" ></MenuItem>
                <Separator/>
                <MenuItem Header="Exit" ></MenuItem>
            </MenuItem>
        </Menu>

        Глагол:

        Счетчик

        <TextBox x:Name="textverb1" Grid.Column="0" Grid.Row="3"></TextBox>
        <TextBox x:Name="textverb2" Grid.Column="1" Grid.Row="3"></TextBox>
        <TextBox x:Name="textverb3" Grid.Column="2" Grid.Row="3" Grid.ColumnSpan="4"></TextBox>

        <Button x:Name="btnstart" Grid.Column="0" Grid.Row="4" Click="btnstart_Click">Начать</Button>
        <Button x:Name="btncheck"  IsEnabled="False" Grid.Column="1" Grid.Row="4" Click="btncheck_Click">Проверить</Button>
        <Button x:Name="btnnext"  IsEnabled="False" Grid.Column="2" Grid.Row="4" Grid.ColumnSpan="4" Click="btnnext_Click">Следующий</Button>

        0
        /
        0

        <Border x:Name="lborder" BorderBrush="White" BorderThickness="4" HorizontalAlignment="Left" Height="64" VerticalAlignment="Top" Width="360" Grid.Row="3" Grid.ColumnSpan="6"/>
        <Border x:Name="lborder1" BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="74" VerticalAlignment="Top" Width="352" Grid.Row="1" Grid.ColumnSpan="6"/>
        <Border x:Name="lborder2" BorderBrush="Black" BorderThickness="1"  Height="71" VerticalAlignment="Top" Grid.Row="2" Grid.ColumnSpan="6" Width="352" Margin="0,0,0.444,0"/>
    </Grid>
</Window>

Хотелось бы провести рефакторинг кода. Что в нем можно улучшить?

A: 1)В кнопках много логики.
Кнопки должны содержать минимум логики и по возможности дергать 1 метод, где и будет описана вся логика.
2)Почему бы не создать отдельный класс, который будет содержать 4 поля: Русский глагол, 1-форма, 2-форма,3- форма? Затем, этот класс оборачиваешь в еще 1 класс, и хранишь все в List и делаешь методы сравнения и т п.
Этим ты заменишь работу с массивом в Verbs. Ты сможешь работать с конкретными полями, а не рукоблудить индексы двумерного массива.
3)Возможно, имеет смысл хранить глаголы не в TXT файле, а в XML и выполнять десериализацию.(Особенное, если будешь следовать совету 2).

A: Начнем с самого основного - класса. Вместо использования двумерного массива, лучше вынести логику работы с глаголом в отдельный класс, например:
public class Verb
{
    public string Rus { get; set; }
    public string F1 { get; set; }
    public string F2 { get; set; }
    public string F3 { get; set; }
}

названия свойство можно и более содержательные придумать =)
Хранить элементы можно в обычном массиве:
    Verb[] data;
    public MainWindow()
    {
        InitializeComponent();
        data =
            File.ReadLines("data.txt")
            .Select(x => x.Split('.'))
            .Select(x => new Verb { F1 = x[0], F2 = x[1], F3 = x[2], Rus = x[3] })
            .ToArray();
    }

Обратите внимание на использование относительного пути, вместо абсолютного.
Вместо разбора строки можно использовать десериализацию в удобный формат.
Методы GetRandom() И SetRandom избыточны. Кроме этого вы жестко задаете верхнюю границу. Можно использовать свойство .Length:
    Verb current;
    private void setNextVerb()
    {
        current = data[rnd.Next(data.Length)];
    }

    private void btnstart_Click(object sender, RoutedEventArgs e)
    {
        setNextVerb();
        btncheck.IsEnabled = true;
        counterWin = 0;
        counterLose = 0;
    }

На мой взгляд эта кнопка вообще не нужна и такой код лучше поместить, например, в конструктор.
В методе CheckVerbs вы используете конструкцию вида:
if something return true; else return false;

которая может быть сведена к
return something;

То есть можно написать сразу так:
    //проверяем соответствуют ли введенные данные,той строке что мы выбрали
    private bool CheckVerbs(string a, string b, string c, Verb verb)
    {
        return a.Equals(verb.F1) && b.Equals(verb.F2) && c.Equals(verb.F3);
    }

Тогда ваши обработчики изменятся следующим образом:
   private void btncheck_Click(object sender, RoutedEventArgs e)
    {
        lblverb4.Content = current.F1;
        lblverb5.Content = current.F2;
        lblverb6.Content = current.F3;
        if (CheckVerbs(textverb1.Text, textverb2.Text, textverb3.Text, current))
        { ...

и
    private void btnnext_Click(object sender, RoutedEventArgs e)
    {
        setNextVerb();
        lblverb2.Content = current.Rus;

Что касается XAML разметки - она не гибкая. Попробуйте изменять размер окна и вы поймете о чем идет речь.
При первой возможности напишу об этом подробнее.

Лучшее решение - переписать код через MVVM. Не хочу приводить здесь такой вариант, так как будет намного лучше, если вы сделаете это самостоятельно.

A: Вот это очень плохо, т.к. путь к файлу прибит к вашему рабочему каталогу
 string[] readText = File.ReadAllLines(@"C:\Users\Рустем\Desktop\проекты\Verbs2\Verbs2\verbs.txt",
            System.Text.Encoding.GetEncoding(1251);

Да, и зачем кодировка 1251. У вас что, работа в Windows XP планируется? Все ж давно на юникод перешли!
Создайте папку в вашем проекте Assets, затем прав.клав.клик по этой папке Add->Existing Item->и укажите ваш verbs.txt установите у него свойства Build Action в Embedded Resource. А далее его можно будет прочитать так (пример из моего проекта = читаю список стран)
StrList = new List<string>();
using (Stream stream = GetType().Assembly.GetManifestResourceStream("WpfEmbeddedResource.Assets.Countries.txt"))
using (StreamReader reader = new StreamReader(stream))
{
    string input = null;
    while ((input = reader.ReadLine()) != null)
    {
        StrList.Add(input);
    }
}

WpfEmbeddedResource - это название проекта.


text:
Q: Manipulation of inferior and superior limits of a summation Can you tell me if it's ok to manipulate the limit of a summation in this way please?
$$ \sum \limits _{l = k_o}^{+ \infty} q^{l - k_0} = \sum \limits _{l - k_0 = 0}^{+ \infty} q^{l - k_0} $$
Are there rules about the possible operations I can perform on the superior and inferior limits?

A: I see what you are doing, but this is unconventional to have an equation in the lower index of the summation. Less confusing variant involves the change of variable:
$$
\sum \limits _{l = k_0}^{+ \infty} q^{l - k_0} \stackrel{}{=} \sum \limits _{n = 0}^{+ \infty} q^{n}
$$
If you are afraid the reader cannot follow, you can add substituting summation index $n=l-k_0$ somewhere in the text


text:
Q: I can't install VirtualBox on my Windows 7 I can't install VirtualBox 5.0.10 on my Windows 7.
I tried almost everything, but when I run the setup, halfway through it stops and shows this message just like in the image below:

Source file not found:
  C\Users\xxx\AppData\Local\Temp\VirtualBox\common.cab.
  Verify that the file exists and that you can access it.

These are some of the things I tried but didn't work.

*

*Run As Administrator

*Delete program and reinstall

*Change MAXNUM filter from 8 to 20

Please help.

A: The installer might be getting tripped up on non-ASCII characters in paths. Try creating a new user account with a name that contains only English letters and running the installer there. The other account will need to be an administrator. You can remove it after you're done.


text:
Q: Why does my 20" iMac running Snow Leopard suffer from very slow wireless? 3 different Windows machines on the same wireless from a position 2' from the aforementioned iMac are snappy. All machines using DHCP, and are using the same DNS servers, so it doesn't seem likely to be a DNS issue. Wireless router is a band new (3 weeks old) Belkin N300 - we had the same problem with an older Linksys device and upgraded to se if we could get better speed.
The displayed behavior is generally that the progress bar for the page load proceeds to half or most of the way complete and then the page load seems to stall. Wireless signal indicator stays full, so it doesn't look like the connection is dropping.
Oh, I saw Wireless internet became extremely slow on my 27" IMac; the problem on our machine doesn't seem to resolve when the machine's been off for a period of time, either - it's almost always slow...
I don't even know where to start troubleshooting this. Help?!
UPDATE
results of router ping:
ping -c 10 192.168.1.1
PING 192.168.1.1 (192.168.1.1): 56 data bytes
64 bytes from 192.168.1.1: icmp_seq=0 ttl=64 time=1.411 ms
64 bytes from 192.168.1.1: icmp_seq=1 ttl=64 time=1.092 ms
64 bytes from 192.168.1.1: icmp_seq=2 ttl=64 time=1.238 ms
64 bytes from 192.168.1.1: icmp_seq=3 ttl=64 time=1.128 ms
64 bytes from 192.168.1.1: icmp_seq=4 ttl=64 time=1.189 ms
64 bytes from 192.168.1.1: icmp_seq=5 ttl=64 time=1.420 ms
64 bytes from 192.168.1.1: icmp_seq=6 ttl=64 time=0.928 ms
64 bytes from 192.168.1.1: icmp_seq=7 ttl=64 time=1.515 ms
64 bytes from 192.168.1.1: icmp_seq=8 ttl=64 time=1.459 ms
64 bytes from 192.168.1.1: icmp_seq=9 ttl=64 time=1.309 ms

--- 192.168.1.1 ping statistics ---
10 packets transmitted, 10 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 0.928/1.269/1.515/0.178 ms

A: I would try "pinging" your router from a terminal window:
ping routerip -c 10

If any of the packets take more than 30ms, or if there are any lost/dropped packets, then you know that it's an adapter hardware/software issue, rather than your web browser.
Apart from that, I would try connecting with a cable to see if you still have the problem. Obviously, that is not a fix - but it might help!
I would also try switching from "N" mode to "G" mode on your router. It seems... illogical, but i know that some people having wireless problems with the macbook pro managed to at least reduce the issue by switching to wireless G. You could even disable the DNS/DHCP functionality of your old router and use it as G-Only access point so that your other computers can use Wireless N.

A: i would also suggest that you try running your iMac by itself on the network, double check all your internet settings. also try using the diagnostic function which you can find in system prefs-network then select "AirPort" on the left and click "Assist me..." you will then be prompted and there will be a "diagnostics..." button


text:
Q: get Chart js tool tips to the top of the page I am facing an issue with Chartjs(2.0) tool tips. In my view there are two wrapper DIV elements, one is the container div for the chart js and other is another container with a custom legend
My issue is its hiding tool tips because of my custom legend which is positioned using z-index and top of the chart
I need to get the tool tips to top of my legend
click to view screen shot of my issue
Sample code of my view

    <canvas id="{{ChartConfig.chartName}}-chart" class="chart"
        chart-data="chartData.counts" chart-labels="chartData.labels"
        chart-options="chartOptions" chart-colors="chartColors" chart-click="openList">
    </canvas>

{{ segment.text }}

{{ chartData.counts[segment.index] }}


text:
Q: Do i need Symfony2's $form->isValid() for a search field? I have created a search form on the fly in my controller to list users by nicknames / names:
$form = $this->createFormBuilder()
        ->add('username', 'search', array('required'=> false))
        ->add('name', 'search', array('required'=> false))
        ->add('submit', 'submit')
        ->getForm();

So, because this form isn't mappped in my database, I don't use any Assert.
My question : I don't know if I have to use isValid() because I don't know if this method does the same as get('validator')->validate(), (then I wouldn't need it), or if it checks other interresting things.
Thanks for help, have a nice day!

A: This is recommended, you can check in the good practice advices of symfony developpers :
They recommend using $form->isSubmitted() in the if statement for clarity. This isn't technically needed, since isValid() first calls isSubmitted(). But without this, the flow doesn't read well as it looks like the form is always processed (even on the GET request).
http://symfony.com/doc/current/best_practices/forms.html


text:
Q: On click action not working properly My javascript function
   function ConfirmDelete()
      {
            if (confirm("Delete Account?"))
             var id= $(this).attr('data-id');
             alert(id);
                 location.href='config-project-delete.php?id='+id;
      }

onclick event trigger
<?php
echo "

Delete

"; ?>

I cant able to get the data-id.It keep saying undefined.Any help would be appreciated.

A: In your example, this doesn't refer to the element where you called the function, but rather refers to the owner of the function (which, as you've defined it, looks like it's in the global scope).  So you'd have to call the function with the parameter of the value you want, then use it within the function, as such:
<?php
echo "
...

(The $ is escaped because you're echoing it with PHP).
And then your function would look something like this:
function ConfirmDelete(data_id)
  {
        if (confirm("Delete Account?"))
         var id= data_id;
         alert(id);
             location.href='config-project-delete.php?id='+id;
  }

If you aren't using the data-id attribute anywhere else and only for this purpose, you can simplify the HTML side as well by passing the value directly:
<?php
echo "
...

Note that I haven't tested any of this code, and when mixing HTML, JS, and PHP, it can be easy to screw this up (at least for me), so tweak the above as needed.

A: try this
<span onclick="javascript:deleteConfirm('<?php echo 'config-project-delete.php?id='.$row['project_id'] ?>');" deleteConfirm class='button-content'>

javascript
function deleteConfirm(url)
 {
    if(confirm('Do you want to Delete this record ?'))
    {
        window.location.href=url;
    }
 }

A: You have to pass the triggering object to your function.
   function ConfirmDelete(triggering_object)
      {
            if (confirm("Delete Account?")) {
                var id= $(triggering_object).attr('data-id');
                alert(id);
                location.href='config-project-delete.php?id='+id;
            }
      }

And add the 'this' to your object:
echo "";

A: Although Nick Coons answer is an easier way to do this (pass the variable to the function), to get the results you first asked about using the data attribute method, you have to pass event to the function to get the proper node. http://jsfiddle.net/2t4hK/
function ConfirmDelete(e) {
    var target = $(e.target);
    if (confirm("Delete Account?")) {
        var id = target.attr('data-id');
        alert(id);
        //location.href='config-project-delete.php?id='+id;
    }
}

Delete

<?php
   echo '';
   echo 'Delete';
?>

Also, in your code, I suggest you wrap the value for data-id inside of quotes.


text:
Q: Android BLE send and recieve data in background I am connected to an android BLE device and I am able to read and write data. In my scenario I have to keep reading data from the device and send response to the sent request. I was implementing on the main thread and after a while when it goes to Pause state the process would end.
Do I have to use a Service class to read and write?

A: Yes. The best approach is to use a Service class in Android since your Activity should not be responsible for any background operations such as performing any BLE read/write actions. You just have to bind your Service class with your Activity class.


text:
Q: How do I enable multithreading/load balancing on NGINX + Phusion Passenger server which serves a Flask API I have a Flask API which runs under a Phusion Passenger container served on an NGINX server. When I observe the HTOP stats during traffic hours, I can see that only a few cores at a time are activating.
There is only one case where multiple cores are activated - when I run reports where I have created a parallel processing using the python built in multiprocessing library. This is not appliable on a higher level though.
Is there a simple way to do load balancing between multiple instances of my API on the same server to utilize the other cores?
Here is the configuration for my API instance:
location / {
    root /var/www/au/api/code;
    passenger_app_type wsgi;
    passenger_startup_file passenger_wsgi.py;
    passenger_enabled on;
    passenger_python /var/www/au/env/bin/python3;
}

I have a general idea of how i'd do this - create a few of these passenger apps running on different port and have an NGINX virtual server which takes all the traffic and does a proxy pass to the least loaded passenger server, but the decision part of this is what I havent figured out - how do I tell NGINX to choose the least loaded app to redirect to?


text:
Q: how to change textbox.text from one child form to other child form. Both are open in MDI form in C#.net I have one MDI Form, With two Child Form named MDIParent1,Form1,Form2.
MDI will Load with showing/loading this two child form in it.
private void MDIParent1_Load(object sender, EventArgs e)

    {
        Form childForm1 = new Form1();
        childForm1.MdiParent = this;
        childForm1.Show();

        Form childForm2 = new Form2();
        childForm2.MdiParent = this;
        childForm2.Show();
    }

In Form1 there is a textbox1 and a Button. And in form2 there is textbox2.
So what i am trying to is when I write sometext in Form1's Textbox1 and then Click on Form1's Button, That same text will be write in Form2's Textbox2.
I Tried a lot. But Dosnt get output. the values are passing through one child form to other. but Textbox.text property is not updating.
I tried it Without MDI Form. The Form1 And Form2 will opened independently. and I have to close and reopen Form2 each and every time when i click on Form1's Button. It Works little bit. But I need it in MDI Form. While Both Child Forms were opened in MDI and then I want to Update property of textbox (In short I need to do this form2.textbox.text = Form1.textbox.text where Form1 and Form2 both are Child forms)
Regards,
Salil

A: Try using the the MDI parent (MDIParent1) as a moderator between the 2 forms.
MDIParent1 will register to Form1's events and will modify Form2 respectively.
Modifications for Form1
Add to Form1 a public event notifying that the button was pressed. The event should also contain information about the current text in textBox1. For this, use a class deriving from EventArgs:
The EventArgs:
public class TextChangedArgs:EventArgs
{
    string _text;

    /// <summary>
    /// Gets text .
    /// </summary>
    /// <value>
    /// The text.
    /// </value>
    public string Text
    {
        get { return _text; }
    }

    public TextChangedArgs(string text)
    {
        this._text = text;
    }
}

The Public Event:
public event EventHandler<TextChangedArgs> OnTextChanged;

The Button1 Click Event:
 private void button1_Click(object sender, EventArgs e)
    {
        if (this.OnTextChanged != null)
        {
            this.OnTextChanged(this, new TextChangedArgs(this.textBox1.Text));
        }
    }

Modification to MDIParent1
In the following code, the modification is the registration to the event, and handling it:
 void MDIParent1_Load(object sender, EventArgs e)
    {
        Form1 childForm1 = new Form1();
        childForm1.MdiParent = this;
        childForm1.OnTextChanged += childForm1_OnTextChanged;
        childForm1.Show();

        Form2 childForm2 = new Form2();
        childForm2.MdiParent = this;
        childForm2.Show();
    }

    void childForm1_OnTextChanged(object sender, TextChangedArgs e)
    {
        //just getting the Form 2 instance, you can implement it in any way you choose to (e.g. make it global...)
        Form2 childForm2 = this.MdiChildren.Where(c => c is Form2).FirstOrDefault() as Form2;
        if (childForm2 != null)
        {
            childForm2.SetText(e.Text);
        }

    }

Modifications to Form2
The modification is Adding a public method for setting the text:
 public void SetText(string text)
    {
        this.textbox2.Text = text;
    }

this should work for you...


text:
Q: Is there a way to make a variable in Minecraft? Can you make variables in Minecraft Java? I want to make an armor stand tp to where I am looking, but I want to make the local Z coordinate editable with scoreboard. My command would be:
/execute at [username] run tp [armorstand UUID] ^ ^ ^#
"#" is a scoreboard objective.
Is that possible?

A: Scoreboard objectives in Minecraft are for all entities, meaning that all entities have all the objectives you have created. In other words you cannot create objectives for specific mobs
Back to the question, your method seems to be over-complicated. There is a method called raycasting, and it is basically a recursive function which repeatedly execute itself through the Minecraft world. It is especially useful for making laser weapons but this case, you can utilize it to detect which block the player is facing.
Here is a template of the raycast
inside a function called raycast.mcfunction
execute unless block ~ ~ ~ air run tp @e[type=armor_stand] ~ ~ ~
execute if block ~ ~ ~ air positioned ^ ^ ^1 run function namespace:raycast

In your tick function
execute as @a at @s run function namespace:raycast

I have tested it out myself and it works.
Unfortunately you might have to do it with datapacks since you cannot make functions in game.


text:
Q: DOMNodeList find php Здравствуйте.
Объясните мне, почему не хочет работать find() в domDocument'e?
Пробую делать так:
// создаю новый объект класса
$dom = new DOMDocument('1.0', 'UTF-8');

// получаю контент
@$dom->loadHTML($my_html);

// убираю пробелы
$dom->preserveWhiteSpace = false;

// извлекаю все теги ссылок
$links = $dom->getElementsByTagName('table')->find('a');

На выходе ошибка

Call to undefined method DOMNodeList::find()

A: PHP правильно сообщает вам, что класс DOMNodeList не имеет метода find.
Если вы хотите получать все ссылки, находящиеся в таблицах, то можно использовать специальный XPath запрос. Например так:
$dom = new DOMDocument('1.0', 'UTF-8');
$dom->loadHTML($my_html);

$xpath = new DOMXpath($dom);
$links = $xpath->query('*/table//a');

А вот и работающий пример на IDE One.


text:
Q: Getting the right font for ptm/n/n in IEEE Access Template I am using the latex template of IEEE ACCESS (i.e., \documentclass{ieeeaccess})officially provided by the IEEE template selector. However, when compiling I get the warning that certain fonts are missing.

Font shape 'T1/ptm/n/n' undefined
(Font) using `T1/ptm/m/n' instead.

Font shape 'T1/phv/n/n' undefined
(Font) using `T1/phv/m/n' instead.

And I dig into the log file, which shows:

LaTeX Font Info:    Trying to load font information for T1+ptm on input line 36.
("/Users/***/Library/Application Support/MiKTeX/texmfs/install/tex/latex/psnfss/t1ptm.fd"
File: t1ptm.fd 2001/06/04 font definitions for T1/ptm.

LaTeX Font Info:    Trying to load font information for T1+phv on input line 55.
("/Users/hurunqiu/Library/Application Support/MiKTeX/texmfs/install/tex/latex/psnfss/t1phv.fd"
File: t1phv.fd 2020/03/25 scalable font definitions for T1/phv.
)

I suppose pdfLaTeX is searching the fonts in T1/ptm and T1/phv. Looking inside one of the two files(T1/ptm.td) I found:
\ProvidesFile{t1ptm.fd}
   [2001/06/04 font definitions for T1/ptm.]

\DeclareFontFamily{T1}{ptm}{}

\DeclareFontShape{T1}{ptm}{m}{n}{
   <-> ptmr8t
}{}

\DeclareFontShape{T1}{ptm}{m}{sc}{
   <-> ptmrc8t
}{}

\DeclareFontShape{T1}{ptm}{m}{sl}{
   <-> ptmro8t
}{}

\DeclareFontShape{T1}{ptm}{m}{it}{
   <-> ptmri8t
}{}

\DeclareFontShape{T1}{ptm}{b}{n}{
   <-> ptmb8t
}{}

\DeclareFontShape{T1}{ptm}{b}{sc}{
   <-> ptmbc8t
}{}

\DeclareFontShape{T1}{ptm}{b}{sl}{
   <-> ptmbo8t
}{}

\DeclareFontShape{T1}{ptm}{b}{it}{
   <-> ptmbi8t
}{}

\DeclareFontShape{T1}{ptm}{bx}{n}{<->ssub * ptm/b/n}{}
\DeclareFontShape{T1}{ptm}{bx}{sc}{<->ssub * ptm/b/sc}{}
\DeclareFontShape{T1}{ptm}{bx}{sl}{<->ssub * ptm/b/sl}{}
\DeclareFontShape{T1}{ptm}{bx}{it}{<->ssub * ptm/b/it}{}

\endinput

There is indeed no combination of ptm/n/n.
Meanwhile, I checked ieeeaccess.cls provided by official, and found one line \def\bioaddressfont{\sffamily\putfont{T1}{formata}{n}{n}{8}{10}}.
I believe it's here that requires the font ptm/n/n and phv/n/n.
I thought I could neglect the warning if the substituted fonts are OK. However, seeing the published paper, I found the font of the bold titles(including subsections) are indeed different from mine now:
The published articles:
Mine currently:
I think I shouldn't change the template, and I found no ptm/n/n font solutions online, so where went wrong? How can I make it right?
(P.S. I have tried both pdfLatex and MiKteX, and both couldn't work.)


text:
Q: Regex to check for different ordering? I'm trying to write out a regex that checks that the following has been written:
session({
  secret: "asdfadf",
  resave: false,
  saveUninitialized: false,
});

The regex test I wrote can be found here:
session\(\{\s*secret\:\s*("|')\w*("|')\s*,\s*resave\s*\:\s*false\,\s*saveUninitialized\:\s*false\,?\s*\}\)

I need to update it so that the properties can be added in different orders and still pass the regex test. Is there a group or a way to set this so it passes?

A: If we want to create a regular expression that matches a string comprised of the substrings
Doe Ray Me Far Sew La Tea
in any order, and we don't want to tediously create a very long expression including every possible ordering, we may begin by trying
(Doe|Ray|Me|Far|Sew|La|Tea){7}
which matches a string containing the seven substrings in any order.
We then have the problem that the expression does not fail to match if one or more substrings is repeated or missing.
One way to ensure each substring appears only once is to add a negative lookahead to each alternative to ensure it doesn't appear in the string again ahead of the match.
(Doe(?!.*D)|Ray(?!.*R)|Me(?!.*M)|Far(?!.*F)|Sew(?!.*S)|La(?!.*L)|Tea(?!.*T)){7}
Note that only the first letter of the substring is required in the lookahead because the first letter of each substring is different.
In your particular case, the following seems to work fine although it hasn't been thoroughly tested.
The final trailing comma is made optional by (,|(?=\s*\})), which ensures that if there isn't a comma then there must be a '}' ahead in the string after optional whitespace.
You may not want to make the semicolon optional as done here.
You may also want to split a long regular expression into multiple lines.

const input = `session({
  secret: "asdfadf",
  resave: false,
  saveUninitialized: false,
});`;

const regex = /^session\s*\(\s*\{\s*((secret\s*:\s*(?<q>["'])\w*\k<q>(?!.*c)|resave\s*\:\s*false(?!.*e\s*:)|saveUninitialized\s*:\s*false(?!.*d\s*:))\s*(,|(?=\s*\}))\s*){3}\}\s*\)\s*;?$/;

console.log(regex.test(input));


text:
Q: What is the name and notation for this matrix norm? For a given matrix $\mathbf{A}\in\mathbb{C}^{m \times n}$, let $\|\mathbf{A}\| = \sum_{i=1}^m\sum_{j=1}^n|A_{ij}|$. Clearly, $\|\cdot\|$ is a matrix norm. Is there a special name and notation for $\|\cdot\|$? Well, name can be "entrywise $1$-norm" probably, but is there a conventional notation, e.g. $\|\mathbf{A}\|_{\mathrm{OMG}}$?

A: While it is horrible to overload notation like this, the entrywise $p$-norm of a matrix is also unfortunately also denoted by $\|A\|_p$ in many books and such. Normally, though, I don't really see this notation come up very often. Most analyses are purely entry-wise, rather than trying to sum up the entry-wise errors. The only exception I've seen is $p = 2$, which is the Frobenius norm, which is nice because it is unitarily invariant.
One way to resolve the ambiguity is to denote the operator norm by $\|A\|_{p,q}$, where this quantity is the operator norm of $A$ as viewed as a map $(\mathbb{C}^n, \|\cdot\|_p) \rightarrow (\mathbb{C}^m, \| \cdot \|_q)$. In this case, the traditional operator $2$-norm of $A$ would be $\|A\|_{2,2}$. Of course, very few people do this, so until then we're stuck with ambiguous notation.


text:
Q: How to find how long the execution time will take before starting? We can measure how long a script took to be executed. As in this question: How do I get time of a Python program's execution?
But what I want is to find the time it takes a code to be executed before the execution.
Example 1:
When executing a script, first thing to print is something like this:
this function will take 1 min 40 seconds to be executed
Example 2:
A percentage of how much execution is done so far. For example, after a minute the percentage is: 60% and it keep increasing until it hits 100%.

A: A fully general solution to this question would solve the halting problem, which has been mathematically proven impossible.
For more particular cases, it can be done. For certain algorithms, if you know how much work must be done and you can periodically check how much of it has been done, then you can update the percentage. You can also estimate the time remaining based on how quickly the percentage is progressing, but this can often be inaccurate.

A: Please be consider that when you are executing a function, the time depends on your algorithm as well as your machine speed. In order to calculate the time without executing the code, you may have to give some initial parameters or else use a machine learning code that will calculate the time of execution by going through the codes but it seems very difficult.
Btw Try this using import timeit.
Just save the time before and after the execution of code and subtract them! But this method is not precise as there might be a background process momentarily running which disrupts the code execution and you will get significant variations in running time of small code snippets.
timeit runs your snippet of code millions of time (default value is 1000000) so that you get the statistically most relevant measurement of code execution time!
# importing the required module
    import timeit
# code snippet to be executed only once
mysetup = "from math import sqrt"

# code snippet whose execution time is to be measured
mycode = '''
def example():
    mylist = []
    for x in range(100):
        mylist.append(sqrt(x))
'''

# timeit statement
print timeit.timeit(setup = mysetup,
                    stmt = mycode,
                    number = 10000)


text:
Q: Opening an OS X disk image with a launchd agent while the display is sleeping I created a launchd agent which opens a non-password-protected sparse disk image (and mounts its solitary volume) daily at 2:45AM in preparation for backup software to write to the volume. The launchd agent's plist file is saved in ~/Library/LaunchAgents/. Here are the plist file's parameters:
Label: my.DiskImageOpener
KeepAlive: NO
RunAtLoad: NO
StartCalendar:
    Hour: 2
    Minute: 45
ProgramArguments:
    hdiutil
    attach
    /path/to/MyDiskImage.sparseimage

As long as the computer's display is awake, the agent works as advertised, opening the disk image and mounting its volume at the time specified in the launch agent. On the other hand, if the display is asleep at the time specified in the launch agent, the disk image fails to open until the display is awoken from sleep (even if that is several hours later), at which point the disk image immediately opens and mounts its volume. The same phenomenon happens if I replace the hdiutil attach /path/to/MyDiskImage.sparseimage command with open /path/to/MyDiskImage.sparseimage, or place the command in a separate executable shell script that the launch agent executes. Also, even though the display is asleep when the above-described problem occurs, the computer itself is awake. Also, I tested having the launch agent execute a dummy executable shell script (echo $(date)) instead of hdiutil, and it executes normally even when the display is asleep.
So it seems that the problem occurs specifically when trying to open a disk image from a launchd launch agent while the computer's display is asleep. Why does the display's sleep vs awake status have any effect on opening a disk image? How can I circumvent this problem?
I am grateful for any help with this puzzling problem. (I am using a MacBook Pro laptop running OS X 10.8.2 Mountain Lion.)

A: It is likely your MacBook is asleep when launchd is scheduled to run your disk mount command. launchd does not change its behaviour because of the state of the display.
Your launchd job will run so long as:

*

*the Mac is awake

*the launchd job is active

*you are logged in (the job ticket is in ~/Library/)

Use pmset's debug logs to find out if your Mac was awake or asleep. The following command will print a log of everything pmset knows:
pmset -g everything

Be sure to check the system.log for messages related to your failed launchd job. If a problem is encountered launchd will log a message.
Applications > Utilities > Console.app > system.log

Mac OS X Energy Saver includes the ability to power on or wake your Mac at a predefined time. You might want to use this ability to wake your Mac a minute before your launchd job is scheduled.
System Preferences.app > Energy Saver > Schedule…


text:
Q: retrieve json from a refreshing page using ajax I have index.php page which makes a ajax call to thread.php by sending the variable "dateposted". The thread.php returns a json which is being looped through in my index.php and the last value is sent back into the ajax call again. All this works fine.
However, the problem i face is when i put thread.php in autorefresh using
<meta http-equiv="refresh" content="2">

When i do this, the returned response in my ajax call includes this and the json results which throws my looping of the json array off. I can remove the above code since i need thread.php to be constantly refreshing to poll data from the server. How do i get around this issue:
For reference:
thread.php
<meta http-equiv="refresh" content="2">
if(!isset($_GET['dateposted']))
{ $lastpost = 0;
}
else
{$lastpost= $_GET['dateposted'];}

  $latestmsgs = retrieveNewMsgs($lastpost,$currtime);
  ?>

 <?php echo json_encode($latestmsgs);?>

index.php
var returnValue = (function() {
    var  dateposted = null;
    return function() {
        $.get("thread.php", { "lastMessage":  dateposted }, function(result) {
        if(result) {

                        for (var i = 0, len = result.length; i < len; i++) {

                            var msgs = result[i];
                            var newDiv = $("
" + msgs[2] + msgs[3] + msgs[4] + msgs[5] + "

");

                           $('#chatContents').append(newDiv);

                        }

                }

           dateposted = result[result.length-1][5];
        }, "json");
    }
})();

A: You could use the window.setInterval function to execute some javascript code at regular intervals of time that you define. So remove the meta refresh tag and place your AJAX call inside setInterval:
// poll the server every 10 seconds for new data
window.setInterval(function() {
    $.get("thread.php", ...
}, 10000);


text:
Q: R Error with axis break code (plotrix gap.plot) When I try to break axis of a plot I always get an error.
I use plotrix pkg.
My code so far:
xlim <- c(0,1)
ylim <- c(0,1)
gap.plot(evcent(USAN_g_num)$vector, betweenness(USAN_g_num, normalized=T), gap=c(0.4,0.6),gap.axis="y", xtics=c(0,0.3,0.7,1) ,xlim='xlim', ylim='ylim')

I get this error:
Error in rangexy[2] - rangexy[1] :
  non-numeric argument to binary operator

Actually I think that I don't really need xlim and ylim. However I get an error that says me that xlim is missing if I don't use it.
Why I need a gap in Y-axis: My data ranges from 0 to 1 on both, x and y axis. On y axis I got an outlier. Therefore I have no datapoint between 0.4 and 0.6 on Y axis. Therefore I would like to cut this section out.
What did I do wrong with my code?
Thank for any help & sorry for this - maybe - beginner question.

A: Unfortunately your code is not reproducible because you do not provide USAN_g_num.
But try:
xlim=xlim, ylim=ylim

in your call to gap.plot instead of xlim='xlim' and ylim='ylim'.

A: Is there a reason that you are defining xlim and ylim outside of the call to gap.plot?
Otherwise, your error is due to passing a character string 'xlim' to the argument rather than a numerical range. Try the following, which will have the added benefit of shortening your code and not storing xlim and ylim as global variables:
gap.plot(evcent(USAN_g_num)$vector, betweenness(USAN_g_num, normalized=T), gap=c(0.4,0.6),gap.axis="y", xtics=c(0,0.3,0.7,1) ,xlim=c(0,1), ylim=c(0,1)


text:
Q: In LibreOffice Calc, how can I control whether the column or row is incremented when pasting? In my LibreOffice Calc spreadsheet, I have a column in one sheet where I want to reference values from another sheet. I want to copy one cell, paste into multiple cells, and have it correctly set the references.
Let's say I start by coping a cell containing =sheet2.A1. By default:

*

*If I paste it into cells in the same column, it will increment the row numbers, like:
=sheet2:A2
=sheet2:A3

*If I paste it into cells in the same row, it will increment the column names, like this:
=sheet2:B1   =sheet2:C1    =sheet2:D1

What I want is to control whether it increments the cell or column, so that I can paste into the same column and increment the column names, like this:
COLUMN A
=sheet2:A1
=sheet2:B1
=sheet2:C1

How can I do this?

A: If I understand you correctly, you are trying to copy a row of cells (A1:C1) and past them into another spread sheet in a way that changes the orientation from horizontal to vertical, in other words, pasting a row of cells into a column of cells.
Lucky day, this is simply solved by clicking on "Paste Special" and checking the box (lower left of the "Paste Special" window under "Options") next to "Transpose".  This will paste the copied cells into the opposite orientation.


text:
Q: return an array of prime numbers I need a method to return prime numbers in an array.
So if given: primeArray(5)
than an array like so should be returned: (2, 3, 5)
For some reason this doesn't seem to work for me:
public static int[] primeArray(int numFind)
{
    //determines the size of the array returned
    int primeTotal = 0;

    //loop to find total prime numbers
    for (int j = 1; j <= numFind; j ++)
    {
        if (isPrime(j))
        primeTotal +=1;
    }

    //declare array to be returned
    int[] numA = new int[primeTotal];

    //current index of prime number
    int iP = 0;

    //loop to add prime elements to array
    for (int x = 1; x <= numFind; x ++)
    {
        if (isPrime(x))
        {
            numA[iP]=x;
            iP++;    // <--- THIS IS CAUSING ME PROBLEMS
        }

    }

    return numA;
}

public static boolean isPrime(int n)
{
    for (int i = 2; i < n; i++)
    {
        if(n%i==0)
            return false;
    }
    return true;
}

This is what I'm using to test my code:
    int[] num = primeArray(11);

    System.out.println(num[0]);
    System.out.println(num[1]);

But for output I'm getting this:
1
2

If however I comment out the iP++; than the if statement finally decides to execute ONLY when prime numbers are passed as a parameter in: isPrime(j) but then if defeats the whole purpose of the primeArray method because I need the primeArray method to return an array of prime numbers.

A: Your isPrime() method is faulty. You need to return false, for number < 2. Also, you don't need to iterate till n, just iterate till n / 2 or even better sqrt(n).
Change it to:
public static boolean isPrime(int n) {

    if (n < 2) return false;

    int maxIteration = Math.ceil(Math.sqrt(n));

    for (int i = 2; i < maxIteration; i++) {
        if(n % i == 0)
            return false;
    }

    return true;
}

Now, given your real problem (Note that your method is just fine. It would return you correct result, given you changed your isPrime() method), but you can avoid iterating twice by  using an ArrayList instead of array:
List<Integer> primes = new ArrayList<Integer>();

//loop to find total prime numbers
for (int j = 1; j <= numFind; j ++)
{
    if (isPrime(j))
        primes.add(j);
}

And then you can just return primes, and change the return type of method to List<Integer> instead of int[].
public static List<Integer> primeNumberList(int numFind)

If you really want to return an int[], then you need to do some work converting the ArrayList to an int array. I leave this task to you. Just search for this on SO only, you will get too many posts.

Also, if you are going to generate all prime numbers till a very large number, then you should take a look at Sieve of Eratosthenes

A: You just do the output for the first to Array-Values...
just replace your output
for(int i = 0; i < num.length; i++)
{
    System.out.println(num[i]);
}

Your code works fine.

A: In your isPrime() method, add this one statement at the end
if(n < 2) return false;
I think in the current way, when 1 is passed you get a true.
Another suggestion that I can think of is you can use a static table for some amount of numbers if you expect your limit to be small.
static int[] PRIME_TABLE = {2,3,5,7,11,13,17,19,23,29,31}; etc
So when the limit is smaller than 32 in this example, you don't need to calculate all the prime numbers below it and just loop through this table and return the numbers.

A: I tried to write isPrime(int num) function in a bit different way. The code becomes a bit more
lengthy but works. I used a different logic to identify if the number is 1 , because 1 is neither prime nor composite. Code is below.
   static int count=0;
   static boolean flag;
public static boolean isPrime(int num){

    for(int i = 1; i<=num/2 ; i++){

        if(num%i ==0){

            count++;

            if(count >=2){

                flag = false;
            }
            else{
                  if( num/1==1){
                      flag = false;
                  }
                  else{
                      flag = true;
                  }

            }

         }
    }
        return flag;
  }

A: this code return all prime numbers less than n
public ArrayList<Integer> allPrimesLessThanN( int n) {

    int sqrtN = (int)Math.sqrt(n);
    int [] numberList = new int[n];
    ArrayList<Integer> primeList = new ArrayList<>();

    for( int i = 0; i < n ; i++)
    {
        numberList[i] = i+1;
    }

    int k = 2;
    while( k <= sqrtN)
    {
        if(numberList[k+1] != 0)
        {
            for( int j = k+1; j < n; j++)
            {
                if( numberList[j] % k == 0)
                {
                    numberList[j] = 0;
                }
            }
        }

        k++;
    }

    for( int i = 1; i < n; i++)
    {
        if(numberList[i] != 0)
            primeList.add(numberList[i]);
    }

    return primeList;

}

A: There are a few ways to get an array of prime numbers, the easiest computationally is to use a Sieve of Eratosthenes. This iterates over every increasing number, where when the next prime is found, all subsequent multiples of this are marked not prime. Most implementations use a boolean array as below:
boolean[] numbers = new boolean[max];
// At first, assume every number is prime
for (int i = 0; i < max; i++)
    numbers[i] = true;
// Zero and one are not primes
numbers[0] = number[1] = false;

// Begin iteration from 2, the smallest prime
for (int i = 2; i < max; i++) {
    // if i is prime, all multiples of i are not prime
    if (numbers[i]) {
        for (int j = i * 2; j < max; j += i) {
            numbers[j] = false;
        }
    }
}

This method is good for a quick way to generate an array of primes, but it can get very memory-intensive for large maximum limits.
An alternate way of going about this problem is the way you have done it, where you simply add the next prime number when you find it. Your implementation though could become more efficient from the following.
boolean isPrime(double p) {
    if (p < 2) return false;
    for (int i = 2; i <= Math.sqrt(p); i++) if (p % i == 0) return false;
    return true;
}

Starting with the corrected implementation suggested by Rohit Jain (as above), you may notice you don't have to test every number less than sqrt(p). If p is not divisible by n, then it is not going to be divisible by the multiples of n - such we only need to test every prime number below p. For example; since 7 is not divisible by 2, it's not going to be divisible by 4 either.
The problem here is that we now need to find which numbers less than sqrt(p) are prime to test against p. Ah, but no we don't! We can just look into our cached list of known primes we will be later returning in the other method. And while we're caching a list of known primes, we don't need to make a new list in the other method either, we can just return our cache (once generated)! The finished product will look something like this:
class Primes {

    private static final List<Double> known_primes = new ArrayList<Double>(Collections.singletonList(2d));

    public static boolean isPrime(double p) {
        if (p < 2) return false; // 2 already in our cache
        if (known_primes.contains(p)) return true; // found prime in cache
        for (double i = 3; i <= Math.sqrt(p); i += 2) { // only check odd numbers
            if (!isPrime(i)) continue; // only check primes
            if (p % i == 0) return false; // p is divisible by i, so not prime
        }
        // checked all possible divisors, so p must be prime - cache and sort it!
        known_primes.add(p);
        Collections.sort(known_primes);
        return true;
    }

}

Now you can use Primes.isPrime(...) to check ;)

A: public class Demo {
public static void main(String[] args) {
    int result[] = ArrayOfPrimeNumbers(30);
    for (int i = 0; i < result.length; i++) {
        System.out.println("Factor: " + result[i]);
    }
}
public static int[] ArrayOfPrimeNumbers(int n) {
    int countPrimeNumbers = 0;
    for (int i = 2; i <= n; i++) {
        if (isPrime(i)) {
            countPrimeNumbers++;
        }
    }
    int newArrayofPrime[] = new int[countPrimeNumbers];
    int count = 0;
    while (count < countPrimeNumbers) {
        for (int i = 2; i <= n; i++) {
            if (isPrime(i)) {
                newArrayofPrime[count] = i;
                count++;
            }
        }
    }
    return newArrayofPrime;
}
public static boolean isPrime(int n) {
    if (n <= 1)
        return false;

    for (int i = 2; i < n; i++)
        if (n % i == 0)
            return false;

    return true;
}

}

A: You can way more optimize it by using Sieve algorithm to find primes. Following implementation can find primes upto (10^9)-1.
#include<iostream>//for I/O
#include<vector>//for keeping primes
#include<math.h>//for sqrt()
#define lli long long int
using namespace std;
vector<lli>prime;//using long long int data type for getting result for relatively bigger numbers...you may use int if you are working with smaller numbers.
lli upto;
bool stat[100000001];//Status array to keep track for primes/non-primes (0=prime, 1=non-prime, initially all are 0)
void sieve(lli upto)
{
    lli n=upto;
    stat[0]=stat[1]=1;//Marking 0 and 1 as they are not primes
    for(lli i=4;i<=n;i+=2)//Marking all even numbers as they won't be primes
    {
        stat[i]=1;
    }
    lli sqrtn=sqrt(n);
    //You can check if a number is prime or not just by making sure it is not divisible by any numbers upto it's square-root.
    //The reason of not checking the numbers after that is that if the number is divisible by a number greater than or equal to its square-root,
    //then we surely have already found another number which also divides the number less than or equal to its square root. For example to check if 36 is
    //a prime we can try dividing it with numbers <=sqrt(36) or <=6.We need not go beyond it. Say we need not check with 9 or 12 etc. as we have already checked
    //the divisibility with their conjugates 4 and 3 respectively (as 4*9=36 and 3*12=36) and found that 36 is getting divided, hence non prime.
    for(lli i=3;i<=sqrtn;i+=2)//So continuing this loop upto sqrt(n) and starting from 3 and stepping to only the odd numbers,as we cannot expect an even number to be a prime (except 2)
    {
        if(stat[i]==0)//ith index is still unmarked means it is a prime
        {
            //..so leaving ith index unmarked we are marking all the multiples of i as number i will divide them and they won't be primes.
            //But again we can do some optimizations:
            //(1) The next unmarked number divided by i, greater than i will be i*i. Because numbers less than i*i which is also divided by i are already marked by some numbers<i. An example will make it clear:
            //    Say for 5 we will start marking from 5*5=25, although 15 is divided by 5 but we need not mark it again as it is already marked by 3 (as 3 also divides 15) when we worked with 3.
            //(2) We are advancing our checking 2*i times as we are now searching for primes in odd numbers only, so we are skipping the marking for even numbers (say for 3, starting check from 3*3=9, we will next check 9+2*i=9+2*3=15 (we skipped checking 12 as it is even and we have already marked all even numbers initially (except 2) for being non-primes).
            for(lli j=i*i;j<=n;j+=2*i)
            {
                stat[j]=1;//so marking the indexes corresponding to numbers which are divisible by j as they are non-primes.
            }
        }
    }
    for(lli i=2;i<=n;i++)
    {
        if(stat[i]==0)//Finally finding which are still unmarked as the are not divisible by any number (except divisible by 1 and the number itself as prime number's definition) and the numbers corresponding to these indexes are primes.
        {
            prime.push_back(i);//storing primes, as index i is unmarked so i is a prime.
        }
    }
}
int main()
{
    cout<<"Enter upto which number you want to look for primes: ";
    cin>>upto;
    sieve(upto);
    for(int i=0,z=prime.size();i<z;i++)//printing
    {
        cout<<prime[i]<<" ";
    }
    cout<<endl;
}


text:
Q: Black-Scholes model with time-dependent volatility We consider the Black-Scholes model with time-dependent volatility $\sigma(t)$:
$$
dS_{1}(t)=rS_{1}(t)dt+\sigma(t)S_{1}(t)dW(t)
$$
The question: what constant $\hat{\sigma}$ one needs to apply such that for the process given by:
$$
dS_{2}(t)=rS_{2}(t)dt+\hat{\sigma}S_{2}(t)dW(t)
$$
the values of the European-style options for both models are the same?
My attempt is as follows:
For European-style option models $S_{1}(t)$ and $S_{2}(t)$ at the maturity time $T$, the same price must be given. Therefore we can equate the model prices and integrate from time $0$ to $T$, which results in
$$
rS(t)+\sigma(t)S(t)dW(t)=rS(t)+\hat{\sigma}S(t)dW(t)
$$
or
$$
\sigma(t)dW(t)=\hat{\sigma}dW(t)
$$
Now, integrating from $0$ to $T$ gives for constant $\hat{\sigma}$
$$
\hat{\sigma}=\frac{\int^{T}_{0}\sigma(t)dW(t)}{\int^{T}_{0}dW(t)}
$$
First of all, I do not know if this is the right way of solving the question, since according to the $It\bar{o}$ integral both the expectations of the numerator and denominator are equal to $0$, therefore this solution seems trivial or nonsense to me. Also, in this framework is this even a constant, since integrating w.r.t. Brownian motion does not produce a constant, it seems to me.

A: My suggestion: Let's suppose that we want to price an European option. Let be $C^1$ the price of a vanilla option where the underlying asset is $S^1$. Then we will look for the implied volatility $\hat{\sigma}$ such that when we plug this parameter into the Black formula we recover $C^1$. This means:
\begin{align*}
C_{BS}(\hat{\sigma}) = C^1
\end{align*} where $C_{BS}(\sigma) = SN(d_1(\sigma)) - K\exp^{-r(T-t)}N(d_2(\sigma))$.
We can go even further by assuming the implied volatility depends only on the maturity of the option. In that case solving the Dupire formula in terms of implied volatility, we can back out the following:
\begin{align*}
\hat{\sigma}^2(T) =  \frac{1}{T}\int_0^T\sigma^2(s)ds
\end{align*}
Overall, the implied volatility is equal to the quadratic mean of the volality over the option life time.


text:
Q: How do i view all transactions in JMeter Report I am running performance test using JMeter 5.0 and then at the end of the test a HTML report is generated. I would like to know if there is anyway to view actual request with the endpoint it served what was the response and ability to view all requests in HTML report. I know JMeter has something called view result tree and it provides most of the information i need but i am not sure how to display result tree or something similar in HTML report.

A: View results is tree is rather resource intensive listener so you want to use it with caution. Typically you want to filter and display only errors so you can analyse them.

If you would like HTML reports then you can use a modular extension for JMeter.  Its default behavior is to read and process samples from CSV files to generate HTML files containing graph views. It can generate the report at end of a load test or on demand.
You can generate the HTML report using menu item Tools → Generate HTML report:

This page explains different configs and options to tweak and tune the report generation.
Hope this helps.

A: As of current JMeter version 5.2

*

*JMeter can only generate the HTML Reporting Dashboard from the CSV files

The dashboard generator is a modular extension of JMeter. Its default behavior is to read and process samples from CSV files to generate HTML files containing graph views. It can generate the report at end of a load test or on demand.

*There is no possibility to store response data in CSV mode:

response_data is currently not supported for CSV output

So there is no easy way to implement your issue unless you use i.e. Flexible File Writer to store request/response data into a separate file and modify report-template (you will need to learn FreeMarker) to display the information you need.

A: use this command,  -g .jtl file -o reportlocationpath, you will get nicely generated html report along lots of graphs as shown below:

A:
I would like to know if there is anyway to view actual request with
  the endpoint it served

My guess is that you already have all the metrics required for each request but would like to see individual request payload and the response. Just in case this guess is wrong, since you already have the report and are still not able to see the individual requests, I am assuming that you have checked on "Generate Parent Sample" across each Transaction Controller. Uncheck that and you should be able to see individual request level response time, 90th percentile etc. Of course you will have to re-run the test to get these individual request level values
However, if you want to literally see the request payload and response in HTML report, there is no way we can do that. Only View Results Tree can do that for you within the scope of JMeter's GUI and not outside of this.

what was the response

As mentioned above, as of today, there is no possibility to see the response of individual requests along with their payload in the HTML report and this is for a good reason. We do not require the requests/responses while we run a load test in our HTML report. It is necessary for debugging and until the script is ready for execution. But post that, we wouldn't require the responses. If you still want to ensure that the correct responses are received, you can always add assertions (although best practice is not to add too many assertions in a load test)
Just an example of why HTML report across any load testing tool will not show responses of a request -
Assume there is a load test of 10K users for 10 iterations and the Thread Group has around 10 transactions each having an average of 7 requests, there is going to be 7 million responses to go through. Having this in a HTML report is not just tedious but literally doesn't make sense.

I know JMeter has something called view result tree and it provides
  most of the information i need

The View Results Tree is the holy grail for debugging and for ensuring if requests and response are appropriate during script creation stage.
I think your primary concern is to ensure the correctness of the responses rather than get the whole response of each request. In that case, as I had mentioned above, you can always use assertions. Several other custom alternatives include capturing specific parts of response and writing them to a file or something like that by leveraging JSR223 sampler or using the if controller to validate. Of course this is going to add some overhead on JMeter depending on the type of test and script that you are going to execute

but i am not sure how to display result tree or something similar in
  HTML report

But if you still insist on having something in HTML and if I have failed to convince as to why this is something that one must not pursue, you can capture the entire response of each request in a variable through Regex Extractor and write them to a file with HTML tags in it. However, you will have to implement logic to collate responses and organize them for your need.
One more way would be to have the JTL save all data and modify this up in some text editor and beautify it with HTML
FYI on JTL and its configuration

Hope this helps!


text:
Q: Can't put Caml Query to wok properly I have a List called "WorkshopResults" that have a reference, Lookup Field "Participant" for a list called "Participant", so I want to get the "FirstName" from "Participant" List.
What I'm missing?
Thanks for help
"<View>
    <ViewFields>
        <FieldRef Name=\"Title\" /><FieldRef Name=\"Id\" /><FieldRef Name=\"FirstName\" />
    </ViewFields>
    <Joins>
        <Join Type=\"LEFT\" ListAlias=\"Participant\"><Eq><FieldRef Name=\"Participant\" RefType=\"ID\" /><FieldRef Name=\"ID\" List=\"Participant\" /></Eq></Join>
    </Joins>
    <ProjectedFields><Field ShowField=\"FirstName\" Type=\"Lookup\" Name=\"Participant\" List=\"Participant\" /></ProjectedFields>
    <Query><Where /></Query>
</View>"

A: The migration of the site collection broke the lookup fields
Thanks


text:
Q: Outlook add-in: Adjoining Form Region not showing for Appointments in Inspectors I am developing an Outlook add-in. I do it in C# code, not in XML.
I added an FormRegion to the project. The type of the FormRegion is adjoining. It is associated with message class 'IPM.Appointment'.
I specified that the FormRegion be displayed in Inspectors in read mode.
With the settings above, I am expecting the FormRegion appear in Inspector windows for appointments. However, when I open Outlook, switch to the 'Calendar' view, double-click an appointment, the popped up Inspector window does not have my FormRegion.
I tried the same steps for message class 'IPM.Notes' and it worked well -- when i double-clicked a mail in the 'inbox' folder, the popped up inspector showed my FormRegion at the lower part of the window.
Could someone help telling me the reason why my FormRegion is not working for appointments?
Thanks,
Richard


text:
Q: how to determine file extension from mime type? I am trying to figure out the best way to determine a file extension given a mime type in android.
This is typically coming in the form of a content uri so I get the mime type as follows:
ContentResolver contentResolver = context.getContentResolver();
String mimeType = contentResolver.getType(uri);

From there I have been using MimeTypeMap:
MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);

This works great in most cases however there are a few glaring holes, one of them being that there is no entry for "audio/mp4".
Is there a more complete mapping I can use that is built into Android?  Or any other ideas?

A:
Is there a more complete mapping I can use that is built into Android?

No, sorry.

Or any other ideas?

Bake a MIME type map of your own into your app. See:

*

*List of ALL MimeTypes on the Planet, mapped to File Extensions?

*complete list of mime-type <-> file extension mapping

*Convert MimeType to extension
...and so on.


text:
Q: Text block width while wrapping floating image I got some problem with text width while it wrapping floating image. Here is good picture what describe the problem:

This guy post kinda poem, but formatting of his text was broken. His text should looks like this:

I'm already know the source of this problem. It because text block starts behind picture, and while text wrap around picture text block not growing longer and text stay in same bounds like there is no image at all. Here is the example fiddle: http://jsfiddle.net/czqGk/3/ I also add solution in JavaScript what do width compensation for text block.
I'm looking for solution without using JavaScript. Set minimum size of user post, or set another static width is not acceptable. Width should be dynamic and depends from content. Any ideas? :(

A: Defining the image within the longer text seems to fix the issue; here's a little demo: little link.


text:
Q: Do we say "strip me by eyes" or "strip me by the eyes"? Do we say:

You strip me by eyes

or

You strip me by the eyes

?
The sense I intend to get is something like, a person undressing someone else just by looking at him.

A: The idiom is undress sb. with one's eyes.
As often happens in idioms, we wouldn't ever say "strip" here even though it's a synonym for "undress".
So, the expression you're looking for is
You undress me with your eyes.


text:
Q: VBA works stepping through but not running My VBA code below works when I step through but not when I run it. I want each tab to be saved as a csv file in my chosen folder. When I run it, the code saves the first sheet multiple times named after each tab. Hope this is clear, see code below.
Sub SaveAsCsv()
Dim xWs As Worksheet
Dim xDir As String
Dim folder As FileDialog
Set folder = Application.FileDialog(msoFileDialogFolderPicker)
If folder.Show <> -1 Then Exit Sub
xDir = folder.SelectedItems(1)
For Each xWs In Application.ActiveWorkbook.Worksheets
xWs.SaveAs xDir & "\" & xWs.Name, xlCSV
Next
End Sub

Thanks!

A: delete the created file and then run again. because F8 has already created the file and while you run f5 it does not know where to save

A: Your naming is a bit confusing. Therefore I have changed the variable names. But now the code works.
Sub SaveAsCsv()
    ' 53

    Dim Ws As Worksheet
    Dim Folder As String
    Dim Dialog As FileDialog

    Set Dialog = Application.FileDialog(msoFileDialogFolderPicker)
    If Dialog.Show Then
        Folder = Dialog.SelectedItems(1)
        For Each Ws In ActiveWorkbook.Worksheets
            Ws.SaveAs Folder & "\" & Ws.Name, xlCSV
        Next
    End If
    MsgBox "Done", vbInformation, "Action report"
End Sub

Note that exiting the procedure before its end isn't good programming practice, akin to the use of GoTo commands. Try and avoid either whenever you can. In this case it's easy to do, using the same IF statement you have anyway.