text:
Q: ActiveX ComboBox_Change event falsely triggering a Compile Error: Variable not defined This is being triggered by my Option Explicit at the top of my module. When I open my workbook, my cbSelectData_Change event fires (for whatever reason), which then says my variable cbStartDate is not defined (i'll include the lines but it shouldn't be relevant:
topnum = ThisWorkbook.Worksheets("Data Pull").Columns(3).Find(What:=cbStartDate.Value, LookIn:=xlValues).Row
botnum = ThisWorkbook.Worksheets("Data Pull").Columns(3).Find(What:=cbEndDate.Value, LookIn:=xlValues).Row

cbSelectData is an ActiveX ComboBox containing a data category that charts populate off of. cbStartDate and cbEndDate are ActiveX ComboBoxes that alter the date range displayed on the chart x-axies.
I can confirm that I have a cbStartDate and a cbEndDate on my worksheet:

In fact, when I just exit the debugger (twice) my file will work fine; I can freely change my cbStartDate and cbEndDate and my charts update as expected, and I never see the compile error again (until re-opening the file).
My Suspicion:
This has something to do with the instantiations of the ActiveX controls - while cbSelectData is loaded (and firing its Change event), it's not finding cbStartDate or cbEndDate because they're not loaded yet.
What I need to do:
I either need to stop my cbSelectData_Change event from firing when I open the file, or I need to force the loading of my cbStartDate and cbEndDate before this event fires. I've messed around with Application.EnableEvents to no avail - any insight to this would be appreciated.
Note: These have to be ActiveX controls for formatting purposes. I also know that I can remove my Option Explicit altogether, but I'd REALLY rather not...

A: I'm not sure what broke it, but ActiveX controls can be flaky.
Try retrieving the object at run-time instead of compile-time:
Public Function FindActiveXControl(ByVal sh As Worksheet, ByVal name As String) As Object

    Dim objects As OLEObjects
    Set objects = sh.OLEObjects

    On Error Resume Next
        Dim oleControl As OLEObject
        Set oleControl = objects.Item(name)
    On Error GoTo 0

    If Not oleControl Is Nothing Then Set FindActiveXControl = oleControl.Object

End Function

Now you can work with locals, and handle the weird case where the control wouldn't be found:
Dim sheet As Worksheet
Set sheet = Me

Dim startDateControl As MSForms.ComboBox
Set startDateControl = FindActiveXControl(sheet, "cbStartDate")
If Not startDateControl Is Nothing Then
    topnum = ThisWorkbook.Worksheets("Data Pull").Columns(3).Find(What:=startDateControl.Value, LookIn:=xlValues).Row
End If

Dim endDateControl As MSForms.ComboBox
Set endDateControl = FindActiveXControl(sheet, "cbEndDate")
If Not endDateControl Is Nothing Then
    botnum = ThisWorkbook.Worksheets("Data Pull").Columns(3).Find(What:=endDateControl.Value, LookIn:=xlValues).Row
End If


text:
Q: Condition for pullback to split This is probably an elementary question, but I'm new to this machinery.
Let $G$ be a group and $N$ be a normal subgroup of $G$. Let $\Gamma$ be another group. Suppose we have a homomorphism $\phi:\Gamma \to G/N$.
Now we have the homomorphism $\phi:\Gamma \to G/N$ and the canonical quotient homomorphism $\psi:G \to G/N$.
Denote by $H$ the pullback of the two homomorphisms to $G/N$. That is, $H \subseteq  G \times \Gamma$ comprising elements $(g,\gamma)$ such that $\phi(\gamma)=\psi(g) \in G/N$.
So we have the following two diagrams:
$$1 \rightarrow N \rightarrow G\stackrel{\psi}{\rightarrow} G/N\rightarrow 1$$
which is a short exact sequence, and another diagram
$$\begin{array}
GG & \stackrel{\psi}{\longrightarrow} & G/N\\
\uparrow & & \uparrow{\phi} \\
H & \longrightarrow & \Gamma
\end{array}
$$
Is the following also a commutative diagram?
$$\begin{array}
11 & \longrightarrow & N & \longrightarrow & G & \stackrel{\psi}{\longrightarrow} & G/N & \longrightarrow & 1\\
& & \uparrow & & \uparrow & & \uparrow{\phi} & & \\
1 & \longrightarrow &  N & \longrightarrow & H & \longrightarrow & \Gamma & \longrightarrow & 1\\
\end{array}
$$
That is, can $N$ be embedded in the pullback $H$?
Secondly, suppose the map $\phi:\Gamma \to G/N$ can be lifted to a map $\phi':\Gamma \to G$ so that we have a commuting diagram bypassing $H$. In this case, is $H$ a semidirect product of $N$ and $\Gamma$?
In other words, is the bottom exact sequence split when $\phi$ can be lifted diagonally to $G$, and is the converse true too?
Thanks!

A: Yes and Yes. The subgroup $N$ of $H$ that you are looking for is $\{(n,1) : n \in N \}$, and the complement you are looking for is $\{(\phi'(\gamma),\gamma) : \gamma \in \Gamma\}$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Map OpenID profiles from different providers that belong to a single user Each time a user logs in to my site via SocialAuth, a new profile is created for him if this is the first time this profile was used. Is there a standard way to map multiple OpenID profiles from different providers that belong to a single user?
For example, if a user logged in to my job board using his Yahoo profile and applied for some jobs, then logged in using Gmail and applied for some more, then realized that he has multiple profiles and must log out and re-login each time to access previous applications and related correspondence, I would like to allow that user to merge his profiles and allow logging in to the merged profile using either one going forward.


text:
Q: JSON Parsing error: No value for JSON array I have a code where i should pass an static user id for authentication and then fetch the JSON response from the URL and display it in listview. But i get an error that says "JSON Parsing error: No value in (JSON array)". Please help

MainActivity.java:

 public class MainActivity extends AppCompatActivity {

        private String TAG = MainActivity.class.getSimpleName();

        private ProgressDialog pDialog;
        private ListView lv;

        // URL to get contacts JSON
        private static String url = "url";

        ArrayList<HashMap<String, String>> contactList;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            contactList = new ArrayList<>();

            lv = (ListView) findViewById(R.id.list);

            new GetContacts().execute();
        }

        /**
         * Async task class to get json by making HTTP call
         */
        private class GetContacts extends AsyncTask<Void, Void, Void> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Showing progress dialog
                pDialog = new ProgressDialog(MainActivity.this);
                pDialog.setMessage("Please wait...");
                pDialog.setCancelable(false);
                pDialog.show();

            }

            @Override
            protected Void doInBackground(Void... arg0) {

     List<NameValuePair> list=new ArrayList<>();
                list.add(new BasicNameValuePair("user_id", "2"));

                HttpHandler sh = new HttpHandler();

                // Making a request to url and getting response
                String jsonStr = sh.makeServiceCall(url);

                Log.e(TAG, "Response from url: " + jsonStr);

                if (jsonStr != null) {
                    try {
                        JSONObject jsonObj = new JSONObject(jsonStr);

                        // Getting JSON Array node
                        JSONArray contacts = jsonObj.getJSONArray("promotion_lists");

                        // looping through All Contacts
                        for (int i = 0; i < contacts.length(); i++) {
                            JSONObject c = contacts.getJSONObject(i);

                            String promotion_id = c.getString("promotion_id");
                            String promotion_title = c.getString("promotion_title");
                            String promotion_description = c.getString("promotion_description");
    //
                            HashMap<String, String> contact = new HashMap<>();

                            // adding each child node to HashMap key => value
                            contact.put("promotion_id", promotion_id);
                            contact.put("promotion_title", promotion_title);
                            contact.put("promotion_description", promotion_description);

                            // adding contact to contact list
                            contactList.add(contact);
                        }
                    } catch (final JSONException e) {
                        Log.e(TAG, "Json parsing error: " + e.getMessage());
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Toast.makeText(getApplicationContext(),
                                        "Json parsing error: " + e.getMessage(),
                                        Toast.LENGTH_LONG)
                                        .show();
                            }
                        });

                    }
                } else {
                    Log.e(TAG, "Couldn't get json from server.");
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Toast.makeText(getApplicationContext(),
                                    "Couldn't get json from server. Check LogCat for possible errors!",
                                    Toast.LENGTH_LONG)
                                    .show();
                        }
                    });

                }

                return null;
            }

            @Override
            protected void onPostExecute(Void result) {
                super.onPostExecute(result);
                Log.e("SignUpRsp", String.valueOf(result));

                // Dismiss the progress dialog
                if (pDialog.isShowing())
                    pDialog.dismiss();
                /**
                 * Updating parsed JSON data into ListView
                 * */
                ListAdapter adapter = new SimpleAdapter(
                        MainActivity.this, contactList,
                        R.layout.list_item, new String[]{"promotion_id", "promotion_title",
                        "promotion_description"}, new int[]{R.id.promotion_id,
                        R.id.promotion_title, R.id.promotion_desc});

                lv.setAdapter(adapter);
            }

        }
        public String PostData(String[] valuse) {
            String s="";

            try
            {
                HttpClient httpClient=new DefaultHttpClient();
                HttpPost httpPost=new HttpPost("url");

                List<NameValuePair> list=new ArrayList<>();
                list.add(new BasicNameValuePair("user_id", "value"));

                httpPost.setEntity(new UrlEncodedFormEntity(list));
                HttpResponse httpResponse=  httpClient.execute(httpPost);

                HttpEntity httpEntity=httpResponse.getEntity();
                s= readResponse(httpResponse);

            }
            catch(Exception exception)  {}
            return s;

        }
        public String readResponse(HttpResponse res) {
            InputStream is=null;
            String return_text="";
            try {
                is=res.getEntity().getContent();
                BufferedReader bufferedReader=new BufferedReader(new InputStreamReader(is));
                String line="";
                StringBuffer sb=new StringBuffer();
                while ((line=bufferedReader.readLine())!=null)
                {
                    sb.append(line);
                }
                return_text=sb.toString();
            } catch (Exception e)
            {

            }
            return return_text;

        }
    }

JSON Response:

  {
            "status": "1",
            "message": "Ok",
            "promotion_lists": [
                {
                    "promotion_id": "3",
                    "promotion_image_name": "1.jpg",
                    "promotion_image_url": "url.jpg",
                    "promotion_title": "winner",
                    "promotion_description": "good\ngold\nred",
                    "admin_status": "1",
                    "promotion_status": "1",
                    "promotion_status_description": "Live"
                },

            ]
        }

A: Your json also has an issue, can you try with this output json. Last comma(,) in an array is not required.
{
        "status": "1",
        "message": "Ok",
        "promotion_lists": [
            {
                "promotion_id": "3",
                "promotion_image_name": "1.jpg",
                "promotion_image_url": "url.jpg",
                "promotion_title": "winner",
                "promotion_description": "good\ngold\nred",
                "admin_status": "1",
                "promotion_status": "1",
                "promotion_status_description": "Live"
            }
        ]
}

