text:
Q: CSS: How to center a image within a div vertically and horizontally i have a div and within div i want to center a image.
here is code

.inner-div
{
  margin: auto;
  width: 100px;
  height: 100px;
  border-radius: 3px;
  display: table;
  vertical-align:middle;
  text-align:center;
  background-color:red;
}

img {
    display:inline-block;
    margin-left: auto;
    margin-right: auto;
}

i use above css but still no luck. image is not getting center in div vertically and horizontally. here is jsfiddle link https://jsfiddle.net/year4qt1/4/
looking for suggestion.
Now it looks fine https://jsfiddle.net/7t2fghtf/1/
thanks for the help Mr @Highdef

A: You can use absolute positioning and transform on the img while setting the parent container (inner-div) to relative position:
   position:absolute; /* Absolute relative to inner-div */
   left:50%;   /* Top, left and transform for horizontal and vertical alignment without the use of margin or changing the display */
   top:50%;
   transform: translate(-50%,-50%);

Fiddle : https://jsfiddle.net/7t2fghtf/

$("#mybutton").click(function() {

  //  $.ajax("").done(function(){
  //          $("#mycontent").html( $("#anothermymodal").html());
  //          })
  setTimeout(function() {

    $("#mycontent").html($("#anothermymodal").html());
  }, 10000);

});
.inner-div {
  margin: 0 auto;
  width: 100px;
  height: 100px;
  border-radius: 3px;
  display: table;
  vertical-align: middle;
  text-align: center;
  background-color: red;
  position: relative;
}

img {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  display: inline-block;
  margin-left: auto;
  margin-right: auto;
}
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Small Modal

  <button type="button" id="mybutton" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Small Modal</button>

This is a small modal.

      <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>

A: There are more ways to do this I would suggest using flex. Add this to your code:
.inner-div {
  margin: auto;
  width: 100px;
  height: 200px;
  border-radius: 3px;
  display: table;
  vertical-align:middle;
  text-align:center;
  background-color:red;
  display: flex;
  align-items: center;
}

Fiddle example: https://jsfiddle.net/femu288x/

A: https://css-tricks.com/centering-css-complete-guide/ there are many examples or ways to do this. The position:absolute answer is one way and another is flex (my fav) - check them on the link and try


text:
Q: How to check if file exists on upload? I am building a small file upload application in ASP.NET Core 6. This is the code:
public async Task<IActionResult> OnPostUploadAsync(List<IFormFile> files)
{
foreach (var formFile in files)
{
    if (formFile.Length > 0)
    {
        var filePath = Path.GetTempFileName();

        using (var stream = System.IO.File.Create(filePath))
        {
            await formFile.CopyToAsync(stream);
        }
    }
}

How do I go about checking if the file already exists on the server? FormFile does not have an File.Exists(path) method such as the File class
Thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: With select2, how to access the original select/input element after it's been processed? I'm using a combination of JQuery EasyUI and Select2 to be able to drag options from a right panel, onto a left select box.
In the original HTML, the select boxes are empty, and I only "add" anything to them if I drop an option on them,
<form id="section1">
<select class="select2" class="drop_target" id="selected_options" name="selected_options"></select>

1234

</form>
<form id="section2">
<select class="select2" class="drop_target"></select>

1235

</form>

Then in javascript, I do something like this,
$('.drop_target').droppable({
    accept: '.draggable_option',
    onDrop:function(e, source){
        var $dragged_source = $(source);
        var $drop_target = $(this);
    }
});

The problem comes at this point, if you're dynamically adding things to the select, you have to check it doesn't exist, and if it doesn't, you create a new option, and add it,
var new_option = {
    id: $drag_source.data('id'), data_id: $drag_source.data('id'),
    text: $drag_source.val(), selected: true};

// Set the value, creating a new option if necessary
if (!$drop_target.find("option[value='" + new_option.id + "']").length) {
    // Append it to the select
    $drop_target.append(new Option(
        new_option.text, new_option.id, true, true)).trigger('change');
}

var data = $drop_target.select2('data');
$drop_target.select2('data', data.concat([new_option]));

Clear as mud?  Unfortunately it goes wrong at this point.  While all calls to .select2 from $drop_target work as expected, this is not the select that was originally in the HTML, this is a div that select2 created, after hiding the original select, with an id attribute like id="s2id_selected_options".  So when we append the new option to it, it doesn't get added to the select, and gets added to select2's div incorrectly instead.
My HTML pseudocode is deliberately set up in this "obtuse" way, because my page is like that.  I have multiple forms, and multiple "identical" selects in those forms, generated by WTForms.  So the "general" method of selecting your select by id, $('#selected_options') doesn't work correctly.
What I need to do, within the javascript, is gain access directly to the original, now hidden, select, and I can't access it via id.

A: When you have access to one of the elements that's "associated" with the generated by select2, you can access meta information for it via .data('select2'), or in this instance,
$(this).data('select2');

In here, there's loads of metadata that select2 uses (which you can see if you browse the source).  For this question, to get the original select or input element, you can use,
var $drop_target = $(this).data('select2').opts.element;

Whether you're using a select, or an input, this gives you a jQuery element linking to it.  If you're using a select, and are only interested in that, you can use the shorter option,
var $drop_target = $(this).data('select2').select;

This may be in the docs somewhere, but I was unable to find it, and I'm also not able to find it by searching now, because searching the docs for "data" and "select2" returns a result for nearly every page of their docs (hence the reason I'm answering this question myself, to hopefully save others the trouble).


text:
Q: How can I denote column and row names in a matrix and align equations with that matrix? I want to typeset a large matrix that represents a generalized case of something. I have difficulty doing the following:

*

*Typing a set of letters near columns and rows that identify them

*The matrix is too big so it cannot be centered to the middle of the text. I would like to temporarily increase the margins so that the matrix can be align horizontally to the center

*If possible, I would like Zorig to go exactly to the middle of the empty area in the matrix

*Increase the display size of all elements in the matrix

*It is a good if the dots are more uniformly distributed between the elements they separate

What I get:

What I am (roughly) looking for:

And my source code:
\documentclass[11pt, a4paper]{book}

\usepackage{amsmath}
\usepackage{amssymb, amsfonts}
\usepackage{graphicx}

\usepackage{tabularx}
\usepackage{booktabs}
\usepackage{makecell}

\begin{document}

\begin{equation}
    %
    \begin{aligned}
    %
        \left[
            \begin{array}{c c c c c c c c c !{\vrule width 0.25mm}c}
                & & & & & Z_{1k} & \dotsm & Z_{1p} & \dotsm & Z_{1k} - Z_{1p} \\
                & & \scalebox{3}{$Z_{orig}$} &  & & \vdots & & \vdots &  & \vdots \\
                & & & & & Z_{lk} & \dotsm & Z_{lp} & \dotsm & Z_{lk} - Z_{lp} \\
                & & &  & & \vdots & & \vdots &  & \vdots \\
                Z_{k1} & \dotsm & \dotsm & Z_{km} & \dotsm & Z_{kk} & \dotsm & Z_{kp} & \dotsm & Z_{kk} - Z_{kp} \\
                \vdots & & & \vdots & & \vdots & & \vdots &  & \vdots \\
                Z_{p1} & \dotsm & \dotsm & Z_{pm} & \dotsm & Z_{pk} & \dotsm & Z_{pp} & \dotsm & Z_{pk} - Z_{pp} \\
                \vdots & & & \vdots & & \vdots & & \vdots &  & \vdots \\
                \vdots & & & \vdots & & \vdots & & \vdots &  & \vdots \\ \Xcline{1-10}{0.25mm}
                Z_{k1} - Z_{p1} & \dotsm & \dotsm & Z_{km} - Z_{pm} & \dotsm & Z_{kk} - Z_{pk} & \dotsm & Z_{kp} - Z_{pp} & \dotsm & Z_{th, kp} + Z_{b} \\
            \end{array}
        \right] & \\
        Z_{th,kp} = Z_{kk} + Z_{pp} - Z_{kp} - Z_{pk} & \\
    %
    \end{aligned}
    %
\end{equation}

\end{document}

I realize that the same question was asked in Where is the \matrix command? and Label rows of a matrix by characters, but the solutions provided there do not seem to simultaneously allow for 1. drawing horizontal lines and 2. aligning the main matrix with smaller equation under it (see the figure above).

A: For typing a set of letters near columns and rows that identify them, use blkarray package. See, for example, here: How to write this array?.
To center your matrix which is bigger than line width, I've used \makebox[\textwidth][c]{...}. See, for example, here: Center figure that is wider than \textwidth.
To increase the display size of all elements in the matrix I used \large within a minipage.
For better alignment, I've used \rule[-1ex]{0ex}{3.7ex} and \hspace.
For the correct length of the horizontal line, see here: Horizontal cline lengths inside blkarray.
\documentclass[11pt, a4paper]{book}

\usepackage{amsmath}
\usepackage{amssymb, amsfonts}
\usepackage{graphicx}

\usepackage{tabularx}
\usepackage{booktabs}
\usepackage{makecell}
\usepackage{array}
\renewcommand{\arraystretch}{1.2}
\usepackage{blkarray}% see, for example, https://tex.stackexchange.com/questions/313214/how-to-write-this-array/313219#313219
\usepackage{mwe}% for testing purpose only
\begin{document}
\blindtext% for testing purpose only
\makebox[\textwidth][c]{%
\begin{minipage}{.86\paperwidth}\large
\setlength\aboverulesep{0pt}\setlength\belowrulesep{0pt}
    \setlength\cmidrulewidth{0.5pt}% https://tex.stackexchange.com/questions/377273/horizontal-cline-lengths-inside-blkarray
\begin{equation}
\begin{blockarray}{ccccccccccc}
& & & & & & k & & p & & q\\[1ex]
\begin{block}{c[c c c c c c c c c @{\hspace{1em}}|@{\hspace{.5em}}c]}
& & & & & & Z_{1k} & \dotsm & Z_{1p} & \dotsm & Z_{1k} - Z_{1p} \\
& & & Z_\mathrm{orig} &  & & \vdots & & \vdots &  & \vdots \\
& & & & & & Z_{lk} & \dotsm & Z_{lp} & \dotsm & Z_{lk} - Z_{lp} \\
& & & &  & & \vdots & & \vdots &  & \vdots \\
k & Z_{k1} & \dotsm & \dotsm & Z_{km} & \dotsm & Z_{kk} & \dotsm & Z_{kp} & \dotsm & Z_{kk} - Z_{kp} \\
& \vdots & & & \vdots & & \vdots & & \vdots &  & \vdots \\
p & Z_{p1} & \dotsm & \dotsm & Z_{pm} & \dotsm & Z_{pk} & \dotsm  & Z_{pp} & \dotsm & Z_{pk} - Z_{pp} \\
& \vdots & & & \vdots & & \vdots & & \vdots &  & \vdots \\
& \vdots & & & \vdots & & \vdots & & \vdots &  & \vdots \\[.5ex]
\cmidrule(lr){2-11}
q & \rule[-1ex]{0ex}{3.7ex}
Z_{k1} - Z_{p1} & \dotsm & \dotsm & Z_{km} - Z_{pm} & \dotsm  & Z_{kk} - Z_{pk} & \dotsm & Z_{kp} - Z_{pp} & \dotsm & Z_{th, kp} + Z_{b}\\
\end{block}
\end{blockarray}
\end{equation}
\end{minipage}}\vspace{1ex}
\blindtext% for testing purpose only
\end{document}