A: Your JSON parsing is correct
You need to parse your JSON  if your response status response code is 1
SAMPLE CODE
Try this
    if (jsonStr != null) {
        try {
            JSONObject jsonObj = new JSONObject(jsonStr);

            // check here of your status of response
            // is status is 0 USER NOT FOUND
            if(jsonObj.getString("status").equals("0")){

           MainActivity.this.runOnUiThread(new Runnable() {
               @Override
              public void run() {
            Toast.makeText(MainActivity.this, jsonObj.getString("message"), Toast.LENGTH_SHORT).show();
               }
           });

            // is status is 1 PARSE YOUR JSON
            }else {
                JSONArray contacts = jsonObj.getJSONArray("promotion_lists");

                // looping through All Contacts
                for (int i = 0; i < contacts.length(); i++) {
                    JSONObject c = contacts.getJSONObject(i);

                    String promotion_id = c.getString("promotion_id");
                    String promotion_title = c.getString("promotion_title");
                    String promotion_description = c.getString("promotion_description");

                    HashMap<String, String> contact = new HashMap<>();

                    // adding each child node to HashMap key => value
                    contact.put("promotion_id", promotion_id);
                    contact.put("promotion_title", promotion_title);
                    contact.put("promotion_description", promotion_description);

                    // adding contact to contact list
                    contactList.add(contact);
                }
            }

        } catch (final JSONException e) {
            Log.e(TAG, "Json parsing error: " + e.getMessage());
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getApplicationContext(),
                            "Json parsing error: " + e.getMessage(),
                            Toast.LENGTH_LONG)
                            .show();
                }
            });

        }
}

A: You can use this solution
public class GetContacts extends AsyncTask<String, Void, String> {
        protected void onPreExecute() {
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setMessage("Please wait...");
            pDialog.setCancelable(false);
            pDialog.show();
        }

        protected String doInBackground(String... arg0) {

            try {
                URL url = new URL(URL HERE);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
                conn.setRequestProperty("Accept", "application/json");
                conn.setDoOutput(true);
                conn.setDoInput(true);
                conn.setReadTimeout(5000);
                conn.setConnectTimeout(5000);
                JSONObject postDataParams = new JSONObject();
                postDataParams.put("user_id", user_id);
                Log.i("JSON", postDataParams.toString());
                DataOutputStream os = new DataOutputStream(conn.getOutputStream());
                //os.writeBytes(URLEncoder.encode(jsonParam.toString(), "UTF-8"));
                os.writeBytes(postDataParams.toString());
                os.flush();
                os.close();

                Log.i("STATUS", String.valueOf(conn.getResponseCode()));
                Log.i("MSG", conn.getResponseMessage());

                int responseCode = conn.getResponseCode();

                if (responseCode == HttpsURLConnection.HTTP_OK) {

                    BufferedReader in = new BufferedReader(new
                            InputStreamReader(
                            conn.getInputStream()));

                    StringBuffer sb = new StringBuffer("");
                    String line = "";

                    while ((line = in.readLine()) != null) {

                        sb.append(line);
                        break;
                    }

                    in.close();
                    conn.disconnect();
                    return sb.toString();

                } else {
                    conn.disconnect();
                    return new String("false : " + responseCode);
                }

            } catch (Exception e) {
                return new String("Exception: " + e.getMessage());
            }

        }

        @Override
        protected void onPostExecute(String jsonStr) {
            try {
                 pDialog();
                Log.e(TAG, "Response from url: " + jsonStr);

            if (jsonStr != null) {
                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    // Getting JSON Array node
                    JSONArray contacts = jsonObj.getJSONArray("promotion_lists");

                    // looping through All Contacts
                    for (int i = 0; i < contacts.length(); i++) {
                        JSONObject c = contacts.getJSONObject(i);

                        String promotion_id = c.getString("promotion_id");
                        String promotion_title = c.getString("promotion_title");
                        String promotion_description = c.getString("promotion_description");
//
                        HashMap<String, String> contact = new HashMap<>();

                        // adding each child node to HashMap key => value
                        contact.put("promotion_id", promotion_id);
                        contact.put("promotion_title", promotion_title);
                        contact.put("promotion_description", promotion_description);

                        // adding contact to contact list
                        contactList.add(contact);
                    }
/**
             * Updating parsed JSON data into ListView
             * */
            ListAdapter adapter = new SimpleAdapter(
                    MainActivity.this, contactList,
                    R.layout.list_item, new String[]{"promotion_id", "promotion_title",
                    "promotion_description"}, new int[]{R.id.promotion_id,
                    R.id.promotion_title, R.id.promotion_desc});

            lv.setAdapter(adapter);

                } catch (final JSONException e) {
                    Log.e(TAG, "Json parsing error: " + e.getMessage());
                    Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();

                }
            } else {
                Log.e(TAG, "Couldn't get json from server.");
                Toast.makeText(getApplicationContext(),
                                    "Json parsing error: " + e.getMessage(),
                                    Toast.LENGTH_LONG)
                                    .show();

            }
            } catch (JSONException e) {
                e.printStackTrace();
            }

        }
    }

One more thing you dont need to use runOnUiThread in Asynctask because
  both are helper threads , which are used to Update UI,you dont have to
  use runOnUIThread in it , just simple show toast without using it, it
  will show it , read the documentation
https://developer.android.com/guide/components/processes-and-threads

A: JSONArray throw error because promotion_lists with a item but has needless comma.
{
    "status": "1",
    "message": "Ok",
    "promotion_lists": [
        {
            "promotion_id": "3",
            "promotion_image_name": "1.jpg",
            "promotion_image_url": "url.jpg",
            "promotion_title": "winner",
            "promotion_description": "good\ngold\nred",
            "admin_status": "1",
            "promotion_status": "1",
            "promotion_status_description": "Live"
        }
    ]
}

A: Your JSON parse looks fine. The issue is with the your JSON response. It  is not a valid JSON Response as there is a unnecessary comma after the JSON Array "promotion_lists". Try removing the comma.


text:
Q: EnableViewStateMac Documentation Warning? There is a warning in the @Page directive regarding the EnableViewStateMac setting found here that states:
"Security Note This attribute should never be set to false in a production Web site."
This warning seems unconditional, regardless of the Page ViewState setting (true or false).  Does this warning apply to @Pages that have EnableViewState set to false?  If the warning does apply in this case, why, when ViewState is turned completely off for the page and its child controls, is this a concern?
Upgate: The warning seems to apply, being that some doofus could drop a control that uses Control State on to a page that has ViewState = false AND ViewStateMac = false.

A: If there's no viewstate there's no harm in leaving it on ... and, remember, there are cases where, despite your best attempts viewstate may sneak in, under the guise of control state, so the warning still applies.


text:
Q: Open two apps at a time to a single click I want to open two apps (ie., WhatsApp and Facebook) at a time to a single button click. If any one knows about this please help me to resolve my issue.
I write like this to open both the apps.
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.whatsapp");
startActivity(launchIntent);
Intent launchface = getPackageManager().getLaunchIntentForPackage("com.facebook.katana");
startActivity(launchface);

But this code is opening the Facebook app only.

A: Hi i got the solution for the my question i opened two apps with some time delay. Here is my code.
 Handler handler = new Handler();
 handler.postDelayed(new Runnable() {
  @Override
  public void run() {
    btn1.setBackgroundColor(Color.GREEN);
  }
}, 1000);
handler.postDelayed(new Runnable() {
 @Override
 public void run() {
    btn1.setBackgroundResource(R.drawable.selector);
 }
}, 2000);

A: Anyhow, Try this :-

*

*Open 1st app with startActivityForResult

*Once you get the result of that intent, open 2nd app

Let me know if this works for you. Otherwise please give more details about your requirements, so we can help you

A: I don't know why android system does not start two apps at once directly. However, you can launch another app after some delay.
First write a method like this:
private static void openApp(Context context, String packageName) {
    Intent intent = context.getPackageManager().getLaunchIntentForPackage(packageName);
    if (intent != null && intent.resolveActivity(context.getPackageManager()) != null) {
        context.startActivity(intent);

    } else System.err.println("Cannot open: " + packageName);
}

Then from your activity, run two apps like this:
openApp(this, "com.whatsapp");
new android.os.Handler().postDelayed(new Runnable() {
    @Override
    public void run() {
        openApp(MainActivity.this, "com.facebook.katana");
    }
}, 100);

A: I got a solution for my question.
 This code is working it is opening the two apps at a time.
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        Intent launchIntentuber = getPackageManager().getLaunchIntentForPackage("com.whatsapp");
        startActivity(launchIntentuber);
    }
}, 1000);

handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.facebook.katala");
        startActivity(launchIntent);
    }
}, 2000);


text:
Q: TypeScript: in recursive type, extra props allowed to be assigned in object declaration only When creating an object using the following recursive type, somehow extra keys not present in the type are allowed to be added when the object is created (but not afterward). Any thoughts on why this is?
type WithChildProps<Props, ChildProps> = Props & { __childProps__: ChildProps };

type WrappedProps<Props extends Record<string, any>, WrapperPropsTuple extends any[]> = WrapperPropsTuple extends [infer ParentProps, ...infer ChildProps]
  ? ChildProps extends []
    ? WithChildProps<ParentProps, Props>
    : WithChildProps<ParentProps, WrappedProps<Props, ChildProps>>
  : string;

type ObjTuple = [
  { prop1: string },
  { prop2: string },
  { prop3: string },
];

type ObjProps = { mainProp: string };

type ObjWrappedProps = WrappedProps<ObjProps, ObjTuple>;

const obj: ObjWrappedProps = {
  prop1: 'allowed',
  __childProps__: {
    prop2: 'allowed',
    __childProps__: {
      prop3: 'allowed',
      extraProp: 'why is this allowed?', // Should error but doesn't
      __childProps__: {
          mainProp: 'allowed',
          extraProp: 'and this also?', // Should error but doesn't
      },
    },
  },
};

// Errors as expected
obj.extraProp = 'expected error';
obj.__childProps__.__childProps__.extraProp = 'expected error';

A: While I'm unable to explain this behavior, I can provide you with working utility type.
Consider this example:
type ObjTuple = [
  { prop1: string },
  { prop2: string },
  { prop3: string },
];

type ObjProps = { mainProp: string };

type Key = '__childProps__';

type Builder<
  Tuple extends any[],
  Level extends number[] = [],
  Result = {}> =
  Level['length'] extends Tuple['length']
  ? Result & ObjProps
  : Tuple[Level['length']] & {
    [Prop in Key]:
    Builder<Tuple, [...Level, 1], Result>
  }

// ok
const test: Builder<ObjTuple> = {
  prop1: 'allowed',
  __childProps__: {
    prop2: 'allowed',
    __childProps__: {
      prop3: 'allowed',
      __childProps__: {
        mainProp: 'allowed',
      },
    },
  },
};

const test2: Builder<ObjTuple> = {
  prop1: 'allowed',
  __childProps__: {
    prop22: 'allowed', // expected error
    __childProps__: {
      prop3: 'allowed',
      __childProps__: {
        mainProp: 'allowed',
      },
    },
  },
};

const test3: Builder<ObjTuple> = {
  prop1: 'allowed',
  __childProps__: {
    prop2: 'allowed',
    __childProps__: {
      prop3: 'allowed',
      __childProps__: {
        mainProp2: 'allowed', // expected error
      },
    },
  },
}

Playground
Builder - iterates through only one property __childProps__ while Level tuple length less than original tuple ObjTuple. IF length is equal - return Result merged with ObjProps, otherwise: merge prop from tuple by index Tuple[Level['length']] with recursive iteration through  __childProps__.
As you might have noticed, I increase Level tuple each time by 1.


text:
Q: How to get multiple api with axios? I want to get multiple api in the same page. With the following code, all the return data from "apione" is work, but not sure why I get nothing from the "apitwo".
async created() {

    let apione = "https://k67r3w45c4.execute-api.ap-southeast-1.amazonaws.com/TwitterTrends";
    let apitwo = "http://ec2-54-179-187-25.ap-southeast-1.compute.amazonaws.com/Test/?param1=HelloHanbinIsFREE"

    try {
      const res = await axios.get(apione);

      this.toptrends1 = res.data[0].Trends;
      this.toptrends2 = res.data[1].Trends;
      this.toptrends3 = res.data[2].Trends;
      this.toptrends4 = res.data[3].Trends;
      this.toptrends5 = res.data[4].Trends;

      this.tweet1 = res.data[0].TweetVolume;
      this.tweet2 = res.data[1].TweetVolume;
      this.tweet3 = res.data[2].TweetVolume;
      this.tweet4 = res.data[3].TweetVolume;
      this.tweet5 = res.data[4].TweetVolume;

      var thetime = res.data[0].retrievalDate
      thetime = thetime.split("T")[0];
      this.time = thetime

      // ----------------------------------API 2 -------------------------------------

      const res2 = await axios.get(apitwo);
      this.trend1fre = res2.data[0].Frequency;

    } catch (e) {
      console.errpr(e);
    }
  },

A: Open the Developer Tools in your browser. Look at the Console. Read the error messages.
When I test your code, I get:

Mixed Content: The page at 'https://jsbin.com/?html,js,console' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://ec2-54-179-187-25.ap-southeast-1.compute.amazonaws.com/Test/?param1=HelloHanbinIsFREE'. This request has been blocked; the content must be served over HTTPS.

One of your APIs uses HTTP the other uses HTTPS. They should both use the same scheme as you used to load the HTML document (and that should almost certainly be HTTPS).

A: try axios.all([apione, apitwo])

A: the problem with the response from apitwo is just the lack of the necessary Access-Control-Allow-Origin header, you can still get things to work—by making the request through a CORS proxy.
replace below
const res2 = await axios.get(apitwo);

with
const res2 = await axios.get('https://cors-anywhere.herokuapp.com/'+apitwo);

for further research on the problem go to this stackover flow answer


text: Q: Почему MongoDB и passportjs не работает при использовании camelCase? Использую passportjs и mongo в качестве бд. Делаю авторизацию, при регистрации в базу добавляю объект с именем и паролем. Если использую в качестве имени свойства username, то все работает как нужно. Но если меняю свойство на userName, то перестает работать, как будто в базе нет такого объекта. Изза чего может так происходить?


text:
Q: How to get System.ServiceModel.DiscoveryClient to use IGMP? I have a D-Link DGS-1210-10P with two VLAN's (10.104.. and 192.168..)  I have a video camera on each network, and two NIC's in my computer on each network.
With IGMP off on the D-Link, I can discover both cameras using Microsoft DiscoveryClient, and some custom endpoint that allows me to specify which NIC to send the mutlicast message out.  With IGMP turned on, I only see the 10.104 network.
foreach (string id in getAdapterIds())
{
   DiscoveryClient dc = new DiscoveryClient(new UdpDiscoveryEndpointByNIC(DiscoveryVersion.WSDiscoveryApril2005, id));
   dc.FindProgressChanged += _real_FindProgressChanged;
   dc.FindAsync();
}

I do see IGMP messages in Wireshark (both sources are my computer, and the destination is the correct multicast address)
Source        Destination     Protocol Length Info
10.104.128.37 239.255.255.250 IGMPv2   60     Membership Report Group
192.168.1.1   239.255.255.250 IGMPv2   60     Membership Report Group

My question boils down to: Does DiscoveryClient automatically join IGMP groups and should just work?  I'm suspecting that there is just some fundamental IGMP understanding I'm missing, or some D-Link router setting.

A: As usual, I find answers right after I ask questions:
The problem was that IGMP on the router was not set up correctly.
So,
Corporate VLAN
1) Disable "Querier State", because the corporate switch is already a querier
2) Enable "Fast Leave"
Isolated VLAN
1) Enable "Querier State", because each VLAN needs a querier
2) Enable "Fast Leave"


text:
Q: Does Amazon Corretto JRE supports any JavaFx dependency? I need to add javafx dependency(as we do for other dependencies, adding in the pom) to my project which runs on amazon corretto jre, so here I have two questions:-

*

*Is there any javafx dependency that would work with Amazon Corretto jre?

*If so, could anyone please suggest what version of amazon corretto jre supports what version of javafx
dependency?


text:
Q: Error in finding minimum element in perl I am trying to get the minimum and maximum element in an array of elements in perl, every thing is working fine but the minimum element is not getting printed:
@array1=();
$i=0;
$array1[$i]=<STDIN>;
$sum=$minimum=$maximum=$array1[$i];
while($array1[$i]!=" ")
{
    $i=$i+1;
    $array1[$i]=<STDIN>;
    $sum=$sum+$array1[$i];
    if($array1[$i]>$maximum)
    {
        $maximum=$array1[$i];
    }
    if($array1[$i]<$minimum)
    {
        $minimum=$array1[$i];
    }
    if($array1[$i]==" ")
    {
        last;
    }
}
print("Entered numbers are : ",@array1);
print("Sum of all numbers is : ",$sum);
print "\n";
print("Minimum number is : ",$minimum);
print "\n";
print("Maximum number is : ",$maximum);

A: Consider what occurs when you enter a space in your loop.  You assign it to $array1[$i].  You then check for min and max.  So if you have a string and do numeric comparisons, it will convert the string to a number if it can (such as "12" is 12).  If you have a string which is not a number (such as a space) then it convert to 0.
I suspect that you are typing positive number, so when you enter a space, the if condition for the minimum is true and space is placed in the minimum value.  If you put in a negative number, it will print out the negative number with your code.
If you move your check for the to see if you are finished to after you read in the item and before you do the checks, it would probably work better and you would not go through the comparisons as you don't really need to do any comparisons/assignments since you are finished and the entry is not a number.

A: Just move this:
if($array1[$i]==" ")
{
        last;
}

to beginning of the loop block!!
A simplified version of your code:
use strict;
use warnings;

my @items;
my ( $sum, $max, $min );

while ( chomp( my $num = <STDIN> ) ) {
    last if ( $num eq ' ' );
    next if ( $num eq '' );

    $max ||= $num;
    $min ||= $num;
    $sum += $num;

    $max = $num if ( $num > $max );
    $min = $num if ( $num < $min );

    push( @items, $num );
}

printf( "Entered numbers are: %s \n", join( ', ', @items ) );
print( "Sum of all numbers is : ", $sum );
print "\n";
print( "Minimum number is : ", $min );
print "\n";
print( "Maximum number is : ", $max );


text:
Q: XSLT limit on 500? A client/customer of ours contacted us about a possible bug and after some searching for an error, we can't really find one.
The problem is that the client has a guestbook, which is a list of comments so we simply put list all comments but for some reason it can't get past 500. 1-499 is the posts that we get back. I have made a simple XSLT script for trying out it but can't get more than 500 either.
Here is my test script:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:msxsl="urn:schemas-microsoft-com:xslt"
 exclude-result-prefixes="msxsl">
    <xsl:output method="html" indent="yes"/>
    <xsl:template match="/">

            <xsl:for-each
                 select="/descendant::node[@id='6221']
                            /node[@nodeTypeAlias = 'BlogPostComment']">

                    <xsl:value-of select="@nodeName"/>

                        <xsl:value-of select="./data[@alias = 'comment']"/>

            </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

I have tried the script both with and without the xslt:sort but neither gives me more posts. Is there some kind of limit in XSLT that makes it impossible to get more than 500 subnodes in a for-each? Apparently count(...) doesn't get more than 499 either. There is a count in the XSLT script running on the clients site and it shows 499 too.
EDIT:
Turned out there is nothing wrong other than the id which the client sorted the post by was converted to string and thereby the 10000 node id's was no longer bigger (sorting wise) than the 9000 node id's and these new posts was showed first in the list since the first nodes had id's starting at 6000. We just changed the sorting field and it all worked just fine again.

A: No, XSLT itself has no limit, however XSLT is a specification, not an implementation. That said, I would find it hard to believe that an XSLT implementation would have arbitrary limits in the way that you are describing.
Consider looking at the source XML data. Perhaps something there is causing the issue. Maybe whatever is writing the data is accidentally truncating it to 500 records.


text:
Q: How to obtain UserTransaction in websphere8.5.0.0? I had deployed my EJB application in Websphere 8.5.0.0 server but while starting it I am facing below exception:
 **CNTR0020E: EJB threw an unexpected (non-declared) exception during invocation of method "getABCMethod" on bean "BeanId(ABC-ear#ABC-ejb-3.9.jar#ABC, null)". Exception data: org.hibernate.TransactionException: Could not find UserTransaction in JNDI [java:comp/UserTransaction]**
    at org.hibernate.transaction.JTATransactionFactory.getUserTransaction(JTATransactionFactory.java:173)
    at org.hibernate.transaction.JTATransactionFactory.createTransaction(JTATransactionFactory.java:149)
    at org.hibernate.jdbc.JDBCContext.registerSynchronizationIfPossible(JDBCContext.java:213)
    at org.hibernate.jdbc.JDBCContext.<init>(JDBCContext.java:103)
    at org.hibernate.impl.SessionImpl.<init>(SessionImpl.java:256)
    at org.hibernate.impl.SessionFactoryImpl.openSession(SessionFactoryImpl.java:670)
    at org.hibernate.context.JTASessionContext.buildOrObtainSession(JTASessionContext.java:152)
    at org.hibernate.context.JTASessionContext.currentSession(JTASessionContext.java:111)
    at org.hibernate.impl.SessionFactoryImpl.getCurrentSession(SessionFactoryImpl.java:687)