text:
Q: Thousands of Cities and Users relationship, what's the right way? In one application, user are allowed to select their desired locations/cities. The city list will be in a tree structure with checkbox like:
[x]Country
-[x]State 1
--[x]City 1
--[x]City 2
--[x]City 100
-[X]State 2
--[x]City 1
--[x]City 2
--[x]City 100
[x]Country 2

......
Now, if user select country then all he'll have all state and cities. If selects one ore more states and those state, cities and country too be be stored for that user. User can select one or more country. Also user can uncheck any one desired city or state.
How would you suggest to store and retrieve data. I'm using MySql and Php.
Will a look-up table be ideal? OR can I grand all locations id kand store in json format in a text type column?
Thanks!

A:
How would you suggest to store and retrieve data. I'm using MySql and Php. Will a look-up table be ideal?

To store country, state and cities you should use normalized database schema. Country has states. States has cities. You need Junction tables.

OR can I grand all locations id kand store in json format in a text type column?

No. that would not be a normal form. And it'll create a lot of problem. You can not perform CRUD operations easily.
Database schema
create table countires(name varchar(100) primary key);
create table sates(name varchar(100) primary key, country varchar(100), foreign key `country` references `countries`(`name`));
create table cities(name varchar(100) primary key, state varchar(100), foreign key `state` references `states`(`name`));

Now you can run any different type of queries on these tables. Say user have selected city (city1, city2), country cntry1 and a state stt2.
Queries
Find all the cities that users have selected.
SELECT ct.name
FROM   cities AS ct
       JOIN states AS st
         ON ( st.name = city.state )
       JOIN countries AS cn
         ON ( cn.name = st.country )
WHERE  ct.name IN ( 'city1', 'city2' )
        OR cn.name = 'cntry1'
        OR st.name = 'stt2';

Find all the states that users have selected.
SELECT st.name
FROM   states AS st
       JOIN countries AS cn
         ON ( cn.name = st.country )
WHERE   OR cn.name = 'cntry1'
        OR st.name = 'stt2';

Update 1

how to maintain its relation with user?

You need Junction tables. Just create 3 of them.
create table users(name varchar(100) primary key);
CREATE TABLE user_countries
  (
     user    VARCHAR(100),
     country VARCHAR(100),
     PRIMARY KEY (`user`, `country`),
     FOREIGN KEY (`user`) REFERENCES `users`(`name`)
     FOREIGN KEY (`counry`) REFERENCES `countries`(`name`)
  );
CREATE TABLE user_states
  (
     user    VARCHAR(100),
     state   VARCHAR(100),
     PRIMARY KEY (`user`, `state`),
     FOREIGN KEY (`user`) REFERENCES `users`(`name`)
     FOREIGN KEY (`state`) REFERENCES `states`(`name`)
  );
CREATE TABLE user_cities
  (
     user    VARCHAR(100),
     city    VARCHAR(100),
     PRIMARY KEY (`user`, `city`),
     FOREIGN KEY (`user`) REFERENCES `users`(`name`)
     FOREIGN KEY (`city`) REFERENCES `cities`(`name`)
  );

A: I would say it depends on how you are going to need to access the stored data.  If you are only going to look up the data based on the user who submitted it, then there is probably no reason that you couldn't store the serialized tree data (i.e JSON, PHP serialize, etc.) in a database record associated with the user. Incidentally this would also be a good use case for a NoSQL data store.
If however you need to be able to, say lookup all users with a specific country, state, or city selected, then you will need to store you data such that it is queryable in this fashion.  That might mean separate tables for countries, state, and cities with table to relate the users to each, or it could simply mean a single jurisdiction table that allows different types of jurisdictions within it along with a table relating users to jurisdictions.  How you approach the schema will likely depend on how differently you need to treat countries, states, and cities from each other (i.e does each jurisdiction type need to have drastically different attributes).

A: I would recommend storing only the selected values and deriving the rest. Yes, it'll be somewhat more painful to retrieve the data, but it'll have a couple significant upsides:
It'll continue to be accurate when your source data changes: Imagine you had this application running when the Soviet Union broke up. You convert you "USSR" entry to read "Russia" and convert a bunch of "States" to countries. With your model, this would cause massive amounts of user data to be changed. However, with a derived model, this becomes much simpler. Anyone with a city selected is automatically fixed when the city is assigned to the proper country. A bunch of people with a state selected may suddenly find they have a country selected instead, but the cities under that level are automatically fixed.
It'll simplify your create, update and delete operations: Instead of writing hundreds or thousands of rows, every change affects exactly one row.