**Caused by: javax.naming.NameNotFoundException: Name "comp/UserTransaction" not found in context "java:".**
    at com.ibm.ws.naming.ipbase.NameSpace.lookupInternal(NameSpace.java:1228)
    at com.ibm.ws.naming.ipbase.NameSpace.lookup(NameSpace.java:1141)
    at com.ibm.ws.naming.urlbase.UrlContextImpl.lookupExt(UrlContextImpl.java:1436)
    at com.ibm.ws.naming.java.javaURLContextImpl.lookupExt(javaURLContextImpl.java:477)
    at com.ibm.ws.naming.java.javaURLContextRoot.lookupExt(javaURLContextRoot.java:485)
    at com.ibm.ws.naming.java.javaURLContextRoot.lookup(javaURLContextRoot.java:370)
    at javax.naming.InitialContext.lookup(InitialContext.java:436)
    at org.hibernate.transaction.JTATransactionFactory.getUserTransaction(JTATransactionFactory.java:163)
    ... 39 more

I had already tried various solution available as changing JNDI name to "jta/UserTransaction" , "UserTransaction" and "java:comp/UserTransaction" but none of them working.
Is it webpshere-hibernate compatibility issue or websphere 8.5.0.0 specific?
Please suggest what could be the solution. Thanks in advance.

A: Looks like, you need to upgrade WAS to FIX PACK 2 , COMP/USERTRANSACTION" NOT FOUND IN CONTEXT "JAVA
or if you might be making this mistake , doing lookup at incorrect place Transaction and Websphere - problems


text:
Q: awk for finding date difference in days from two column For date like
20 20180110 20180113
100 20180110 20180115
9 20180110 20180114

desired output
20 20180110 20180113 3
100 20180110 20180115 5
9 20180110 20180114 4

pls help me to with awk command.

A: Using GNU awk, mktime() and substr() function
Input:
$ cat file
20 20180110 20180113
100 20180110 20180115
9 20180110 20180114

Output:
awk 'function df(v){ return mktime(substr(v,1,4)" "substr(v,5,2)" "substr(v,7,2)" "0" "0" "0)  }{print $0,(df($3)-df($2))/86400}' file
20 20180110 20180113 3
100 20180110 20180115 5
9 20180110 20180114 4

Better Readable:
awk '
    function df(v)
    {
      return mktime(substr(v,1,4)" "substr(v,5,2)" "substr(v,7,2)" "0" "0" "0)
    }
    {
      print $0,(df($3)-df($2))/86400
    }
    ' file


text:
Q: Yii ActiveRecord vs Repository patterns Those methods have both advantages and disadvantages.
I am developing a mid-sized application using Yii.
Yii has adopted the AR pattern and supports it by default. The advantages of using a repository pattern are very clear but the question is: should I really invest time in implementing a repository pattern combined with Yii?
Also I would like to know your opinion regarding this two patterns. I would also like to know why is AR so popular and so frequently used? In my opinion Repository pattern is more flexible, more testable, has a cleaner code and integrates better in an enterprise application.
Should I continue using the AR pattern with Yii?
I'm also thinking about switching from Yii to Laravel. In this moment I won't lose much of my work by doing this.

A: As for me, ActiveRecord is pretty good in small projects, but for medium or huge apps it is hard to maintain.
pros of Yii ActiveRecord

*

*Using of Yii AR can speed up coding. All AR models and controllers can be one-click generated by gii.

*AR is extremely popular. Almost all developers are familiar with this pattern. New team members dive into the project faster.

cons of Yii ActiveRecord
In case of Yii, too much logic concentrated in AR model classes:

*

*Validation

*Find methods

*Business logic

That makes code:

*

*Less readable. Often AR classes consists of several dozen of unrelated methods. Logic can be decomposed using behaviors or traits. But in fact it is still really hard to maintain.

*Hard to test.
When the app becomes big enough, the addition layer between Controller and AR model is needed. Repository is a great choice. As for me, I started using repository in Laravel, but now I am using it in Yii 1/2 too.
It is not actually the problem to implement repository in Yii. Yii's AR is very similar to Laravel's Eloquent. It is much harder to force all team members not to work with AR directly, but use repositories instead.
If you have experience in Laravel, I recommend to use it.

A: It depends on type of your application:

*

*Complex business Application (Domain) worth the effort for repository for those reasons:

*

*Testable

*Data Source ignorance

*Use interfaces to adapt the data source to your domain

*Small Application (basicaly CRUD) just go with active record repository could overkill.
I use Yii2 active Record decorated in repository implementation, in reality with Yii2 you can have a real repository implementation because you can use ActiveQuery instead of the ActiveRecord class itself, ActiveQuery can return raw array data :
namespace app\clean\infrastructure;
class ActiveRepository implements ActiveRepositoryInterface
{
   protected $activeRecordClass;
   protected $query;
   protected $factory;

   function __construct($activeRecordClass)
   {
     $this->query = new ActiveQuery($activeRecordClass);
     $this->factory = new TheEntityFactoy;
   }

   public function findAll(){
     $data = $this->query->asArray()->all();
     return $this->factory->create($data);
   }

}


text:
Q: Converting a bnode to a string in graphdb I have an RDF file where the resources are identified with nodeID's instead of URIs. I have imported them into Ontotext graphdb, and would like to generate URIs based on the nodeID (which I preserved during import). For example, I am trying to map this triple
_:C00456 rdf:type skos:Concept

to this:
<https://example.com/data/C00456> rdf:type skos:Concept

Unfortunately, if ?s is a BNODE, STR(?s) is an empty string in graphdb. xsd:string(?s), ditto. IRI(?s), you guessed it. Is there any function that will expose the form of the bnode as a string, so that I can build a URI from it? I went through the list of functions in the sparql 1.1 specification and could not see any.
PS It would have been nice if graphdb would just convert the nodeIDs to URIs during import (I specified a prefix for relative names), but it went by the book and turned them into bnodes. If I overlooked something, I'll be glad to be set right.

A: You can use the spif:buildString function to convert a BNode to String and then to IRI.
Here is a sample query:
PREFIX spif: <http://spinrdf.org/spif#>
PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
CONSTRUCT {?sIRI ?p ?o}  WHERE {
?s ?p ?o .
    FILTER (isBlank(?s))
    BIND (IRI(spif:buildString("http://my/namespace/{?1}", ?s)) as ?sIRI)
} LIMIT 10

The function is documented here:
https://graphdb.ontotext.com/documentation/10.0/sparql-functions-reference.html?highlight=buildstring#sparql-spin-functions-and-magic-predicates


text:
Q: How To Alias Model Inside Angular I have an angular template, and I would like to reuse the template inside two different controllers. The issue is that both controllers require different ng-model names.
The template contains HTML like below, where the ng-model references are properties of "obj":
<input name="customer" ng-model="obj.customer" id="customer">

One of the controllers needs the ng-model names to be associated with "obj". This means the template is perfect as is.
The other controller needs the ng-model to be associated with, for the sake of simplicity, "obj1".
Is there a way to handle this in such a way that I could use the same HTML template? It seems a shame to have to duplicate the HTML just to change the ng-model name. I tried using ng-init, saying obj = obj1, but that doesn't seem to work.

A: As with what @PSL commented about...
Directives in Angular allow for templates and code to be re-used elsewhere throughout your application. You can pass an angular directive some sort of model, and it behaves as its own controller and own scope, isolating it from the rest of your app.
Take for example you wish to have a list of user's and their information, you can create a directive and pass onto it data on which to act upon. Then you can repeat the process as many times as you like.
For more information and examples you can check out Angular's write up on Directives. >> Directives guide.
I'll also provide a short example directive below with your customer problem..
>>plunkr example
.directive('myCustomer', ['$timeout', function($timeout) {
return {
  template: '<input name="customer" data-ng-model="customerInfo.name">',
  replace: true,
  scope: {
    customerInfo: "="
  },
  controller: ['$scope', function($scope){
    $scope.init = function(){
      console.log("i'm alive!");
    }
  }],
  link: function(scope, element, attrs, transclute, requires){
    scope.init();
  }
}
}])

Hope this helps!
-mbp


text:
Q: Check if a parameter is a Python module? How can I (pythonically) check if a parameter is a Python module? There's no type like module or package.
>>> os
<module 'os' from '/usr/lib/python2.6/os.pyc'>

>>> isinstance(os, module)
Traceback (most recent call last):
  File "/usr/lib/gedit-2/plugins/pythonconsole/console.py", line 290, in __run
    r = eval(command, self.namespace, self.namespace)
  File "<string>", line 1, in <module>
NameError: name 'module' is not defined

I can do this:
>>> type(os)
<type 'module'>

But what do I compare it to? :(
I've made a simple module to quickly find methods in modules and get help texts for them. I supply a module var and a string to my method:
def gethelp(module, sstring):

    # here i need to check if module is a module.

    for func in listseek(dir(module), sstring):
        help(module.__dict__[func])

Of course, this will work even if module = 'abc': then dir('abc') will give me the list of methods for string object, but I don't need that.

A: This seems a bit hacky, but:
>>> import sys
>>> import os
>>> type(os) is type(sys)
True

A: >>> import inspect, os
>>> inspect.ismodule(os)
True

A: A mix of @Greg Hewgill and @Lennart Regebro answers:
>>> from types import ModuleType
>>> import os
>>> type(os) is ModuleType
True

A: from types import ModuleType

isinstance(obj, ModuleType)

A: Flatten the module to a string and check if it starts with '<module '
import matplotlib
foobarbaz = "some string"
print(str(matplotlib).startswith("<module "))     #prints True
print(str(foobarbaz).startswith("<module "))      #prints False

Drawback being this could collide with a python string that starts with the text '<module'  You could try to classify it more strongly with a regex.

A: Another way to do this without importing anything else is to make it a string and directly compare to the output:
import os

print(str(type(os)))  #Prints "<class 'module'>"

print(str(type(os))) == "<class 'module'>")  #Prints True

A: Two ways,you could not import any modules:

*

*type(os) is type(__builtins__)

*str(type(os)).find('module')>-1


text:
Q: Menu feito no Bootstrap Como centralizar um menu feito no Pingendo Bootstrap?

    <meta charset="utf-8">
    <title>Boletim Online</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="">
    <meta name="author" content="">
    <link href="http://netdna.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css" rel="stylesheet">

          Toggle navigation

          Administrador

              Turmas

A: Ajusta no css como descrito aqui que acredito resolver o seu problema:

        Turmas

.navbar{
    padding : 0 25px;
}

.nav-center{
    position: relative;
    left: 30%;
}

http://jsfiddle.net/kwvLm6tg/2/
Importante que seja com percentual para manter a responsividade.


text:
Q: duplicate model instance with all related objects EDIT:
it works fine this way

I'm trying to clone a model instance with all the related objects.
I have two models :
class VersionContrat(models.Model):

    nom_version = models.CharField(max_length=25, blank=True, null=True)
    version = models.IntegerField()

and :
class Vacation (models.Model):

    poste_travail = models.CharField(max_length=50, default='')
    version_contrat = models.ForeignKey(VersionContrat, on_delete=models.CASCADE, default=9)

    date_debut = models.DateField(blank=True, null=True)
    date_fin = models.DateField(blank=True, null=True)

I tried this method in VersionContrat to copy a VersionContrat object and all the Vacation objects related with the foreign key:
def duplicate(self):
    vacations = Vacation.objects.filter(version_contrat=self)
    self.pk = None
    self.version = int(self.version)+1
    self.save()

    for vacation in vacations:
        vacation.pk = None
        vacation.version_contrat = self
        vacation.save()

    return print('clone to {}'.format(self))

But it doesn't work and I can't find out why, anyone has an idea why ?


text:
Q: Why can't I delete this file? When I run brew doctor, I get this warning:
Warning: Unbrewed dylibs were found in /usr/local/lib.
If you didn't put them there on purpose they could cause problems when
building Homebrew formulae, and may need to be deleted.

Unexpected dylibs:
    /usr/local/lib/libusb-0.1.4.4.4.dylib
    /usr/local/lib/libusbpp-0.1.4.4.4.dylib

According to this question and answer, I want to delete these files.
But when I remove the second one with rm, it seems to be recreated automatically:
$ rm /usr/local/lib/libusbpp-0.1.4.4.4.dylib
override rwxr-xr-x  root/wheel for /usr/local/lib/libusbpp-0.1.4.4.4.dylib?
$ ls /usr/local/lib/libusbpp-0.1.4.4.4.dylib
/usr/local/lib/libusbpp-0.1.4.4.4.dylib

I totally don't understand what's going on. Why can't I delete this file?

A: rm is telling you that you don't have write access to the file you told it to delete, and is asking for confirmation. Type y and then press return when it asks you if you want to override. If you type n or nothing at all, it won't delete the file.

Technical(ish) details:
rwxr-xr-x root/wheel is a representation of the permissions and ownership of the file.
The first part tells you the permissions of the file; the second that the file is owned by the user root and the group wheel.
See man chown for more information on file ownership, and man chmod for more information on file permissions. Wikipedia might have easier-to-understand information on chown and chmod.

A: You need to use sudo...
sudo rm -rf /usr/local/lib/libusbpp-0.1.4.4.4.dylib

that should do it

A: The answer above is accurate for the contents of /usr/local/. MacOS has something called System Integrity Protection, which restricts the actions of superuser. Attempts to alter the contents of /usr/bin and other folders may be rejected with Operation not permitted. This is described in which folders are affected by System Integrity Protection.


text:
Q: Can you mix spring's security and rest api together? I'm new to spring boot and I want to create a rest api for my back end, but I also like spring security's authentication system and I want t use it in my application without having to make my own restful api for that part of the code.
Is this doable and will it be better to do it this way rather than make everything as a rest api?

A: yes it's very doable. Steps:

*

*you have to configure spring security session management to stateless
@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable().exceptionHandling().authenticationEntryPoint(authenticationEntryPoint()).and()
            .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and().authorizeRequests()

}

*configure an authentication entry point to return HTTP status instead of a view
@Bean
public AuthenticationEntryPoint authenticationEntryPoint() {
    return new AuthenticationEntryPoint() {
        @Override
        public void commence(HttpServletRequest resq, HttpServletResponse resp, AuthenticationException arg2)
            throws IOException, ServletException {
            resp.sendError(HttpStatus.UNAUTHORIZED.value(), "Secured URL Hit");
        }
    };
}

*Proceed with the usual authentication provider


text:
Q: Orient multiple traverse I have this graph:

And I'm trying to write a query with the "SQL Syntax" of OrientDB v3.0 that start from a Client and follow the read path (the X means: and don't have Have relation to the Client).
I can get the Segments, but I don't find how to walk to the Contact.
The docs have many examples but only walking one path.
I have tried without success these queries:
SELECT FROM  (TRAVERSE out("Access").out("Contain") FROM (SELECT @rid FROM Client where myId = 30543) MAXDEPTH 1)

SELECT FROM (
    TRAVERSE out("Contain") FROM
        (TRAVERSE out("Access") FROM (SELECT @rid FROM Client where myId = 30543) MAXDEPTH 1)
    MAXDEPTH 1
)

SELECT out('Access').out("Contain") FROM Client WHERE myId = 30543

Do you have any info to accomplish this traverse?
I'm using the Node.js API:
const pool = await orient.getPool();
const session = await pool.acquire();

logger.info('Running query...');
session.command(`SELECT out('Access').out("Contain") FROM Client WHERE myId = 30543`)
  .on('data', (data) => {
    if (data.out_Contain && data.out_Contain.delegate) {
      logger.info('Segment %s contains %o Contact', data['@rid'].toString(), data.out_Contain.delegate.size);
    } else if (data['@rid']) {
      logger.info('Segment %s contains %o Contact', data['@rid'].toString(), data);
    } else {
      logger.info('Data %o', data);
    }
  })
  .on('error', (err) => {
    logger.error(err);
  })
  .on('end', () => {
    console.timeEnd('query');
    logger.info('End of the stream');
    process.emit('SIGINT');
  });

logger.debug('Registering SIGINT');
process.once('SIGINT', async () => {
  await session.close();
  await pool.close();
  await orient.stop();
});

A: Please try using this code:
"select out_{edgeclass}.in from (select expand(out_{edgeclass}.in) from {Vetex} where {condition})"

A: The match is better for this kind of tasks.
With SELECT:

In the first version, the query is more readable, but it does not use indexes, so it is less optimal in terms of execution time. The second and third use indexes if they exist, (on Person.name or City.name, both in the sub-query), but they're harder to read. Which index they use depends only on the way you write the query.

But match:

the query executor optimizes the query for you, choosing indexes where they exist. Moreover, the query becomes more readable, especially in complex cases, such as multiple nested SELECT queries.

Here the right query:
SELECT EXPAND(contatti)
    FROM (
      match { class: Client, as: user, where : ( myId = 30543)}
        .out('Access')
        .out('Contain'){ class:Contact, as:contatti, where: (gender= 'M')},
      NOT {as:user} -Have-> {as:contatti}
      RETURN DISTINCT contatti LIMIT 1000
    )


text:
Q: javascript to recognize that it is being clicked again, to reverse changes it made when initially clicked I have this bit of JavaScript that is fired when I press a button on the page. When pressed, it fires an event that runs this code and it turns styled text into html source code:
showHTMLmarkupCode: function(e) {
    var text = document.createTextNode($('.storyBookText').html());
    var html = $('.storyBookText').html();
    $('.storyBookText').empty();
    $('.storyBookText').append(text);
}

It works the first time you press the button.
So if I have text like this:
This is bold
When I press the button, it will show this:
This is bold

Which is what I want.
But if I press it again, to go back to the styled text, it does this:
<span style="font-weight: bold;">This is bold</span>

Is there a way to code it so that when it's pressed a second time, it reverts back to the styled text instead of the ugly code?
Thanks!
Modified function:
showSourceCode: function(e) {
    console.log('show source code clicked');
    console.log("isHTML: ", isHTML);
    if (isHTML) {
        $('.storyBookText').textContent = $('.storyBookText').innerHTML;
    } else {
        $('.storyBookText').innerHTML = $('.storyBookText').textContent;
    }
    isHTML = !isHTML;
}

A: You can accomplish the text to HTML conversion by setting the .innerHTML property of the parent to its .textContent:

const $button = document.getElementById('button');
const $element = document.querySelector('.storyBookText');
let isHTML = true;

$button.addEventListener('click', () => {
  if (isHTML) {
    $element.textContent = $element.innerHTML;
  } else {
    $element.innerHTML = $element.textContent;
  }
  isHTML = !isHTML;
});

  This is bold

<button id="button">Change</button>


text:
Q: PropertyGrid doesn't reflect attributes when object is received from referenced webservice I have a custom class with properties in let's say Project1. These properties are accompanied by some standard attributes like CategoryAttribute and DescriptionAttribute. I want the values of these attributes to be shown in a PropertyGrid.
When I create the custom object and attach it to the PropertyGrid1.SelectedObject all the attributes' values are shown like expected.
Now when I move the custom class out of Project1 and place it into an ASP.NET webservice and use a service reference in Project1 all my attributes disappear and the PropertyGrid shows all the properties under the Misc category.
How can make the attributes visible and useable again in the PropertyGrid when using a webservice?

A: When you add a service reference you will generate new classes that match the same serialization structure. Those new classed lack the attributes the original ones had.
What you can do:

*

*Move your classes in a separate project that is referenced by both the server and the client code

*When you generate the service reference check the option "Reuse types from referenced assemblies" or something similar named.
That way you will actually use the same types in both places.


text:
Q: Metallb LoadBalancer is stuck on pending I am trying to set up a bare metal Kubernetes server including the metallb LoadBalancer. Therefore, I followed the instructions published on the website of the kind project https://kind.sigs.k8s.io/docs/user/loadbalancer/. To test my installation I tried to deploy the default nginx web-server and reach it via the browser. Unfortunately the created service of type LoadBalancer is stuck on EXTERNAL IP <Pending>. I will attach as much information as possible. I hope someone could help me with this issue. If you need more info please let me know.
This is what I did:

*

*Installation of metallb LoadBalancer according to https://kind.sigs.k8s.io/docs/user/loadbalancer/

*Created a nginx deployment via kubectl create deployment nginx --image nginx

*Created a corresponding service kubectl expose deployment/nginx --type="LoadBalancer" --port 8080
Outputs
Version and Nodes
$ kubectl version --short
Client Version: v1.20.2
Server Version: v1.20.2

$ kubectl get nodes -o wide
NAME      STATUS   ROLES                  AGE     VERSION   INTERNAL-IP     EXTERNAL-IP   OS-IMAGE       KERNEL-VERSION     CONTAINER-RUNTIME
gemini    Ready    control-plane,master   3d      v1.20.2   192.168.2.203   <none>        Ubuntu 20.10   5.8.0-1013-raspi   docker://19.3.13
phoenix   Ready    <none>                 2d23h   v1.20.2   192.168.2.129   <none>        Ubuntu 20.10   5.8.0-1013-raspi   docker://19.3.13
taurus    Ready    <none>                 2d23h   v1.20.2   192.168.2.201   <none>        Ubuntu 20.10   5.8.0-1013-raspi   docker://19.3.13
virgo     Ready    <none>                 2d23h   v1.20.2   192.168.2.202   <none>        Ubuntu 20.10   5.8.0-1013-raspi   docker://19.3.13