text:
Q: UVM Monitor behaves differently based on sequence of two statements In UVM monitor when below two statements are added in run_phase as below, value sampled in tr.pkt is correct as per data_in. But if the order of statement is reversed, tr.pkt sampled is incorrect ('h0 sampled). Anybody seen it before?
tr.pkt.push_back(this.wr_if.mon_clk_blk.data_in);
`uvm_info("",$sformatf("Write Monitor data = %0h", this.wr_if.mon_clk_blk.data_in), UVM_NONE)

A: Most likely data_in is being updated in the same time step as the UVM montitor's execution.
In the scheduler, push_back() executes in the active region and `uvm_info() happens in the observed region. Another process would have updated data_in in the reactive region or latter scheduled active region. By reversing the .push_bach() / `uvm_info() order gives an opportunity the other thread to assign data_in before re-entering the active region to perform .push_bach(). Zero time glitches (such as #0 in the design), could also relate to the unexpected values.
One way to guarantee both .push_bach() and `uvm_info() get the same value is to create a temporary variable that samples data_in. Example:
sampled_data = this.wr_if.mon_clk_blk.data_in;
tr.pkt.push_back(sampled_data);
`uvm_info("",$sformatf("Write Monitor data = %0h", sampled_data), UVM_NONE)


text:
Q: Can't access a object property of an array element, inside a object in javascript I have an array of objects inside an object.
Why do I get the error 'Cannot read property fname of undefined' below?  How do I fix it?
Also, I'm new to javascript and would appreciate any styling or convention suggestions.
https://jsfiddle.net/go1eu9z6/
function myObj() {
  this.X = [],

    this.haveEntries = function() {
      return this.A.length > 0;
    },

    this.add = function(fname_in, lname_in, city_in) {
      var t = new Date().getTime() / 1000;

      var obj = {
        fname: fname_in,
        lname: lname_in,
        city: city_in,
        t_create: t
      };

      this.X.push(obj);

      return this;
    }
}

var AB = {};
AB.X = new myObj();

AB.X.add("mike", 'smith', 'Toronto');

var s = AB.X[0].fname; // Error:  Cannot read property fname of undefined

document.getElementById('fname').innerHTML = s

A: There were a couple problems with your javascript code. Firstly, you were assigning AB.X a value of new Obj() instead of simply AB. Then, you were calling the add method on AB.X, when the correct call would simply be AB.add - see code example below
  function myObj() {
    this.X = [],

    this.haveEntries = function() {
      return this.A.length > 0;
    },

    this.add = function(fname_in, lname_in, city_in) {
      var t = new Date().getTime() / 1000;

      var obj = {
        fname: fname_in,
        lname: lname_in,
        city: city_in,
        t_create: t
      };

      this.X.push(obj);

      return this;
    }
}

var AB = {};
AB = new myObj();

AB.add("mike", 'smith', 'Toronto');

var s = AB.X[0].fname;

A: You don't need to make X an instance of myObj. In fact, that's what's breaking your code. X is created when you make a new instance of myObject, like this:
var AB = new myObject();

Then you would be calling your add() method on this AB object, not on X:
AB.add('mike','smith','toronto');

Finally, you would get your results like this:
var firstName = AB.X[0].fname;

This is a little round-about why of constructing this object, though. How do you know which person's name and info occur at which index of X? Maybe look into using an object to store this data with some key that helps you know where stuff is. Might look like:
var people = {
    "uniqueID": {            // some uniqueID
       "fname":"mike",
       "lname":"smith",
       "city":"toronto"
    }
}

A: with you existing code you can also access it by using
var s = AB.X.X[0].fname;


text:
Q: Parsing JSON response in JSP {"name":"Arnav","surname":"Rodrigues","gender":"male","region":"India"}

How do I parse this JSON response in JSP/Java.
For Ex:
Name: Arnav
Surname: Rodrigues

A: String jsonStr = '{"name":"Arnav","surname":"Rodrigues","gender":"male","region":"India"}';
JSONObject myObject = (JSONObject) JSONValue.parse(jsonStr);
// myObject.name, myObject.surname, ...


text:
Q: Running Linux commands with multiple arguments After some digging I can run Linux commands from go like this:
func main() {
    lsCmd := exec.Command("ls")
    lsOut, err := lsCmd.Output()
    if err != nil {
        panic(err)
    }
    fmt.Println(">ls")
    fmt.Println(string(lsOut))
}

What I want to do is, running following command in remote machine:
ssh -p $someport $someuser@$someip 'ls'

I can  do this successfully from my terminal, but when I try to run it within Go, I get following error:
panic: exec: "ssh -p $someport $someuser@$someip 'ls'": executable file not found in $PATH

Update: I updated the question for convenience.

A: As per the doc about the exec package, program name and arguments are differents parameters of the Command method.
You should do something like that :
exec.Command("ssh", "-p port", "user@ip", "'ls'")

If you need something more elaborate, you could also look at the go.crypto/ssh package.

A: If you want run multiple commands on a remote machine the below trick might help you achieve this.
Ssh username@ip < EOf

ls -I

Pwd

Uname

Eof

Please note that it doesn't pass any special characters like . , etc.


text:
Q: Problem in Opening Word 2010 using Visual Studio 2010? I have been trying to open a Word document using C# in VS2010. But I have been successful so far. I have tried searching for answers but all in vain. In the reference section, I cannot see the Microsoft Word office library (any version) in the COM tab. I added the Microsoft.Office.Interop.Word. version 14 from the .Net tab, but still i get the same exception:

An unhandled exception of type
  'System.Runtime.InteropServices.COMException'
  occurred in mscorlib.dll

Additional information: Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)).

A: You need to make sure that both Microsoft Office and Visual Studio Tools For Office (VSTO) are installed on the machine.

*

*VSTO: http://www.microsoft.com/downloads/details.aspx?FamilyId=5E86CAB3-6FD6-4955-B979-E1676DB6B3CB&displaylang=en

A: VSTO is not the solution; Visual Studio 2010 has it built in.
I found the problem for me with the exact same error that you are getting was that I installed Office from the download using the "Click to run".  I did download Office the first time I installed.  This time I actually used the install DVD and now my code works perfectly.  If you don't have the DVD then you can download the trial ISO file instead of the "Click to run" exe.

A: Word 2010 must be installed on the machine.


text:
Q: Syncfusion Dashboard: load data from Data Source dynamically by swap parameters I try to use Syncfusion Dashboard Designer for data visualization.
I use Web Data Source as connection type.
I want to filter data by some parameters, for example date range filter (DatePicker).
The problem is that Dashboard (I try dashboard preview) loads data from Data Source once and then filtering all at the UI level.. i.e. caches data.
Also when I try update manually from UI in browser requests don't go to the server :

It updates only when I use refresh button in Dashboard designer Data Source editor:

Also Refresh Settings -> Enable Auto Refresh not works in dashboard preview:

This is a problem because I have a lot of data for several years that constantly adding and I don't want to pull everything at once.
Is it possible to load data from Data Source dynamically by swap startDate and endDate parameters from DatePicker?
Example:
http://host_name/webservice/some_rest_method?startTime={swapped_startTime}&endTime={swapped_endTime}&group=false

So web data source  will return the data that is required by request.
I'm sure that this should be because this is one of the main things and this is good practice.

A: You can achieve this using the Dashboard SDK platform as an alternate solution. A sample application has been created in ASP.Net MVC to demonstrate your requirement. Please find the sample from the following link http://www.syncfusion.com/downloads/support/directtrac/general/ze/LocalEmbeddedDashboard-304170304 .
Copy the Dashboard Service hosted URL and paste it in the file "Controllers\DashboardViewerController.cs" as shown below and run the application.
DashboardViewerController.cs
In the sample application we have a date picker widget where you can choose the start and end range of the data. Upon selecting the range the query will be generated with the selected value and the dashboard will be showcasing the filtered data.
Please refer the code in the files "Controllers\DashboardViewerController.cs" and "Views/DashboardViewer/Index.cshtml".

A: The current version (2.2.0.31) of Syncfusion Dashboard  doesn't support dynamic requests to data sources.
Also it doesn't support dynamic parameters.


text:
Q: Thymeleaf: Comma separated values of a list? I am beginner in Thymeleaf, I have a list and want to list elements in a line by separating comma e.g. London, Paris, Berlin, HonKong (there will be no comma after the the last element). However, the following code generate new row. So, how can I make it work as explained above?

I know it also add an extra comma at the end of the last element and I need to use index e.g. for detecting the last index. How can I do this?

A: You should look at Thymeleaf #strings utility methods. There is a set of functions to split and join different types of lists. Your code may look like ...

A: You can use a sequence of  tags to hold your text.
You can use Thymeleaf's iteration status tracking values to know when you are handling the last item in the list.
Combining these:

The iterStat.last value is a boolean which tells us when we are processing the final value - and the ! (not) operator is used to suppress the final comma + space.


text:
Q: Skrollr does sudden jerk instead of smooth scroll Can you help me figure out why skrollr (parallax scrolling) isn't working on this page?
http://adoptastar.whitedwarf.org
When logged in with an admin bar at the top, I can scroll all the way to the bottom, and toward the end there will be a jump where the background stars move. When there's no admin bar, there isn't even a jump. How can I make the background layers scroll smoothly like at http://adoptastar.whitedwarf.org/parallax/?
I've tried adding
height: 100%;

to html, body, #wrapper, and #container, to no avail. And sometimes adding this screws up the navigation bar anchors, like http://adoptastar.whitedwarf.org/#adopt, in Safari (the bottom of #container will jump up above the bottom of the page, and content within #container will appear beyond the bottom of #container).

A: You're missing a unit for the background position, which skrollr requires
Wrong
data-0="background-position: 0 0;"

Right
data-0="background-position: 0 0px;"


text:
Q: Need optimization of this trigger?Can anyone help me out.? Actually, I am trying to get Area_c field from custom object(Zip Codes) into the lead object custom field Area_c. So, I have written some of the code but is there any other way to write it or get some optimization of this code.
trigger OpportunityPriceBook on Lead (before insert) {

List<String> zipList = new List<String>();

for(Lead lead : Trigger.new){

   zipList.add(lead.PostalCode);

}

List<Zip_Code__c> zipCodeList = [Select Id, Name, City__c, Area__c from

Zip_Code__c WHERE Name IN : zipList];

for(Lead leads : Trigger.new){

    for(Integer i =0 ; i < zipCodeList.size(); i++)
      {
         leads.Area__c = zipCodeList.get(i).Area__c;
         leads.City = zipCodeList.get(i).City__c;
         break;
      }

    }

  }

A: Given the code, there are a couple of ways that you can simplify your last multi-dimensional for loops; nested for loops can be problematic at times due to their exponential nature.
That point made, you have one pretty glaring bug in your code: You do not have an identifying conditional statement in your nested for loop, and actually always only set the lead to the first zipcode's data each time.
This is the approach I would take:
// Extract out the postal codes of the leads
List<String> zipList = new List<String>();
for (Lead lead : Trigger.new) {
    zipList.add(lead.PostalCode);
}

// Query for the related Zip Codes, and map them by Name
List<Zip_Code__c> zipCodeList = [SELECT Id, Name, City__c, Area__c FROM Zip_Code__c WHERE Name IN :zipList];
Map<String, Zip_Code__c> zipCodeByName = new Map<String, Zip_Code__c>();
for (Zip_Code__c zipCode : zipCodeList) {
    zipCodeByName.put(zipCode.Name, zipCode);
}

// Stamp leads with the Area and City as identified by the matching Zip Code
for (Lead lead : Trigger.new) {
    Zip_Code__c zipCode = zipCodeByName.get(lead.PostalCode);
    lead.Area__c = zipCode.Area__c;
    lead.City = zipCode.City__c;
}


text:
Q: Validate XPath expression in Perl Please refer this question How can we do the same in Perl?

A: You're looking for libxml's xmlXPathNewContext in Perl? It's easy, you search the CPAN for libxml, and then search (grep) the distribution you found for xmlXPathNewContext. After that you should have found an example to copy/paste or docs to read.
$ perl -mXML::LibXML -e'XML::LibXML::XPathExpression->new( q{/foo} )'

$ perl -mXML::LibXML -e'XML::LibXML::XPathExpression->new( q{/foo<} )'
XPath error : Invalid expression
/foo<
     ^

$ perl -mXML::LibXML -e'XML::LibXML::XPathExpression->new( q{/foo[} )'
XPath error : Invalid expression
/foo[
     ^

$ perl -mXML::LibXML -e'XML::LibXML::XPathExpression->new( q{/foo[]} )'
XPath error : Invalid expression
/foo[]
     ^

$ perl -mXML::LibXML -e'XML::LibXML::XPathExpression->new( q{/foo[1]} )'

$


text:
Q: Express routes and middleware I'm using a role authorisation (connect-roles), and trying to add more than one role for each route. This is using express, and monogoose. Here is the code I currently have:
 router.get('/admin/:slug', function (req, res) {

   if (user.can('vip')) {

     adminController.showVipView // <-- this is what I need to work

   } else {

     // call a different view

   }

});

This is how it normally works without the if statement. This seems like super basic express, but I just cannot get it to work.
router.get('/admin/:slug', user.can('vip'), adminController.showVipView);

A: Just pass request and response into it:
adminController.showVipView(req, res);

It might also requires the next callback, then you should pass that into it too...
By the way, your if statement wont work either as it returns a middleware. Might do this:
user.can('vip')(req, res, function(){
  adminController.showVipView(req, res);
});


text:
Q: Is index like key(timetime) usable when we query: SELECT * ....... ORDER BY timetime DESC When we index a timestamp field like timetime. Can we use it for ORDER BY timetime DESC or is it just usable for ORDER BY timetime ASC OR ORDER BY timetime? Does mySQL use this index when doing vise verse ordering?

A: Yes, it does. MySQL can use the index and use it for scanning/seeking in either direction. You can read in MySQL documentation: How MySQL Uses Indexes

To sort or group a table if the sorting or grouping is done on a leftmost prefix of a usable key (for example, ORDER BY key_part1, key_part2). If all key parts are followed by DESC, the key is read in reverse order. See Section 8.13.9, "ORDER BY Optimization", and Section 8.13.10, "GROUP BY Optimization".


text:
Q: PHP + MsSQL = Checkbox problems. Need HELP! I have been working on this one topic for weeks. I'm creating a webpage that pulls information from MsSQL server. My problem is where there is a section with few check boxes.
The checkboxes are suppose to be checked if they are found in the SQL database.
If the borrower used money from "Savings", "Checking" and "Stock" those checkboxes should be checked in HTML page.  In my case it is only checking whatever is on the first row of the SQL search list. So if the list has "Saving" on the first row, only the "Saving" checkbox will be checked not the rest on the list. I tried using loop (while($r->EOF)), but then it picks whatever is on the end of the list.  Here is what I am using to pull data from the SQL server.  Thank you in advance for your help. Really appreciate it!
function __construct($_ldid, $_lrid)

            $this->ldid = $_ldid;
            $this->lrid = $_lrid;

//$loan is defined in the PHP.class (which is shown below).

$q = ("SELECT * FROM Tabel_name where loan_id = 885775")
$v = array($_ldid, $_lrid);
$r = $db->Execute($q, $v);
$this->downpaymenttype = $r->fields; //<- I think I have this line done wrong because it is suppose to store the outputs to an array.

//So wherever the "$loan" is in HTML page, it will take the outputs from the above statement.

//The above code, which is in PHP.class file, outputs the following(or suppose to):
1    885775    Checking
2    885775    Saving
3    885775    Gift

In the HTML webpage, the following codes should check mark the boxes according to the outputs:
<input type="checkbox" name="DPS1[]" id="DPS1-{$key}" {if $loan-> downpaymenttype.downpaymentsource == "Checking"} checked {/if}/>

<input type="checkbox" name="DPS2[]" id="DPS2-{$key}" {if $loan-> downpaymenttype.downpaymentsource == "Saving"} checked {/if}/>

<input type="checkbox" name="DPS3[]" id="DPS3-{$key}" {if $loan-> downpaymenttype.downpaymentsource == "Gift"} checked {/if}/>

Only the "checking" checkbox is getting checked because that's the one on the first row.
I also tried to loop, but it is not storing in array (I guess I don't know how to use the array for session)
$q = ("SELECT Tabel_name FROM loan_downpaymentsource where loan_id = 885775");
$v = array($_ldid, $_lrid));
$r = $db->Execute($q, $v);
while(!$r->EOF) {
$this->downpaymenttype = $r->fields;
$r->MoveNext();
}

A: Add a loop to go through your results before displaying and set flags.  $r->fields is only going to grab the fields for the current row.  You need to go through your entire rowset to see if the others are set.
Something like (It looks like you're using adodb or something like that)
$checking = false;
$saving = false;
$gift = false;

while(!$r->EOF){
    $row = $r->fields;
    switch($row->downpaymenttype){
        case 'Checking':
            $checking=true;
            break;
        case 'Saving':
            $saving=true;
            break;
        case 'Gift':
            $gift=true;
            break;
        default:
        break;
    }
    $r->moveNext();
}

Now on your view check the flags. I've not used smarty but you'll have to pass those flags to your template as well as I'm sure you know, and then change your checkbox lines to check if each flag is true/false.
Hope that helps!


text:
Q: Keycloak only gets Google refresh token on first login I'm using Keycloak with Google as identity provider. I need a refresh token from Google in order to manage the calendar of users. Here are my Keycloak Google IDP settings:

After login I fetch the refresh token according to https://www.keycloak.org/docs/latest/server_development/index.html#retrieving-external-idp-tokens. Which looks like this:
{
    "access_token": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "expires_in": 3599,
    "refresh_expires_in": 0,
    "refresh_token": "YYYYYYYYYYYYYYYYYYYYYYYYYYYY",
    "token_type": "Bearer",
    "id_token": "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
    "not-before-policy": 0,
    "scope": "openid https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile",
    "accessTokenExpiration": 1593706596
}

Now the problem is when I login a second time and then try to fetch the refresh token again it's gone:
{
    "access_token": "XXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    "expires_in": 3599,
    "refresh_expires_in": 0,
    "token_type": "Bearer",
    "id_token": "ZZZZZZZZZZZZZZZZZZZZZZZZZZZZ",
    "not-before-policy": 0,
    "scope": "https://www.googleapis.com/auth/calendar https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile openid",
    "accessTokenExpiration": 1593706782
}

I'm really not sure how this is possible. One thing that came to my mind is that Keycloak is not respecting the "Request refresh token" setting on subsequest logins, but I don't know how to verify this.

A: It's not a Keycloak bug, it's a Google specification. The refresh_token is only provided on the first authorization from the user. Here the documentation of this behavior:

refresh_token: A token that you can use to obtain a new access token. Refresh tokens are valid until the user revokes access. Again, this field is only present in this response if you set the access_type parameter to offline in the initial request to Google's authorization server. - source

If you want to get the refresh token again you must:

*

*Go to the page showing Apps with access to your account: https://myaccount.google.com/u/0/permissions.

*Under the Third-party apps menu, choose your app.

*Click Remove access and then click Ok to confirm

*The next OAuth2 request you make will return a refresh_token (providing that it also includes the 'access_type=offline' query parameter.

related to this answer


text:
Q: SQL Server 2016 query Azure AD I need to query our (Azure) AD to get a user username based on on an email address I am being passed and then write it to a table ideally via an SP.
From my brief bit of reading, Azure AD supports Graph as does SQL Server 2017 and in theory I could use that to integrate the two, unfortunately, I am using SQL Server 2016 and the amount of testing required to upgrade to a more modern SQL version would probably be more than I could justify for this (small) project.
Does anyone have any suggestions?  Am I going to have to resort to calling an external power shell script?


text:
Q: Stream MP4 video onto iPhone directly from S3? I have a bunch of MP4 files on S3.  Is it possible to stream MP4 video content onto iPhone directly from S3?  If so, how can I do this?  If I can't do this, what options do I have for streaming video to iPhone? (e.g. run HLs streaming server on EC2? pseudo-streaming or progressive media download?)
Cloudfront can stream video but apparently only using RTMP protocol which is not supported natively by iOS.  I'd like to stream natively (make things easier).  Thanks all.

A: You can stream, but the video file must be segmented into .ts files and an .m3u8 file that lists the segments. See https://developer.apple.com/streaming/


text:
Q: Android Studio SQLite Database Unable to find on Android Device Monitor I'm trying to create a database to store data entered on the journal app I'm developing at the moment, but I came across an small issue where I try to see if the database is created, but it doesn't show when I look on Android Device Monitor > data > data > database folders.
What exactly am I missing on my code?
     public class DBOpenHelper extends SQLiteOpenHelper{

    //Constants for db name and version
    private static final String DATABASE_NAME = "notes.db";
    private static final int DATABASE_VERSION = 1;

    //Constants for identifying table and columns
    public static final String TABLE_NOTES = "notes";
    public static final String NOTE_ID = "_id";
    public static final String NOTE_TEXT = "noteText";
    public static final String NOTE_CREATED = "noteCreated";

    //SQL to create table
    private static final String TABLE_CREATE =
            "CREATE TABLE " + TABLE_NOTES + " (" +
                    NOTE_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
                    NOTE_TEXT + " TEXT, " +
                    NOTE_CREATED + " TEXT default CURRENT_TIMESTAMP" +
                    ")";

    public DBOpenHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(TABLE_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_NOTES);
        onCreate(db);
    }
}

     public class HomeActivity extends AppCompatActivity implements NavigationView.OnNavigationItemSelectedListener
{
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        DBOpenHelper helper = new DBOpenHelper(this);
        SQLiteDatabase database = helper.getWritableDatabase();
}


text:
Q: Conditional logic for mouseleave I have a grid of buttons four across by two deep, say 800px wide by 400px deep. Mousing over any button shows a smaller layer centered over the buttons (say 700 x 300 px).
I'm attaching the mouseenter and mouseleave events to a class assigned to all the buttons, which swaps the img src for all the buttons, and a separate function to show the specific layer element for each button.
So when you mouse over any button, all the buttons are greyed out and a specific layer is displayed on top of them, and when the mouse leaves the button, the layer is hidden and the buttons return to the default state.
This works fine, but I want to prevent the buttons from changing back to their default state when the mouse is over the visible layer. So if you move the mouse from the button onto the layer superimposed above it, all the buttons remain greyed out. If the mouse leaves the layer, then the layer is hidden and all the buttons revert to their default state.
I've tried creating a global javascript var to prevent the mouseleave event from firing when the mouse is over the visible layer, and setting that var when the mouse enters the visible layer, but the mouseleave event fires before I can set the global var...I'm caught in a chicken-and-egg loop?
I'm setting my mouseenter/leave here:
    window.lyrEntered = false;

    jQuery(function () {
        $(".img-swap").mouseenter(
      function () {
          $(".img-swap").each(function () {
             this.src = this.src.replace("_on", "_off");
          });
      });
        $(".img-swap").mouseleave(
      function () {
          //if layer entered, keep button state
          if (lyrEntered) {

          } else {
              //reset buttons if layer entered is false
              $(".img-swap").each(function () {
                  this.src = this.src.replace("_off", "_on");
                  //reset button state
                  window.lyrEntered = false;
              });

          };
      });
    });
    function showIt(lyr) {
        $(lyr).show();
    }

on each button, I'm setting the layer to display:

and on each layer, I'm trying to set the global var to prevent the mouseleave event from firing and resetting the buttons to their default state:

[content here]

but of course, setting the global var here is too late, because the button's mouseleave event is triggered before the global var can be set to true?

A: It's not an ideal situation, but you could use a variable in javascript:
var layerTimeout;

On the buttons use
onmouseout="layerTimeout = setTimeout(function(){$('#layer1').hide();},100);"

And when you enter the layer clear the timeout, before it fires:
clearTimeout(layerTimeout);

For your image u can also use a timeout and when you enter the layer clear both timeouts.
As i said before i don't find this solution very clean, but it can surely help you out.

A: I would think something like this would work
$('your_top_layer_element').on('mouseenter', function() {
    $(".img-swap").each(function () {
        this.src = this.src.replace("_on", "_off");
    });
});

Basically you are doing the same thing when hover on that top layer as when hovered over the img-swap


text:
Q: Unable to Call System.Management.Automation.Runspaces.WSManConnectionInfo I need to achieve this using .Net-3.5
I have referenced the required DLLs in my project:
[]
using System.Management.Automation;
using System.Management.Automation.Runspaces;

But whenever I try using WSManConnectionInfo, for example here:
WSManConnectionInfo connectionInfo = new WSManConnectionInfo();
connectionInfo.ComputerName = machineAddress;
Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);
runspace.Open();
using (PowerShell ps = PowerShell.Create())
{
    ps.Runspace = runspace;
    ps.AddScript("Get-Service");
    var results = ps.Invoke();
    // Do something with result ...
}
runspace.Close();

I get a "type could not be found" error:
The type or namespace 'WSManConnectionInfo' could not be foun (are you missing a using directive or assembly reference?)
I am trying to remote into a PowerShell session on our server (from an app running locally on the client machine), which can then query which processes are running in that person's session.
According to MSDN all I need is the System.Management.Automation namespace, and I couldn't see any mention of framework version limitations. Am I being really stupid here or does Microsoft just have the worst documentation in the universe?

A: I found the answer I was looking for here.
Basically, I had to change my reference from
C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll
to
C:\Program Files(x86)\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\System.Management.Automation.dll
For some reason this completely resolved all of my issues - I have no idea what the difference is between these two assemblies and would really appreciate any insight into this.


text:
Q: Open HKCR and HKCU for another user from unprivileged app (via RPC) Having trouble implementing cross-user registry access in an unprivileged app (via local RPC). Here's the situation:

*

*I'm writing a sandboxed app that can access an RPC server, but has almost no access to the registry.

*I have an RPC server running as LocalSystem on the same machine as the sandboxed app. The RPC transport used is LRPC (ncalrpc).

*I want to enable the app to browse various parts of the registry - including keys owned by other users - without editing the ACLs on the registry keys to give this app access directly.

Currently, the app calls into the RPC server, which opens an HKEY to the requested path and then uses DuplicateHandle to pass it back to the app.

*

*This works fine for HKLM and HKU. The app receives the HKEY and can use it to enumerate subkeys and read values.

*For subkeys of those hives, it also works well. The app gets the subkey and can enumerate its contents.

*I want something that will handle HKCU (which is entirely per-user) and HKCR (which is a union of the system classes root and the per-user classes root) for users other than LocalSystem (what the RPC service runs as).

What I've tried so far:

*

*Having the app try opening the root keys itself, then pass them (via DuplicateHandle) to the RPC server instead of the predefined keys.

*

*This doesn't work even for the app's own user; the app can open the keys (with very limited access) but the server apparently can't open sub-keys of these passed-in root HKEYs (possibly due to the low privileges of the original HKEY?).

*This doesn't work at all for other users; the app doesn't have permission to use functions like RegOpenUserClassesRoot (can't get another user's token) or RegOpenCurrentUser (app is unable to impersonate other users).

*Having the app call RegOpenUserClassesRoot and RegOpenCurrentUser on the server and pass those HKEYs back to the app (via DuplicateHandle, the way it does with all HKEYs). The app then stores those returned keys, and duplicates them to the server when it wants to open a subkey of those keys. This doesn't work either (results in access denied errors).

Things I could try:

*

*Have the server get the reg keys it needs, on demand, when the client tells it to get a user's HKCU or HKCR. Downside is more overhead on repeated calls (unable to re-use keys, unless a lot of caching goes on), upside is it avoids a DuplicateHandle round-drip (which might be the problem, somehow...). Seems unlikely to actually solve the problem, but I haven't tried yet.

*Change registry key ACLs to give the app the access it needs directly. This still requires that the server be able to open the registry keys that the user is trying to identify. I'm not even sure that the per-user HKCR union view exists until somebody tries to open that key.

*Go over the code yet again looking for a bug that has thus far eluded me, narrowing down the range of possible causes of the problem. So far this hasn't worked for this problem, though it did let me solve a different one that I had with this RPC server (this is the first large-scale piece of MSRPC code I've written) so maybe I'll get lucky this time. This is also obviously the thing to do if one of the things I've tried ought to have worked, but didn't.

Anybody with any experience in this area have an idea about what I'm doing wrong?


text:
Q: How to save list of own classes in a plist in XML format using NSKeyedArchiver (or other mechanics)? I manage to write a plist in binary format to disk.
But I do not manage to write the data in XML format. I read this should be possible, but there is no sample code or documentation doing this.
Code for storing which works:
var listofbookmarks = [Bookmark]() // <- needed to create a mutable array instance
listofbookmarks.append(Bookmark(name: "myname", position: "100"))

let fileManager = NSFileManager.defaultManager()

if let directories = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory,NSSearchPathDomainMask.AllDomainsMask, true) as? [String] {
    if !directories.isEmpty {
        let plistpath = directories[0].stringByAppendingPathComponent("BookmarkArray.plist")
        if !fileManager.fileExistsAtPath(plistpath) {
            // HOWTO TO STORE IN XML ?
            NSKeyedArchiver.archiveRootObject(listofbookmarks, toFile: plistpath)

            println(plistpath);
        }
    }
}

A: Assuming your Bookmark class is adopting the NSCoding protocol, all you have to do is set your NSKeyedArchiver outputFormat to NSPropertyListFormat.XMLFormat_v1_0:
Replace
NSKeyedArchiver.archiveRootObject(listofbookmarks, toFile: plistpath)

with
let archivedData = NSMutableData()
let archiver = NSKeyedArchiver(forWritingWithMutableData: archivedData)
archiver.outputFormat = NSPropertyListFormat.XMLFormat_v1_0
archiver.encodeObject(listofbookmarks)
archiver.finishEncoding()
archivedData.writeToFile(plistpath, atomically: true)


text:
Q: error of creating a repository:did you run git update-server-info on the server? I'm very new to git. I wanted to create a repository named Common-Lib, below is the commands I used.
E:\My Doc\programming\git\Common-Lib>touch README

E:\My Doc\programming\git\Common-Lib>git init
Initialized empty Git repository in E:/My Doc/programming/git/Common-Lib/.git/

E:\My Doc\programming\git\Common-Lib>git add README

E:\My Doc\programming\git\Common-Lib>git commit -m "first commit"
[master (root-commit) 5e25a0d] first commit
 0 files changed
 create mode 100644 README

E:\My Doc\programming\git\Common-Lib>  git remote add origin https://github.com/fxbird/Common-Lib.git

E:\My Doc\programming\git\Common-Lib>git push -u origin master
fatal: https://github.com/fxbird/Common-Lib.git/info/refs not found: did you run git update-server-info on the server?

E:\My Doc\programming\git\Common-Lib>git update-server-info

E:\My Doc\programming\git\Common-Lib>git push -u origin master
fatal: https://github.com/fxbird/Common-Lib.git/info/refs not found: did you run git update-server-info on the server?

E:\My Doc\programming\git\Common-Lib>

Even after running git update-server-info, it still throws the same error, why is that? thanks.

A: The commands you've used have successfully created a repository OK on your own machine, but it doesn't exist on Github; that's why you get the error:
fatal: https://github.com/fxbird/Common-Lib.git/info/refs not found

The "refs" file isn't found because it doesn't exist. Your best solution is to create the repository on Github first and then clone it to your local machine. That way everything will be set up for you to push and pull.
Oh, and when you ran:
git update-server-info

you ran that on your local repository, not on the server so it wouldn't work anyway. That command generates files necessary to access your repository over "dumb" protocols like http.

A: I don't see targetted repository in your GitHub profile. Click the icon Create a New Repo on top bar right to your username to create it first.

A: this is a work around I'm also new to git so if we ave to manually create the directory then what's te use of executing this statement
"git remote add origin https://github.com/fxbird/Common-Lib.git"


text:
Q: React - API Function Does Not Have Access to Context API While creating a reusable, importable function for making API calls I ran into the issue of not being able to access the Context API to get the auth token.
Importable Function:
import React, { useContext } from 'react';
import { Context } from '../Context';
import axios from 'axios';

const FetchDataFunction = (method, endpoint, params) => {

  const [context] = useContext(Context); // the line throwing the error

  const api = axios.create({
    baseURL: `...`,
    headers: {
      'Authorization': 'Bearer 11111111111111111', //need this from API Context
      'Content-Type': 'application/json',
      'Accept': 'application/json'
    }
  });

   ...make api request...
 }

Component trying to use the function
import React, { useContext } from 'react';
import FetchDataFunctionfrom '../../../../FetchDataFunction';
import { Context } from '../../../../Context';

const ComponentName = () => {
   const [context] = useContext(Context); //works!

   useEffect(() => {
     async function fetchData() {
         var result = await FetchDataFunction('get','endpoint', {params: {...}});
     }

    fetchData();
   },[]);
}

Error:
Unhandled Rejection (Error): Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See link for tips about how to debug and fix this problem.
I need access to the context api to get auth tokens as well be able to update the context api when auth tokens expire. Thus passing the context to the function is not an option. React/Redux is complex and seems like it will be replaced by Context.
Anyone have a solution to this problem?

A: context is meant for functional Components and not functions. Why not read context value and pass in your function as parameter?

A: I used a custom hook that would fetch the data.
See here: https://reactjs.org/docs/hooks-custom.html

const useApi = (method, endpoint, params) => {

  const [response, setResponse] = useState(null);
  const [context, setContext] = useContext(Context);

  const api = axios.create({
    baseURL: `URL`,
    headers: {
      'Authorization': 'Bearer ' + context.user.bearer,
      'Content-Type': 'application/json',
      'Accept': 'application/json',
    }
  });

  useEffect(() => {
    const fetchData = async () => {
      //Just did a GET for this, but you can easily change this to be more universal
      const res = await api.get(endpoint,params);
      setResponse(res);
    };
    fetchData();
  }, [] );

  return response;
}

Then in the component file:

import { useApi } from './../../../../Utilities/Hooks/use-api.js';

/* ..... */
  const something= useApi(
    'get',
    'something/',
    {params: {foo: bar}},
  );

  /* .... */
   useEffect( () => {

    if (something){
      // Do something with the API call data you get back here
    }

 },[something]);


text:
Q: expose VPN IP to External IP I have setup a VPN on a windows server 2012, I have several machines at multiple locations, (ie: laptop/workstation etc..).
What I need is to be able to connect to the VPN from anywhere and would be able to access the http/mysql/ssh through the external ip's.
My VPN connects just fine but i have no idea how to routes traffic/ports in/out from the external ip to the internal VPN IP.


text:
Q: Regex to capture: word {word} word I'm trying to capture: word {word} word.
I have the following regex: \S*\s\{.*?\}\S[^{\s]*
It actually captures this pattern, but it also captures word {word}. See: https://regex101.com/r/yI64KQ/6
How to fix it to only capture: word {word} word ?
Thank you very much in advance for all the people who help.

A: Here you go: \w+\s+\{\w+\}\s+\w+
See explanation at regex101...

Here you can visualize your regular expression...

A: If I understand the problem right, we wish to capture the three words, which we can start with an expression similar to:
^(.+?)(\s+)?({(.*)?\})?(\s+)?(.+?)?$

Demo

A: [RESOLVED]
Thanks to Norbert Incze, final regex is: ([A-zÀ-ú]+([^\S\n]+\{[^}]*\}[^\S\n]+[A-zÀ-ú]+)+)
This worked perfectly! Thanks to everyone who helped me.


text:
Q: Full text search returns different results on test and live I will try to explain this issue as properly as I can. It's really weird in my mind, hopefully  some of you guys have an idea of what might be wrong.
I have built a website with a search function, which uses full text search in MySQL, and searches in a table that is a dictionary.
I have set ft_min_word_len = 1 and ft_stopword_file = "" on both my test (windows xampp) and live (ubuntu 12.04) server.
Now, on my localhost test server if I search for example the word "hello", it returns around 20 entries from my dictionary. If I search for "hello" (same) on my live server, no results get returned.
However, if I search for example the word "kyuu" (japanese word) on my test server, I get around 50 results. On my live server I get 2 results.
So this means that it does search and it does return some results sometimes. There's just something very weird with the result it grabs on the live server.
Any ideas? It seems almost as if the live server only searches a part of the table or something? Or it runs out of memory and quits in the middle of the search or something? I don't know...
Thank you in advance.

A: Not an answer but suggestion:
do u have the exact indexes and table setup on the live server? Even a variation in encoding can throw it off.. Maybe you should run the table repair quick option
MySql Repair Table


text:
Q: Shadow in UIPageViewController Can anyone tell me, how to make shadow, using UIPageViewController, around of my background image instead of the view bounds?
In other words, I have an "irregular background image" which bounds looks like a wave. And when I go from page to page, shadow must be around "waves of backgrounds image" instead of pages rectangle.
Thanks.

A: You can use the QuartzCore.framework.
Every UIView has a CALayer which can help u on that

*

*Add QuartzCore.framework to ur project (Build Phase => Link Binary With Libraries)

*#import "QuartzCore/QuartzCore.h" to the file that u will make shadow

Then you can do something like:
- (void) stylingUIView:(UIView *) _view
{
    [_view.layer setBorderWidth:3]; // add border to the UIView
    [_view.layer setBorderColor:[UIColor colorWithRed:0.7f green:0.7f blue:0.7f alpha:0.2].CGColor]; // set border Color for the UIView
    [_view.layer setShadowColor:[UIColor blackColor].CGColor]; //set shadow color for the UIView
    [_view.layer setShadowRadius:10]; // set Shadow radius
}

For your case:
You can do something like:
[(UIViewController) viewController.view.layer setShadowRadius:10];
[(UIImageView) *imageView setShadowRadius:10];


text:
Q: switch between left and right alignment in multiline equation I would like to typeset an equation, with multiple equalities and long terms.
Each equals sign should be left-aligned on a new line. But leftover terms that flow to a new line should be right-aligned.
Here's a minimal example, I've used alignment symbols to position the parts of the equation:
\begin{align*}
  &p_{very\;long\;function}(x) =&& \\
  &&\int f_{very \; long \; integral \; terms}(x)&\\
  &&\mathcal{N}(x; 0, \sigma^2) dx&\\
  &= 2&&
\end{align*}

The result looks like this:

The alignment pushes the equation apart. It does left- and right- align it, but the individual columns can't overlap. So it's not the same as just flowing the lines left and right.
What I would like to get is this:

In the image above, the equation is as wide as the widest line. And individual lines are left or right-aligned.
I've searched for related questions, on how to configure alignment. There are many similar questions, but none of them seem to answer my problem:

*

*Aligning equations with text with alignat

*https://stackoverflow.com/questions/62330024/latex-alignat-syntax

*Aligning equations across multiple lines with proper \left( and \right)

*Aligning equations with left and right comment
UPDATE:
To clarify my question: The document is in two-column mode. That's why I need a compact way to typeset my equations.
Here is an example equation with 4 lines. The first and last should be left-bound. The second one determines the width of the equation, the third one should be right-bound.
I think the key problem is that align and alignat columns may not overlap.
The code is this:
\begin{align*}
  &p_{long \; function}(x) =\\
  & \int f_{many\; very \; long \; integral \; terms}(x)\\
  &\mathcal{N}(x; 0, \sigma^2) dx\\
  &= 2
\end{align*}

It should look like this:

A: I supposed you're in two-column mode, and, if I understand well your requirements, they can be satisfied with an aligned environment nested in the outer align* (with a single alignment column). However, I also propose another solution, based on multlined:
\documentclass[twocolumn]{article}
\usepackage{mathtools}

\begin{document}

\begin{align*}
  & p_\text{very\;long\;function}(x) = \\
  & \phantom{{}={}} \begin{aligned}[t]\int f_\text{very long integral terms}(x)\\
 \mathcal{N}(x; 0, \sigma^2)\, dx
 \end{aligned}\\
  & = 2
\end{align*}

\begin{align*}
  & p_\text{very\;long\;function}(x) \\
  & = \begin{multlined}[t]\int f_\text{very long integral terms}(x)\\
 \mathcal{N}(x; 0, \sigma^2)\, dx
 \end{multlined}\\
  & = 2
\end{align*}

\end{document}

A: You have to properly align your equation:
\documentclass{article}
\usepackage{amsmath}

\begin{document}

\begin{align*}
  p_{\text{very long function}}(x) &= &\\
  \int f_{\text{very long integral terms}}(x)&\\
  \mathcal{N}(x; 0, \sigma^2) dx &\\
  &= 2 &
\end{align*}

\begin{alignat*}{3}
  &p_{\text{very long function}}(x) =\\
  &\int f_{\text{very long integral terms}}(x)&\\
  &\mathcal{N}(x; 0, \sigma^2) dx&&\\
  &= 2
\end{alignat*}

\end{document}

A: I would write your equation on the following way:
\documentclass{article}
\usepackage{newtxtext,newtxmath}
\usepackage{mathtools}

\begin{document}
\begin{align*}
  p_{A}(x)  & = \int f_{B}(x) \mathcal{N}(x; 0, \sigma^2)\, dx  \\
            & = 2
\shortintertext{where are}
        A   & = \text{very long function} \\
        B   & = \text{very long integral terms} \\
\end{align*}

\end{document}

A: In case you're working with IEEE styles, there also the IEEEeqnarray, which allows you to specify a different alignment for each column.
Here is an example:
\begin{IEEEeqnarray*}{llr}
  p(x) &=& \int f_{many\; very \; long \; integral \; terms}(x)\\
  &&\mathcal{N}(x; 0, \sigma^2) dx\\
  &= 2&
\end{IEEEeqnarray*}

which renders:

Please note that strictly speaking, this does not completely solve my question.
It's a convenient way to switch between left and right alignment, but individual columns still can't overlap. The rendered output only looks good, because I shortened the length of p(x).


text:
Q: Estimating bandwidth from PerformanceEntry API So I have read a few articles now about how if you have an image of a known size and then you time how long it takes to download that image, you can infer connection-speed/bandwidth.
My thought is, why not use the data from window.performance.getEntries() and take the total transferSize / total duration as the sample size would be much greater and I wouldn't have to instrument any of my own timing or inject any extra arbitrary images as measurement fodder.
Here is what I have done so far just to proof it out.
First I get all the entries with type, size, and duration in tabular-esque format.
window.performance.getEntries().map(i => i.initiatorType + '   ' + i.transferSize + '  ' + i.duration );

Then I copy and paste it into notepad++ to do a little regex to clean it up before I stuff it in a spreadsheet.
^\d*:\s"(\w*\s\w*\s[\w\.]*)"

From here I am able to paste into Excel.
I am filtering out undefined & navigation initiatorType, and 0 for both transferSize & duration.

And a few calculated columns just to get everything into the correct Units.

*

*transferSize in MB =(B3/1000000)

*duration in Seconds =(C3/1000)

*MBps =(D3/E3)

Then I created a PivotChart

Question: Is my math correct? What flaws are there in my logic?
My plan is to codify this, but first I wanted a way to present my logic in a easy to follow layout before I proceed.
Motivation and Sources:
How to detect internet speed in JavaScript?
https://developer.mozilla.org/en-US/docs/Web/API/PerformanceResourceTiming/transferSize
https://developer.mozilla.org/en-US/docs/Web/API/PerformanceServerTiming
https://developer.mozilla.org/en-US/docs/Web/API/PerformanceEntry

A: While its possible to roughly estimate bandwidth this way you will probably have large uncertainity in this measurment.
You are using a large ammount of small files that are potentially loaded in parallel, so you may be measuring transfer time for files sharing the bandwidth between them. Smaller files also tend to give off unreliable results for many reasons.
It would be better to use large file/files like images that can be downloaded while no other network traffic is in play. The longer the measurment the better the results - higher chance to hit a spot when a user is not using his connection for anything else.
This won't be accurate but may give you some idea for profiling purposes if thats what you are going for.


text:
Q: Is there a Special Method for extracting PKZip files with VBA? I'm attempting to use a fairly standard method for pulling emails from Outlook and then extracting Zip files.  The File names and the folder locations are correct.  I wonder if PKZip files (our corporate standard for Zip files) requires a special technique?  Here's my code so far...  It works perfectly up to the point where files are extracted from the Zip files where it fails.  (oApp.Namespace(fDest).CopyHere oApp.Namespace(fDest & Fname).Items)
Sub SaveAttachments()
    Dim ol As Outlook.Application
    Dim ns As Outlook.Namespace
    Dim fol As Outlook.Folder
    Dim i As Object
    Dim mi As Outlook.MailItem
    Dim at As Outlook.Attachment
    Dim Inbox As MAPIFolder
    Dim strDate As String
    Dim oApp As Object
    Dim fDest As String
    Dim fZip As String

    strDate = InputBox("Enter Date in format dd-Mmm-yyyy", "User Date", Format(Now(), "dd-Mmm-yyyy"))

    Set ol = New Outlook.Application
    Set ns = ol.GetNamespace("MAPI")
    Set fol = ns.Folders("GCMNamLogs").Folders("Inbox")

    fDest = "C:\Users\jb76991\Desktop\0_SWPA 50011 CORP Violations\"

    For Each i In fol.Items.Restrict("@SQL=urn:schemas:httpmail:subject LIKE '%" & strDate & "%'")

        If i.Class = olMail Then
            Set mi = i
            For Each at In mi.Attachments
                If InStr(at.Filename, ".zip") > 0 Then
                    If InStr(mi.Subject, "Daily SWPA swpaViolRPT REPORT for DOMAIN:CORP") > 0 Then
                        'Set oApp = CreateObject("Shell.Application")
                        FileNameFolder = fDest
                        Fname = at.Filename
                        at.SaveAsFile fDest & Fname
                        Set oApp = CreateObject("Shell.Application")
                        Debug.Print fDest & Fname
                        oApp.Namespace(fDest).CopyHere oApp.Namespace(fDest & Fname).Items
                        Application.Wait (Now + TimeValue("0:00:02"))
                    End If
                    If InStr(mi.Subject, "Daily SWPA swpaViolRPT REPORT for DOMAIN:INFRA") > 0 Then
                        Set oApp = CreateObject("Shell.Application")
                        FileNameFolder = fDest
                        Fname = at.Filename
                        at.SaveAsFile fDest & Fname
                        Debug.Print fDest & Fname
                        oApp.Namespace(fDest).CopyHere oApp.Namespace(fDest & Fname).Items
                        Application.Wait (Now + TimeValue("0:00:01"))
                    End If
                    If InStr(mi.Subject, "Daily SWPA swpaSumRPT REPORT for DOMAIN:CORP") > 0 Then
                        Set oApp = CreateObject("Shell.Application")
                        FileNameFolder = fDest
                        Fname = at.Filename
                        at.SaveAsFile fDest & Fname
                        Debug.Print fDest & Fname
                        oApp.Namespace(fDest).CopyHere oApp.Namespace(fDest & Fname).Items
                        Application.Wait (Now + TimeValue("0:00:01"))
                    End If
                    If InStr(mi.Subject, "Daily SWPA swpaSumRPT REPORT for DOMAIN:INFRA") > 0 Then
                        Set oApp = CreateObject("Shell.Application")
                        FileNameFolder = fDest
                        Fname = at.Filename
                        at.SaveAsFile fDest & Fname
                        Debug.Print fDest & Fname
                        oApp.Namespace(fDest).CopyHere oApp.Namespace(fDest & Fname).Items
                        Application.Wait (Now + TimeValue("0:00:01"))
                    End If

                End If
            Next at
        End If
    Next i
    MsgBox ("Done")

End Sub

A: The string/variant is the fix, but you'd also benefit from reducing the repetition in the code
(untested)
Sub SaveAttachments()
    Dim ol As Outlook.Application
    Dim ns As Outlook.Namespace
    Dim fol As Outlook.Folder
    Dim i As Object
    Dim mi As Outlook.MailItem
    Dim at As Outlook.Attachment
    Dim Inbox As MAPIFolder
    Dim strDate As String
    Dim fDest As Variant, FName As Variant, e, arrZips

    strDate = InputBox("Enter Date in format dd-Mmm-yyyy", "User Date", Format(Now(), "dd-Mmm-yyyy"))

    Set ol = New Outlook.Application
    Set ns = ol.GetNamespace("MAPI")
    Set fol = ns.Folders("GCMNamLogs").Folders("Inbox")

    arrZips = Array("Daily SWPA swpaViolRPT REPORT for DOMAIN:CORP", _
                    "Daily SWPA swpaViolRPT REPORT for DOMAIN:INFRA", _
                    "Daily SWPA swpaSumRPT REPORT for DOMAIN:CORP", _
                    "Daily SWPA swpaSumRPT REPORT for DOMAIN:INFRA")

    fDest = "C:\Users\jb76991\Desktop\0_SWPA 50011 CORP Violations\"

    For Each i In fol.items.Restrict("@SQL=urn:schemas:httpmail:subject LIKE '%" & strDate & "%'")
        If i.Class = olMail Then
            Set mi = i
            For Each at In mi.Attachments
                FName = at.Filename
                If InStr(FName, ".zip") > 0 Then
                    For Each e In arrZips
                        If InStr(mi.Subject, e) > 0 Then
                            at.SaveAsFile fDest & FName
                            ExtractZip fDest & FName, fDest, 2
                            Exit For
                        End If
                    Next e
                End If
            Next at
        End If
    Next i
    MsgBox ("Done")
End Sub

Sub ExtractZip(ZipPath, DestFolder, Optional waitsecs As Long = 0)
    Debug.Print "Extracting '" & ZipPath & "' to '" & DestFolder & "'"
    With CreateObject("Shell.Application")
        .Namespace(DestFolder).copyhere .Namespace(ZipPath).items
    End With
    If waitsecs > 0 Then Application.Wait Now + waitsecs / (24 * 60 * 60)
End Sub


text:
Q: How to remove this object from a Swift array? What would be an appropriate command for removing formattedCoordinate from the array? I know a removeObject exists for Objective-C, but how about Swift?
var markersArray: Array<CLLocationCoordinate2D> = []

func mapView(_ mapView: GMSMapView, didTap marker: GMSMarker){
    let lat: CLLocationDegrees = marker.position.latitude
    let lng: CLLocationDegrees = marker.position.longitude
    var formattedCoordinate = CLLocationCoordinate2D(latitude: lat,longitude: lng)
    //markersArray.remove(formattedCoordinate) need to fix this
    self.clean()
    //    return 0; not sure if we need this here
}

func mapView(_ mapView: GMSMapView, didBeginDragging marker: GMSMarker){
    let lat: CLLocationDegrees = marker.position.latitude
    let lng: CLLocationDegrees = marker.position.longitude
    var formattedCoordinate = CLLocationCoordinate2D(latitude: lat,longitude: lng)
    // markersArray.remove(formattedCoordinate) need to fix this
}

A: I would suggest
self.markersArray = self.markersArray.filter({ !(($0.latitude == formattedCoordinate.latitude) && ($0.longitude == formattedCoordinate.longitude)) })


text:
Q: how to keep origin image size in swift ui I am using KFImage to load images from URLs in swift UI, however, I want to keep the width and height that come with the image from the URL they come in different sizes
KFImage(URL(string: egg.logoUrl))
                           .resizable()
                           .fixedSize()

I used jetback compose, and I can say that one of the hardest things in swift Ui, is image scaling that requires geometry rendering wherein compose can do it in single function call


text:
Q: Power Demand for Motion of Vehicle on a Road and Plain in Air with Air Resistance Let's say we have an ideal motorcycle without frictional losses (no tire slip, ideal machine without losses). But we want to consider wind force which is proportional to the square of speed
$F = k \cdot v^2$
The required Power would be
$P = F \cdot v = k \cdot v^3$
Now consider tailwind of velocity w:
$F = k \cdot (v-w)^2$
and the required Power
$P = F \cdot v = k \cdot (v-w)^2v$
Now consider a plain, moving exactly with same speed v against ground and within the same wind above the cycle:
The pilot would (as usual in aviation) argue to move against the packet of air, so his frame of reference is a system, where wind is zero. The relative speed against this "wind system" is (v-w). Wind force is again
$F = k \cdot (v-w)^2$
but his speed against reference system is also v-w. Power demand of the plane would be therefore
$P = F \cdot (v-w) = k \cdot (v-w)^3$
Assuming both cw-values are the same, I would expect also same power requirements. But this is not the case.
Where is the problem in my chain of thoughts? I miss something relevant but cannot identify it.

A: For the no wind situation
$$P=kv^3$$
as derived, however there is a need to be careful what this means...
It means that an engine, that can operate at a power $P$ (i.e. deliver a certain amount of energy per second), could cause the vehicle to reach the maximum speed of $v$.
for both the motorcycle and plane this means that if $F$ is reduced to $$F=k(v-w)^2$$
they could obtain a new greater maximum speed $v'$, from an engine delivering the same power $$P=k(v-w)^2 v' = kv^3$$
so $$v' = \frac{v^3}{(v-w)^2}$$
The energy required for the journey would be lowered to the same value (for both vehicles with the tailwind) and could be found from power multiplied by time
$$E=P\times \frac{d}{v'} = k (v-w)^2d$$
where $d$ is the distance travelled.

A: You just discovered that the work, kinetic energy and power are frame dependent quantities. Your result has nothing to do with the motorcicle versus plane. You just analysed the same motion from two different reference frames and found different results. If you do the same thing for the motorcycle from a reference frame moving with the wind (so the wind velocity is zero) you will find the same formula as for the airplane. Even better, consider two motorcyclists, going next o each other, as they do sometime. From the frame associated with one motorcyclist the velocity of the other is zero so the power associated with any force acting on him is zero.
So the bottom line is that the work, kinetic energy, power depend on the reference frame you use to calculate them. This is a well known fact and is nothing wrong with finding different values in different frames.
Edit after the comment.
Of course the fuel used does not depend on the referenece frame you use to calculate things. But here you don't calculate the fuel used. You calculate the work (and power) done by the resistance force. This is not directly related to the fuel spent at all. Again, it is not plane versus cycle. If you analyse the cycle in the same reference frame as you use for the plane you get the same formula as you have for the plane. Think about this: you can use up a full thank of fuel by starting your engine and leave it in "park" position until all the fuel is burned. The work done by the air resistance is zero but you burned fuel. The same is true if you drive the car (or cycle) and you analyse it from a frame moving with the same speed (a second motorcyclist).


text:
Q: Include padding in size of div Here is an image to explain my problem:

I need the padding to be factored in when the width: 50%; is done.
If I don't, the first div's width will actually be 50% + 2em because the padding had not been accounted for.
How can I count the padding in the width calculation, or is there a workaround for having two equal-sized but padded divs?
Fiddle: http://jsfiddle.net/sMuCY/
Code for testing:

    This div has 50% width, 1em padding, float left

    This is a div with 1em padding

    This div has 50% width and float left

    This is a normal div

A: You can use box-sizing property to change the default behaviour of the box-model:
div {box-sizing: border-box;}

Demo
Another demo to test the difference: http://jsfiddle.net/sMuCY/2/
Reading: http://css-tricks.com/box-sizing/
Alos note, that -moz- preffix is required in Firefox. IE supports this property starting from 8th version.


text:
Q: Long subscript handling I wan to get basically this expression

The problem, if I don't do much, is the big space on the subscript

The best I have been to do is (from where I erase the top part to make the first picture)

I have two problems with this expression; first the vertical line is too big (if I don't use \bigg| it overlaps with the text) and second in the equation environment it gives

which is not what I want.
The code for the three las pictures is
\documentclass{article}

\usepackage{tensor}
\usepackage{mathtools}

\begin{document}
\begin{equation}
(p+q)_\mu\left.\tensor*{\tilde\Gamma}{^\mu_a^\nu_b^\rho_c}\right|_{\text{regulated}} (-p-q,p,q)
\end{equation}

$
(p+q)_\mu\tensor*{\tilde\Gamma}{^\mu_a^\nu_b^\rho_c}\mathop{\bigg|(-p}_{\mathclap{\text{regulated}}} -q,p,q)
$

\begin{equation}
(p+q)_\mu\tensor*{\tilde\Gamma}{^\mu_a^\nu_b^\rho_c}\mathop{\bigg|(-p}_{\mathclap{\text{regulated}}} -q,p,q)
\end{equation}

\end{document}

A: The command \mathclap is a centered overlap which forces you to add (-p. Instead you can use \mathrlap, where the text only overlaps on the right side.
Using this in the subscript of \biggr| leads to
\begin{equation}
  (p+q)_\mu\tensor*{\tilde\Gamma} {^\mu_a^\nu_b^\rho_c}\biggr|_{\mathrlap{\text{regulated}}} (-p-q,p,q)
\end{equation}

This works in display and inline math, but the line is still too big.
The problem is that delimiters are always centered around the math axis in TeX.
If you use LuaTeX, you can use the noaxis flag to fix this:
\documentclass{article}

\usepackage{tensor}
\usepackage{mathtools}

\begin{document}
\begin{equation}
  (p+q)_\mu\left.\tensor*{\tilde\Gamma}{^\mu_a^\nu_b^\rho_c}\Uright noaxis|_{\mathrlap{\text{regulated}}} (-p-q,p,q)
\end{equation}
\end{document}


text:
Q: Rewriting .txt to array by scanner class Materials implements Runnable {
    String path;

    public Materials(String path) {
        this.path = path;
    }

    public int checkSize() throws FileNotFoundException {
        Scanner sc = new Scanner(new File(path));
        int size = 0;
            while(sc.hasNextLine()) size++;
        sc.close();
        return size;
    }

    public void run() {
    try {
        Scanner sc = new Scanner (new File(path));
        int[][] materialsTab = new int[1][checkSize()];
        int x=0, count=0;
        while(sc.hasNext()){
            count++;

            materialsTab[x][0] = sc.nextInt();
            materialsTab[x][1] = sc.nextInt();
            x++;
            System.out.println("Im working!");

            if(count%200 == 0) System.out.println("Creat " + count + " objects");
    }
    sc.close();

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

    }
}

My problem is that I have to rewrite .txt file into an array by thread, then comes the next thread, but I got stuck at the first part of the task.
public int checkSize () is responsible for counting the size of the array, because the text file consists of about 10 000 lines. The whole will look exactly like this:
[Product ID] [Weight]
So I decided to count the number of lines and create just such a table, one place where I keep ID, and next to the weight, because later I will have to count a few things.
In addition, every 200 records must appear in the message. The problem is that after starting this part...  nothing happens.

A: If I'm understanding your problem correctly, try changing Runnable to Callable<int[]> and public void run() to public int[] call() and adding return materialsTab; at the end.

A: Instead of
int[][] materialsTab ...

consider using something roughly like:
List<Point> materialsTab = new ArrayList<Point>();

Point mat = new Point();
mat.x = sc.nextInt();
if (!sc.hasNext())
    break;
mat.y = sc.nextInt();
materialsTab.add(mat);


text:
Q: What is the role of Grand Central Dispatch when implementing multitasking in iOS? I'm a little bit confusing those two concepts when it comes to multitasking implementation. I read that GCD effectively uses all device cores, and also facilitates the work of app developers by making  their apps multithreaded in a simpler way.
So the questions that arise to me are like, is GCD Apple preferred way for implementing multitasking? How does multitasking with GCD differs from multitasking without GCD?


text:
Q: PHP appendChild analog in Smarty My aim is to insert an HMTL element only once in the foreach loop inside Smarty, but insert Children elements as many cycles as foreach loop has. With PHP the working code looks like this:
$counter1 = 0;
foreach ($secCont->getContent() as $row) {
if ($row->getType() == "head") {
    $counter1++;
    if ($counter1 == 1) {
        $theadNode = $html->createElement("thead");
        $tableNode->appendChild($theadNode);
    }
    $tr = $html->createElement("tr");
    $theadNode->appendChild($tr);
    foreach ($row->getContent() as $cell) {
        $thElement = $html->createElement("th");
        $thElement->setAttribute("colspan", $cell->getColspan());
        $thElement->setAttribute("rowspan", $cell->getRowspan());
        $tr->appendChild($thElement);
        foreach ($cell->getContent() as $parInCell) {
            self::paragraphWriting($html, $parInCell, $thElement);
        }
      }
   }
}

But in case of Smarty I have stuck with this:
{assign var="counter1" value=0}
{foreach from=$secCont->getContent() item=row}
    {if $row->getType() == "head"}

        {** capture group for adding inside thead*}
        {capture name="insideTableHead"}

                {foreach from=$row->getContent() item=cell}
                    getColspan()}" rowspan="{$cell->getRowspan}">
                        {foreach from=$cell->getContent() item=parCont}
                            {include file="`$path_template`/paragraph.tpl"}
                        {/foreach}

                {/foreach}

        {/capture}

        {** we need thead only once if exists *}
        {assign var="counter1" value=$counter1+1}
        {if $counter1 == 1}

            {$smarty.capture.insideTableHead}

        {/if}
{/foreach}

The problem is that in capture group the code also is executed only once. Also Smarty version is 2, not 3.

A: Hmm. The answer was so simple, how I missed it?
Problem solved by placing first foreach loop inside {capture}:
{capture name="insideTableHead"}
    {foreach from=$secCont->getContent() item=row}
        {if $row->getType() == "head"}

                {foreach from=$row->getContent() item=cell}
                    getColspan()}" rowspan="{$cell->getRowspan}">
                        {foreach from=$cell->getContent() item=parCont}
                            {include file="`$path_template`/paragraph.tpl"}
                        {/foreach}

                {/foreach}

        {/if}
    {/foreach}
{/capture}

{** we need thead only once if exists *}

{$smarty.capture.insideTableHead}


text:
Q: Comments: Approve when admin Replies, from the Front end Thank you for reading,
In the admin panel, when a comment is awaiting moderation, you can "Approve and Reply" in the same action.
However, in the front end, if you show the awaiting comments to the admin, and she hits Reply, the comment wont approve.
Does anybody know how to get the proper link, or where modify the code, to auto-approve comments when the admin replies ?
Why: I'm creating the site for a client, and trying to make it as easy as posible so she won't need to learn WP's admin panel.

A: Well... All you have to do is to check what hooks are available during comment posting.
The one I think might be helpful is wp_insert_comment. So you could do something like this:
function my_wp_insert_comment($id, $comment) {
    if ( is_admin() && $comment->comment_parent ) {
        if ( wp_get_comment_status( $comment->comment_parent ) == 'unapproved' )
            wp_set_comment_status( $comment->comment_parent, 'approve' );
    }
}
add_action('wp_insert_comment', 'my_wp_insert_comment', 10, 2);

Just place this code in function.php file of your theme. This function will be called every time a comment is inserted into database. No matter how (from admin area, front end or by some plugin, etc.)


text:
Q: PHP spam issues with Gmail and Hotmail I'm having some crazy spam problems with the following code in gMail and Hotmail.. is there something I'm doing wrong from a PHP perspective?
function mail_attachment($filename, $path, $mailto, $from_mail, $from_name, $replyto, $subject, $message) {
$file = $path.$filename;
$file_size = filesize($file);
$handle = fopen($file, "r");
$content = fread($handle, $file_size);
fclose($handle);
$content = chunk_split(base64_encode($content));
$uid = md5(uniqid(time()));
$name = basename($file);
$header = "From: ".$from_name." <".$from_mail.">\r\n";
$header .= "Reply-To: ".$replyto."\r\n";
$header .= "MIME-Version: 1.0\r\n";
$header .= "Content-Type: multipart/mixed; boundary=\"".$uid."\"\r\n\r\n";
$header .= "This is a multi-part message in MIME format.\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-type:text/plain; charset=iso-8859-1\r\n";
$header .= "Content-Transfer-Encoding: 7bit\r\n\r\n";
$header .= $message."\r\n\r\n";
$header .= "--".$uid."\r\n";
$header .= "Content-Type: application/octet-stream; name=\"".$filename."\"\r\n"; // use different content types here
$header .= "Content-Transfer-Encoding: base64\r\n";
$header .= "Content-Disposition: attachment; filename=\"".$filename."\"\r\n\r\n";
$header .= $content."\r\n\r\n";
$header .= "--".$uid."--";
if (mail($mailto, $subject, "", $header)) {
    echo "mail send ... OK"; // or use booleans here
} else {
    echo "mail send ... ERROR!";
}
}
$my_file = "f92ffc796f.jpg";
$my_path = $_SERVER['DOCUMENT_ROOT']."/resources/template/uploads/";
$my_name = "BB Avatar";
$my_mail = "someone@somehwerecom";
$my_replyto = "someone@somehwerecom";
$my_subject = "This is a mail with attachment.";
$my_message = "Hallo,\r\ndo Your download is attached.\r\n\r\";
mail_attachment($my_file, $my_path, $_REQUEST['email'], $my_mail, $my_name, $my_replyto, $my_subject, $my_message);

A: Try using Swift Mailer with proper credentials :)
Also check out:

*

*How to (legitimately) minimize being seen as spam

A: Spam issue because of following reasons
1)Shared hosting
If you are using shared hosting, PHP is not the solutions for this issue.try to contact your server providers.Some time your hosted IP treated as spam.Try to change the hosting providers, It may work fine.
2) More Links in your e-mail body
3 )Partial header(Always use reply-to,Ref Ans:TrentonMcManus)
4) Bulk E-Mailing
5) Spam Reporting(number of people who have clicked on your link as spam)
6) The message not to be too short or too long.
7) Sending From Blacklisted IP(hosting, and SMTP server) )
It may be new your IP address has been previously blacklisted by Google or Hotmail
You can check Blacklisted ip or not from the site from here
8)Verifying sender IP
Sender Policy Framework (SPF) is an email validation system designed to prevent email spam by detecting email spoofing, a common vulnerability, by verifying sender IP addresses.
Perhaps PHP not solutions for this.You can do in php coding following things
1)Always use  the from/reply to address
2)Add  unsubscribe link in body
3)Avoid spam keywords.
4)The message not to be too short or too long.
5)Text version is better than HTML

A: One thing I can see that is going to cause you problems is that:
$my_mail = "someone@somehwerecom";
$my_replyto = "someone@somehwerecom";

Should be:
$my_mail = "someone@somehwere.com";
$my_replyto = "someone@somehwere.com";

If you are sending lots of email from this script, you may be marked as SPAM if you are not complying with the CAN SPAM Act. It may have nothing to do with your php.
I haven't used them, but I talked to some guys from Send Grid, who claimed that their service can help ensure that the email gets delivered properly.


text:
Q: Intellisense not working for remote VSCode window I am encountering this error where intellisense does not work for my python files in my ssh window (accessed with the remote development kit). I have uninstalled and reinstalled. My settings.json file on my remote workstation match my settings.json file on my laptop (where intellisense does work). I have tested to make sure that the correct python interpreter is selected on my ssh machine, and that this python interpreter launches and will run code.
My output window previously showed this error:
Error 2021-04-30 13:53:16: Failed to check if file needs to be fixed [EntryNotFound (FileSystemError): Unable to read file 'vscode-remote://ssh-remote+172.16.214.73/home/jkang/.config/Code/User/settings.json' (Error: Unable to resolve non-existing file 'vscode-remote://ssh-remote+172.16.214.73/home/jkang/.config/Code/User/settings.json')
    at _handleError (/home/jkang/.vscode-server/bin/3c4e3df9e89829dce27b7b5c24508306b151f30d/out/vs/server/remoteExtensionHostProcess.js:86:154942)
    at async y.readText (/home/jkang/.vscode-server/extensions/ms-python.python-2021.4.765268190/out/client/extension.js:9:339523)
    at async p.doesFileNeedToBeFixed (/home/jkang/.vscode-server/extensions/ms-python.python-2021.4.765268190/out/client/extension.js:59:577126)
    at async /home/jkang/.vscode-server/extensions/ms-python.python-2021.4.765268190/out/client/extension.js:59:576253
    at async Promise.all (index 0)
    at async p.getFilesToBeFixed (/home/jkang/.vscode-server/extensions/ms-python.python-2021.4.765268190/out/client/extension.js:59:576199)
    at async p.updateTestSettings (/home/jkang/.vscode-server/extensions/ms-python.python-2021.4.765268190/out/client/extension.js:59:575826)] {
  code: 'FileNotFound'
}

I created this file home/jkang/.config/Code/User/settings.json with content {} in order to satisfy this error. It no longer shows.
Additionally, when I googled this problem some suggested that I run python: build workplace symbols. However, I am not able to and I get the error
Command 'Python: Build Workspace Symbols' resulted in an error (command 'python.buildWorkspaceSymbols' not found)

Can anyone help me? This is very frustrating.


text:
Q: global objects in javascript I have 2 files. 1 html and a js. The html file has check boxes. I'm setting a flag when I select a check box. And this flag has to go in the .js file. Based on whether the flag is set or not, I'll be performing some manipulations in the js file. Basically, how do I do this so that the flag set from the html file is available in the javascript file?
Thank you.
Html file
function checkWIFI(){

if(document.getElementById('wifi').checked == true)

wifiFlag.changeFlag(true);

else

wifiFlag.changeFlag(false);

}

javscript file
wifiFlag = new testFlag();

function testFlag()

{

this.flag = false;

}

testFlag.prototype.changeFlag = function(newFlag)

{

 this.flag = newFlag;

}

A: You can use global variables for this and declare them at the top of the JS file. Whatever you declare under the window, becomes a global variable. In your JS file, add the following line in the top.
window.flag = 0;

And in the checkbox, when you change, set the flag.
<input type="checkbox" name="flag"
       onclick="if (this.checked) window.flag = 1; else window.flag = 0;" />

Now, you can access the flag using window.flag.
if (window.flag == 1)
    // Do something
else
    // Do something

A: In the html you declare a hidden variable
<input type="hidden" id="hidden1" >

and set the value for it
document.getElementById('hidden1').value = '//your returned value';

access the hidden value in your script
var x=document.getElementById("hidden1").value;
alert(x);

hope this will work for you..

A: I would suggest writing the javascript that you have in your .js file in such a way that it can be given the necessary context information. So, write functions or something that you can pass in the checkbox values. This will help keep your code more reusable and will not be tied to the global window. You can initiate this code whenever a checkbox value changes, enumerate the checkbox values and pass them to  your code. I would suggest against using global variables. If you absolutely have to, then namespace them.

A: The safest approach I would suggest is use the data-attribute made available. For example,
<input type="checkbox" name="firstCheckbox" data-flag="old">

This approach allow you to graciously fall back because old browsers won't complain. You don't need extra markup for every checkbox in case you have multiple ones. Using global variables can cause problems and namespace issues. Hidden values is a fine approach as well :)
You can obtain the value of the data attributes using one of 2 ways. 1) getAttribute, the old JavaScript method, you want to grab for data-flag. In jQuery, use attr(), 2) the HTML5 way, which is stored in the .dataset array property, so .dataset['flag'], and the equivalent in jQuery is .data('flag')
Angela


text:
Q: Vector mesons as background gauge fields Suppose we have some complicated fundamental theory of fermions and gauge fields which involves global chiral symmetry and global anomalies which breaks some subgroup of this symmetr. At some energy scale spontaneously symmetry breaking happens, and goldstone bosons arise. We may then write chiral effective lagrangian (usual kinetic terms plus Wess-Zumino term). The problem of such description is that it doesn't contain information about global chiral anomalies. Thus theory have to be consistent if we gauge global subgroups of chiral group which are breaked by anomalies. For doing that we must introduce background gauge fields.
In QCD roles of gauge bosons is taken by vector and axial-vector mesons with spin one.
Why we can treat vector mesons as background gauge fields if they vanish on $\text{GeV}$ scale? What is the motivation of such treatment?