All namespaces
$ kubectl get all --all-namespaces

NAMESPACE              NAME                                             READY   STATUS             RESTARTS   AGE
default                pod/nginx-6799fc88d8-62cjd                       1/1     Running            0          59m
kube-system            pod/calico-kube-controllers-86bddfcff-ccrhg      1/1     Running            5          3d
kube-system            pod/calico-node-djt5s                            0/1     CrashLoopBackOff   1007       3d
kube-system            pod/calico-node-jddnl                            1/1     Running            3          3d
kube-system            pod/calico-node-nxwlw                            1/1     Running            5          3d
kube-system            pod/calico-node-zrxzl                            1/1     Running            3          3d
kube-system            pod/coredns-74ff55c5b-kb2nm                      1/1     Running            5          3d1h
kube-system            pod/coredns-74ff55c5b-wsgs5                      1/1     Running            5          3d1h
kube-system            pod/etcd-gemini                                  1/1     Running            6          3d1h
kube-system            pod/kube-apiserver-gemini                        1/1     Running            6          3d1h
kube-system            pod/kube-controller-manager-gemini               1/1     Running            6          3d1h
kube-system            pod/kube-proxy-7fcjz                             1/1     Running            6          3d1h
kube-system            pod/kube-proxy-84rr7                             1/1     Running            3          3d
kube-system            pod/kube-proxy-lc88w                             1/1     Running            3          3d
kube-system            pod/kube-proxy-v4qd9                             1/1     Running            3          3d
kube-system            pod/kube-scheduler-gemini                        1/1     Running            6          3d1h
kubernetes-dashboard   pod/dashboard-metrics-scraper-79c5968bdc-mlb4s   1/1     Running            5          3d
kubernetes-dashboard   pod/kubernetes-dashboard-7448ffc97b-nq5c9        1/1     Running            5          3d
metallb-system         pod/controller-5c797bc4f8-2zx7l                  1/1     Running            0          101m
metallb-system         pod/speaker-5kxc9                                1/1     Running            0          101m
metallb-system         pod/speaker-b6lbh                                1/1     Running            0          101m
metallb-system         pod/speaker-c8sr7                                1/1     Running            0          101m
metallb-system         pod/speaker-fwbgt                                1/1     Running            1          101m

NAMESPACE              NAME                                TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)                  AGE
default                service/kubernetes                  ClusterIP      10.96.0.1        <none>        443/TCP                  23h
default                service/nginx                       LoadBalancer   10.110.25.14     <pending>     8080:30444/TCP           24m
kube-system            service/calico-etcd                 ClusterIP      10.96.232.136    <none>        6666/TCP                 3d
kube-system            service/calico-typha                ClusterIP      10.109.108.233   <none>        5473/TCP                 3d
kube-system            service/kube-dns                    ClusterIP      10.96.0.10       <none>        53/UDP,53/TCP,9153/TCP   3d1h
kubernetes-dashboard   service/dashboard-metrics-scraper   ClusterIP      10.110.70.52     <none>        8000/TCP                 3d
kubernetes-dashboard   service/kubernetes-dashboard        NodePort       10.106.194.127   <none>        443:31741/TCP            3d

NAMESPACE        NAME                         DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR            AGE
kube-system      daemonset.apps/calico-node   4         4         3       4            3           kubernetes.io/os=linux   3d
kube-system      daemonset.apps/kube-proxy    4         4         4       4            4           kubernetes.io/os=linux   3d1h
metallb-system   daemonset.apps/speaker       4         4         4       4            4           kubernetes.io/os=linux   101m

NAMESPACE              NAME                                        READY   UP-TO-DATE   AVAILABLE   AGE
default                deployment.apps/nginx                       1/1     1            1           59m
kube-system            deployment.apps/calico-kube-controllers     1/1     1            1           3d
kube-system            deployment.apps/coredns                     2/2     2            2           3d1h
kubernetes-dashboard   deployment.apps/dashboard-metrics-scraper   1/1     1            1           3d
kubernetes-dashboard   deployment.apps/kubernetes-dashboard        1/1     1            1           3d
metallb-system         deployment.apps/controller                  1/1     1            1           101m

NAMESPACE              NAME                                                   DESIRED   CURRENT   READY   AGE
default                replicaset.apps/nginx-6799fc88d8                       1         1         1       59m
kube-system            replicaset.apps/calico-kube-controllers-56b44cd6d5     0         0         0       3d
kube-system            replicaset.apps/calico-kube-controllers-86bddfcff      1         1         1       3d
kube-system            replicaset.apps/coredns-74ff55c5b                      2         2         2       3d1h
kubernetes-dashboard   replicaset.apps/dashboard-metrics-scraper-79c5968bdc   1         1         1       3d
kubernetes-dashboard   replicaset.apps/kubernetes-dashboard-7448ffc97b        1         1         1       3d
metallb-system         replicaset.apps/controller-5c797bc4f8                  1         1         1       101m

Namespace default:
$ kubectl get all
NAME                         READY   STATUS    RESTARTS   AGE
pod/nginx-6799fc88d8-62cjd   1/1     Running   0          29m

NAME                 TYPE           CLUSTER-IP       EXTERNAL-IP   PORT(S)          AGE
service/kubernetes   ClusterIP      10.96.0.1        <none>        443/TCP          23h
service/nginx        LoadBalancer   10.110.25.14     <pending>     8080:30444/TCP   29m

NAME                    READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/nginx   1/1     1            1           29m

NAME                               DESIRED   CURRENT   READY   AGE
replicaset.apps/nginx-6799fc88d8   1         1         1       29m

Namespace metallb-system:
$ kubectl get all -n metallb-system
NAME                              READY   STATUS    RESTARTS   AGE
pod/controller-5c797bc4f8-2zx7l   1/1     Running   0          73m
pod/speaker-5kxc9                 1/1     Running   0          73m
pod/speaker-b6lbh                 1/1     Running   0          73m
pod/speaker-c8sr7                 1/1     Running   0          73m
pod/speaker-fwbgt                 1/1     Running   1          73m

NAME                     DESIRED   CURRENT   READY   UP-TO-DATE   AVAILABLE   NODE SELECTOR            AGE
daemonset.apps/speaker   4         4         4       4            4           kubernetes.io/os=linux   73m

NAME                         READY   UP-TO-DATE   AVAILABLE   AGE
deployment.apps/controller   1/1     1            1           73m

NAME                                    DESIRED   CURRENT   READY   AGE
replicaset.apps/controller-5c797bc4f8   1         1         1       73m

Config map
$ kubectl describe configmap config -n metallb-system
Name:         config
Namespace:    metallb-system
Labels:       <none>
Annotations:  <none>

Data
====
config:
----
address-pools:
- name: default
  protocol: layer2
  addresses:
  - 192.168.2.210-192.168.2.250

Events:  <none>

Kube-proxy
$ kubectl describe configmap -n kube-system kube-proxy

Name:         kube-proxy
Namespace:    kube-system
Labels:       app=kube-proxy
Annotations:  kubeadm.kubernetes.io/component-config.hash: sha256:038b6c93b0ae1da89eb9c0c589c8e3439e9c91b849975435c29f905041b9b9fc

Data
====
config.conf:
----
apiVersion: kubeproxy.config.k8s.io/v1alpha1
bindAddress: 0.0.0.0
bindAddressHardFail: false
clientConnection:
  acceptContentTypes: ""
  burst: 0
  contentType: ""
  kubeconfig: /var/lib/kube-proxy/kubeconfig.conf
  qps: 0
clusterCIDR: 192.168.0.0/16
configSyncPeriod: 0s
conntrack:
  maxPerCore: null
  min: null
  tcpCloseWaitTimeout: null
  tcpEstablishedTimeout: null
detectLocalMode: ""
enableProfiling: false
healthzBindAddress: ""
hostnameOverride: ""
iptables:
  masqueradeAll: false
  masqueradeBit: null
  minSyncPeriod: 0s
  syncPeriod: 0s
ipvs:
  excludeCIDRs: null
  minSyncPeriod: 0s
  scheduler: ""
  strictARP: true
  syncPeriod: 0s
  tcpFinTimeout: 0s
  tcpTimeout: 0s
  udpTimeout: 0s
kind: KubeProxyConfiguration
metricsBindAddress: ""
mode: ""
nodePortAddresses: null
oomScoreAdj: null
portRange: ""
showHiddenMetricsForVersion: ""
udpIdleTimeout: 0s
winkernel:
  enableDSR: false
  networkName: ""
  sourceVip: ""
kubeconfig.conf:
----
apiVersion: v1
kind: Config
clusters:
- cluster:
    certificate-authority: /var/run/secrets/kubernetes.io/serviceaccount/ca.crt
    server: https://192.168.2.203:6443
  name: default
contexts:
- context:
    cluster: default
    namespace: default
    user: default
  name: default
current-context: default
users:
- name: default
  user:
    tokenFile: /var/run/secrets/kubernetes.io/serviceaccount/token
Events:  <none>

Metallb Controller and one of the Speaker Pods
$ kubectl describe pods -n metallb-system
Name:         controller-5c797bc4f8-2zx7l
Namespace:    metallb-system
Priority:     0
Node:         virgo/192.168.2.202
Start Time:   Tue, 09 Feb 2021 14:10:16 +0000
Labels:       app=metallb
              component=controller
              pod-template-hash=5c797bc4f8
Annotations:  cni.projectcalico.org/podIP: 192.168.9.246/32
              cni.projectcalico.org/podIPs: 192.168.9.246/32
              prometheus.io/port: 7472
              prometheus.io/scrape: true
Status:       Running
IP:           192.168.9.246
IPs:
  IP:           192.168.9.246
Controlled By:  ReplicaSet/controller-5c797bc4f8
Containers:
  controller:
    Container ID:  docker://b10ee06c88facfc97fcd246bcd214c746deea60073dc8928f478c89ca3a4feb9
    Image:         quay.io/metallb/controller:main
    Image ID:      docker-pullable://quay.io/metallb/controller@sha256:1e1a1bd75cebcecfe84db28c9a8605caeac3e30e57905185822c79fc00e5dcaf
    Port:          7472/TCP
    Host Port:     0/TCP
    Args:
      --port=7472
      --config=config
    State:          Running
      Started:      Tue, 09 Feb 2021 14:10:43 +0000
    Ready:          True
    Restart Count:  0
    Limits:
      cpu:     100m
      memory:  100Mi
    Requests:
      cpu:        100m
      memory:     100Mi
    Environment:  <none>
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from controller-token-ghmtk (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  controller-token-ghmtk:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  controller-token-ghmtk
    Optional:    false
QoS Class:       Guaranteed
Node-Selectors:  kubernetes.io/os=linux
Tolerations:     node.kubernetes.io/not-ready:NoExecute op=Exists for 300s
                 node.kubernetes.io/unreachable:NoExecute op=Exists for 300s
Events:
  Type    Reason     Age   From               Message
  ----    ------     ----  ----               -------
  Normal  Scheduled  89m   default-scheduler  Successfully assigned metallb-system/controller-5c797bc4f8-2zx7l to virgo
  Normal  Pulling    89m   kubelet            Pulling image "quay.io/metallb/controller:main"
  Normal  Pulled     89m   kubelet            Successfully pulled image "quay.io/metallb/controller:main" in 23.412886883s
  Normal  Created    89m   kubelet            Created container controller
  Normal  Started    89m   kubelet            Started container controller

Name:         speaker-5kxc9
Namespace:    metallb-system
Priority:     0
Node:         taurus/192.168.2.201
Start Time:   Tue, 09 Feb 2021 14:10:16 +0000
Labels:       app=metallb
              component=speaker
              controller-revision-hash=7548d88c64
              pod-template-generation=1
Annotations:  prometheus.io/port: 7472
              prometheus.io/scrape: true
Status:       Running
IP:           192.168.2.201
IPs:
  IP:           192.168.2.201
Controlled By:  DaemonSet/speaker
Containers:
  speaker:
    Container ID:  docker://e5ff811c47191f67c7089ce2464abff4fb8e4d3084f8053eb591c9d21e9a2276
    Image:         quay.io/metallb/speaker:main
    Image ID:      docker-pullable://quay.io/metallb/speaker@sha256:90a8cbdd543870e7db841a49743f3d8cd72b7074b5299086e09c5c1d92331eb4
    Port:          7472/TCP
    Host Port:     7472/TCP
    Args:
      --port=7472
      --config=config
    State:          Running
      Started:      Tue, 09 Feb 2021 14:10:33 +0000
    Ready:          True
    Restart Count:  0
    Limits:
      cpu:     100m
      memory:  100Mi
    Requests:
      cpu:     100m
      memory:  100Mi
    Environment:
      METALLB_NODE_NAME:       (v1:spec.nodeName)
      METALLB_HOST:            (v1:status.hostIP)
      METALLB_ML_BIND_ADDR:    (v1:status.podIP)
      METALLB_ML_LABELS:      app=metallb,component=speaker
      METALLB_ML_NAMESPACE:   metallb-system (v1:metadata.namespace)
      METALLB_ML_SECRET_KEY:  <set to the key 'secretkey' in secret 'memberlist'>  Optional: false
    Mounts:
      /var/run/secrets/kubernetes.io/serviceaccount from speaker-token-xfz9p (ro)
Conditions:
  Type              Status
  Initialized       True
  Ready             True
  ContainersReady   True
  PodScheduled      True
Volumes:
  speaker-token-xfz9p:
    Type:        Secret (a volume populated by a Secret)
    SecretName:  speaker-token-xfz9p
    Optional:    false
QoS Class:       Guaranteed
Node-Selectors:  kubernetes.io/os=linux
Tolerations:     node-role.kubernetes.io/master:NoSchedule
                 node.kubernetes.io/disk-pressure:NoSchedule op=Exists
                 node.kubernetes.io/memory-pressure:NoSchedule op=Exists
                 node.kubernetes.io/network-unavailable:NoSchedule op=Exists
                 node.kubernetes.io/not-ready:NoExecute op=Exists
                 node.kubernetes.io/pid-pressure:NoSchedule op=Exists
                 node.kubernetes.io/unreachable:NoExecute op=Exists
                 node.kubernetes.io/unschedulable:NoSchedule op=Exists
Events:
  Type     Reason            Age                   From               Message
  ----     ------            ----                  ----               -------
  Normal   Scheduled         89m                   default-scheduler  Successfully assigned metallb-system/speaker-5kxc9 to taurus
  Normal   Pulling           89m                   kubelet            Pulling image "quay.io/metallb/speaker:main"
  Normal   Pulled            89m                   kubelet            Successfully pulled image "quay.io/metallb/speaker:main" in 14.647284366s
  Normal   Created           89m                   kubelet            Created container speaker
  Normal   Started           89m                   kubelet            Started container speaker
  Warning  DNSConfigForming  4m14s (x71 over 89m)  kubelet            Nameserver limits were exceeded, some nameservers have been omitted, the applied nameserver line is: 8.8.8.8 1.1.1.1 192.168.2.1

A: The problem concern about MetalLB controller. I have face this issue as well for my action reintall MetalLB again. refer: https://github.com/metallb/metallb/issues/673
Remove
kubectl delete -f https://raw.githubusercontent.com/metallb/metallb/v0.9.5/manifests/metallb.yaml
kubectl delete -f metallb-configMap.yaml

Install
kubectl apply -f https://raw.githubusercontent.com/metallb/metallb/v0.9.5/manifests/metallb.yaml
kubectl apply -f metallb-configMap.yaml

Don't worry about existing service that was assigned IP. As of you deleting the MetalLB controller the service can serve and still work as normal.

A: There seems to be an issue with the metallb config map you've created. In the address pools section you've mentioned the allocated IP range as  192.168.2.210 - 192.168.250, which is wrong because the second one is not a valid IP (192.168.250 is not a valid IP address).
Please edit the configmap using the following command,
$ kubectl edit configmap config -n metallb-system

and correct the range to 192.168.2.210 - 192.168.2.250.
Then delete the service and create it again. If it still fails post to this thread again. Hope this helps :)

A: I followed Kind documentation too, of using master version of metallb. My cluster was 1.21.1 and made LB works by using a specific version of metallb, i.e. v0.10.


text:
Q: Background CSS Image I have a fairly complex webpage and am looking to have a image in the background that is seen through all out all the div layers. Please take a look at http://va.in-design.com for the code. No matter what I try, I am able to only get some of the menu to show. Some settings make it show when the menu on the page is accessed (hovered over). Can someone give me a pointer on the best way to do this. Also, is there anything available out there that would allow that image to be 100% at load and then fade down to 15%?

A: There is CSS opacity and CSS transitions, but for this I am going to use jquery.

*

*Adjust your html{} selector to show the background like this
html {
height: 100%;
margin: 0;
width: 100%;
background-image: url(/images/logos/v-alexander-logo1-04-transpart-web.gif)
no-repeat center center fixed;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
}

*I am not sure what you mean the menu doesn't show I saw the menu over the background image for sure. If you are still having this issue I would recommend using the z-index as one of your css rules for your menu ul#sdt_menu or wrapping that in a div id also and adjusting that parent div's z-index.

*the jquery to do the opacity fade would be this http://jsfiddle.net/naeluh/XYB3u/
add this div to all the pages you want the background.

add this css rule to your style.css file and take away your html{}
    #background{
    height: 100%;
    position:absolute;
    top:0;
    left:0;
    width: 100%;
    background-image: url(http://va.in-design.com/images/logos/v-alexander-logo1-04-transpart-web.gif);
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
    z-index:-1;
    }

add this in the head of the pages you want it to fade out


text:
Q: How to add a row below the column header and move the existing row downwards using Word VBA Macros? Whenever I update the document, I need to add a row to the top of the table, just below the headers, and then move the old row to the next level. The table is usually present on the last page of the Word document. Please find attached the screenshot for the expected and actual behaviors.
Below is the code I have written to achieve:

*

*Go to the last page and find the table

*Add a row (This adds above the column header)

Expectations:

*

*Add the row immediately after the column header and move the existing row to the next level

*Add the date to the second column.
Click for the screenshot
My code:
Sub Macro1()
Selection.EndKey Unit:=wdStory
Dim theTable As Table
Dim theNewRow As Row
For Each theTable In ActiveDocument.Tables
    Set theNewRow = theTable.Rows.Add(theTable.Rows.First)
    'Other row formatting
Next theTable

End Sub
I am learning VBA and any help would be of great use. Thanks for your time.
screenshot2

A: For example:
With ActiveDocument
  With .Tables(.Tables.Count)
    .Split (2)
    With .Range.Characters.Last.Next
      .FormattedText = .Next.Rows(1).Range.FormattedText
    End With
    .Rows(2).Range.Delete
  End With
End With

It's not clear, though, what you mean by "move the existing row to the next level".

A: It needs next.
Sub test()
    Selection.EndKey Unit:=wdStory
    Dim theTable As Table
    Dim theNewRow As Row
    For Each theTable In ActiveDocument.Tables
        Set theNewRow = theTable.Rows.Add(theTable.Rows.First.Next) '<~~ add next

        'Other row formatting
    Next theTable
End Sub

A: As Intellisense shows you the input parameter for Table.Rows.Add is [BeforeRow]. This is an optional parameter so if it is omitted the new row is added after the last row of the table.
As you want the row to come after the first row and before the second you need to pass the second row as the parameter, e.g.
With ActiveDocument.Tables(ActiveDocument.Tables.Count)
   With .Rows.Add(.Rows(2))
      'add date
      .Cells(2).Range.Text = Format(Date, "MMMM d, yyyy")
      'add any additional row formatting
   End With
End With


text:
Q: How to map this tricky entity/relationship model in Java? I have little bit confusing many to many relationship between 3 entities. And i want to know how can be my object model look like. I have three Entities, A,B,C and A<->B (M:N) and associate table between both, A and B, is linked with another associate table which make another 1:n relationship with third entity. I have never seen such relationship which make 1:n relationship with another associate table. For further information please have look on following diagram.

Uploaded Image link
If i talk about object model then i will say "INSTANCE_A" has many "INSTANCE_B" instance and vice versa but i do not know how can i summarize relationship  for "INSTANCE_C".
Please also let me know whether definition of such relationship between all three entities is right ? i mean is there any problem in relationship design.
Thanks in advance
EDIT: All arrows denote (1:n or m:1) relationship

A: The data model is correct, but the object model for these tables can be kind of trucky. I'd do something like this:

*

*One class for TBL_A, with a List attribute of TBL_B

*One class for TBL_B, with a List attribute of TBL_A

*One class for TBL_C_TBL_A_B, with and an attribute for TBL_B, TBL_A and TBL_C

Mapping that in an ORM framework can get funky.

A: This shall bring you into the right direction. Try to design a UML diagram, or ER should be ok too. Here is some paper with a Model and the corresponding Java-Code for this model http://www.csd.uoc.gr/~hy252/references/UML_for_Java_Programmers-Book.pdf. (Go to -> Class diagrams chapter).


text:
Q: Node Project & Practice I am learning Node JS. It had almost learnt 70%. I am very interested in Backend Development but I'm not interested in Frontend development. My question is how do I practice my Node Skills. I only know HTML, CSS in Frontend. How can I make projects in Node JS without knowing Frontend? Or do I need to learn frontend frameworks such as React too to make projects.

A: You can build an API and use postman to make requests. Start with something simple and keep improving by refactoring your code.

A: You can work on the API creation part but in my opinion, you must learn one frontend framework it will not only increase your skill sets but also help you to coordinate with frontend easily and take more advantage of it than the projects you will build will be more useful and advanced as well.

A: You could also focus on implementing some algorithms and data structures starting of with simple ones such as LinkedLists, ArrayLists, sorting algorithms and then move on to (binary) trees and graphs.
These will be required for any programming language to solve (complex) problems and there are many books and internet resources for this. Just search for algorithms and data structures and you'll get plenty. You don't need more than a console application with some simple console.log() statements to implement algorithms - no need for fancy UI.
Last but not least, you should certainly have a look at TypeScript if you want to develop more complex backend applications.
If you really want to do Web Development though it is certainly helpful to have a basic understanding of frontend development or know the basics of common frameworks such as React, Vue, Angular or Svelte.
As others have mentioned for API development you could also just use Postman to send requests.


text:
Q: How can I send a Base64 Image as a body in POST I'm looking  to make a post request with a base64 image. When I make the request, I get an error called "ERROR_ZERO_CAPTCHA_FILESIZE" from the api. When I looked up what it means it says:
 Image size is less than 100 bytes. Check the image file, the post returns this error message:
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import java.io.*;
import java.net.*;
import java.util.Base64;

public class Main {

    public static void main(String args[]) throws IOException {
        File originalFile = new File("sec_token.php.png");
        String encodedBase64 = null;
        try {
            FileInputStream fileInputStreamReader = new FileInputStream(originalFile);
            byte[] bytes = new byte[(int)originalFile.length()];
            fileInputStreamReader.read(bytes);
            encodedBase64 = new String(Base64.getEncoder().encodeToString(bytes));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println(encodedBase64);
        HttpURLConnection con = (HttpURLConnection) new URL("http://2captcha.com/in.php?key=61f5d7a6cccc2db4e7c503a59f4f7e&method=base64&imginstructions="+encodedBase64).openConnection();

        String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0";
        System.out.println("User agent: " + USER_AGENT);
        //add request header
        con.setRequestMethod("POST");
        con.setRequestProperty("Host", "2captcha.com");

        con.setDoOutput(true);
        DataOutputStream wr = new DataOutputStream(con.getOutputStream());
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
        String inputLine;
        StringBuffer response = new StringBuffer();

        while((inputLine = in.readLine()) != null){
            response.append(inputLine);
        }
        String res = response.toString();
        System.out.println(res);
    }
}

A: I've looked at the API docs and it looks like you need to use application/x-www-form-urlencoded or multipart/form-data for the POST body.
    File originalFile = new File("sec_token.php.png");
    String encodedBase64 = null;
    try {
        FileInputStream fileInputStreamReader = new FileInputStream(originalFile);
        byte[] bytes = new byte[(int)originalFile.length()];
        fileInputStreamReader.read(bytes);
        encodedBase64 = new String(Base64.getEncoder().encodeToString(bytes));
    } catch (IOException e) {
        e.printStackTrace();
    }

    System.out.println(encodedBase64);
    HttpURLConnection con = (HttpURLConnection) new URL("http://2captcha.com/in.php").openConnection();

    String USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0";
    System.out.println("User agent: " + USER_AGENT);
    //add request header
    con.setRequestMethod("POST");
    con.setRequestProperty("Host", "2captcha.com");

    String data = "method=base64&body=" + encodedBase64 + "&key=[API_KEY]";
    con.setDoOutput(true);
    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeChars(data);
    wr.flush();

    BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();

    while((inputLine = in.readLine()) != null){
        response.append(inputLine);
    }

    String res = response.toString();
    System.out.println(res);


text:
Q: 'from A to B to C' or 'from A to B and from B to C'? How do I describe such a trend? If I want to describe a trend, for example, a gas has a density of 1, its liquid form has a density of 2, and its solid form's density is 3, which expression will be better

the density increases from the gas form to the liquid form to the solid form

or

the density increases from the gas form to the liquid form and from the liquid form to the solid form

By the way, are there any better ways to describe this trend? For example, is

the density is the lowest of the gas form and the highest of the solid form

correct?
Does it look better or worse than the two above? How do native English speakers describe such a trend?

A: The technical term for gas, liquid and solid is state. You can eliminate a lot of the repetition in your sentences by describing what happens as the state changes.

The density increases as the state changes from gas to liquid to solid.

A: The second one is correct. The 3rd one is also fine, but it doesn't show a trend.
You can also say "The density increases as the state changes from Gas to Solid" or "The density increases as the element moves from its gas state to its solid state"
You don't need to mention the liquid state as it is understood that the element changes into its liquid state before it changes into its solid state.
Hope it helps.


text:
Q: Deploying Node.js app to Heroku. Error NPM_CONFIG_LOGLEVEL=error I am deploying my node.js application on heroku but when i run my app it shows me Application error and when i check my logs file i found NPM_CONFIG_LOGLEVEL=error
My package.json file is:
{
  "name": "wework-1",
  "version": "1.0.0",
  "description": "We Work Meteor, a job board and developer directory for Meteor specific work https://www.weworkmeteor.com",
  "main": "",
  "engines": {
    "node": "= 4.5.0",
    "npm": "= 3.9.6"
  },
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "lint": "eslint .",
    "pretest": "npm run lint --silent"
  },
  "repository": {
    "type": "git",
    "url": "git+https://github.com/rohitchaudhary701/wework-1.git"
  }
}

My logs file is:
-----> Node.js app detected
-----> Creating runtime environment

       NPM_CONFIG_LOGLEVEL=error
       NPM_CONFIG_PRODUCTION=true
       NODE_VERBOSE=false
       NODE_ENV=production
       NODE_MODULES_CACHE=true
-----> Installing binaries
       engines.node (package.json):  = 4.5.0
       engines.npm (package.json):   = 3.9.6

       Resolving node version = 4.5.0 via semver.io...
       Downloading and installing node 4.5.0...
       Resolving npm version = 3.9.6 via semver.io...
       Downloading and installing npm 3.9.6 (replacing version 2.15.9)...
-----> Restoring cache
       Loading 2 from cacheDirectories (default):
       - node_modules
       - bower_components (not cached - skipping)
-----> Building dependencies
       Installing node modules (package.json)
-----> Caching build
       Clearing previous node cache
       Saving 2 cacheDirectories (default):
       - node_modules
       - bower_components (nothing to cache)
-----> Build succeeded!
 !     This app may not specify any way to start a node process
       https://devcenter.heroku.com/articles/nodejs-support#default-web-process-type
-----> Discovering process types
       Procfile declares types     -> (none)
       Default types for buildpack -> web
-----> Compressing...
       Done: 12.7M
-----> Launching...
       Released v6
       https://whispering-cliffs-66861.herokuapp.com/ deployed to Heroku

App url is https://whispering-cliffs-66861.herokuapp.com/

A: From your logs:

This app may not specify any way to start a node process

You probably need to do two things:

*

*add start script in package.json

*make sure you listen on the port in process.env.PORT
Take a look at this example:

*

*https://github.com/rsp/node-live-color
See package.json and the start script:
  "scripts": {
    "start": "node server.js"
  },

See:

*

*https://github.com/rsp/node-live-color/blob/master/package.json#L6
And see the port number initialization:
const port = process.env.PORT || 3338;
// ...
server.listen(port, () => {
  console.log(`Listening on http://localhost:${port}/`);
});

See:

*

*https://github.com/rsp/node-live-color/blob/master/server.js#L13

*https://github.com/rsp/node-live-color/blob/master/server.js#L46-L48
If you want easier deploy with Deploy to Heroku button then you may also need an app.json file:

*

*https://github.com/rsp/node-live-color/blob/master/app.json
But for manual deploys you should only need a start script in package.json so that you app could be started with npm start and your app needs to take the port to listen to from the PORT environment variable.
You can test it with locally running:
PORT=2255 npm start

and making sure that you can access your app on http://localhost:2255/ for this and any other port you specify. If you cannot start your app with the above command then your app is unlikely to run on Heroku. You could also have a Procfile presend but without it you should at least have npm start working, see:

*

*https://devcenter.heroku.com/articles/procfile

*https://devcenter.heroku.com/articles/nodejs-support

A: You seem to be trying to deploy a Meteor app to Heroku.
Heroku is not as integrated with Meteor as Galaxy is, or as Modulus / Xervo used to be.
Heroku will detect a node-like app, but you will need first to convert your Meteor app into a Node.js app, typically using meteor build command and uploading the resulting server bundle, or using some MUP thing.
A simple alternative is to use a 3rd party Buildpack, which will do the conversion for you once you upload your Meteor app to Heroku.
You will find plenty resources for that on the above link or here on SO.
See for example: Heroku errors with Meteor 1.4.1.1
Note: the NPM_CONFIG_LOGLEVEL=error line is a setting, not an actual error…

A: What does your Procfile look like? Make sure you don't have web: node app.js in the Procfile. I had the same error and didn't need to use the Procfile. Once I removed it started working.

A: For me, it turned out i required a package that was not in my package.json (dependency), when I added it, the application started working.


text:
Q: Half coloured boxplot in R Is there anyway to have the native R boxplot function produce boxplots with different colours for the top and bottom boxes? Something like this:

Here is the function I came up with:
h.boxplot <- function(..., col.top='orange', col.bottom='yellow', col.scheme='none'){
    cols = c(col.top, col.bottom)
    if(col.scheme != 'none'){
      cs =  list(blue=c('#0071c1', '#3198ff'), green=c('#008001', '#99cc00'), yellow=c('#ffcc00', '#cc9900'))
      stopifnot(col.scheme %in% names(cs))
      cols = cs[[col.scheme]]
    }

    bx<-boxplot(..., col = "white", lty=1, boxlwd=0.00001)
    n = length(bx$names)

    rect(1:n-.4, bx$stats[2,], 1:n+.4, bx$stats[3,], col=cols[2], border=NA)
    rect(1:n-.4, bx$stats[3,], 1:n+.4, bx$stats[4,], col=cols[1], border=NA)
    return(bx)
}

# Examples
data = list(A=1:10, B=20:50)
h.boxplot(data, col.scheme='green', outline=F, frame=F)
h.boxplot(data, col.scheme='blue', outline=F, frame=F)

Should give something like:

A: There's not a parameter that you can set on the base boxplot function to get that behavior, but you can kind of fake it by drawing rectangles over the plot with different colors. For example
bx<-boxplot(count ~ spray, data = InsectSprays, col = "lightgray")
rect(1:6-.4, bx$stats[2,], 1:6+.4, bx$stats[3,], col="orange")
rect(1:6-.4, bx$stats[3,], 1:6+.4, bx$stats[4,], col="yellow")

You can continue to customize that however you like.