text:
Q: Redux обновляется с задержкой Когда я обновляю Redux через компонент, само хранилище не обновляется мгновенно, а с задержкой. Почему так происходит? Использую react-starter-kit/redux

Сам компонент:
class ArticleList extends Component {
  constructor(props) {
    super(props);

    this.props = props;
  }

  componentWillMount() {
    let { reduxKey, articles, actions } = this.props; // key in redux storage
    this.props.actions.initAll(reduxKey); // init key in redux; to prevent errors
    let store = this.props.store[reduxKey]; // current storage in redux

    // pass mainkey in context also
    this.store = store;

    console.log("inComponent: ", store, this.props.store);
    setTimeout(function () {
      console.log("setTimeout: ", this.props.store, store)
    }.bind(this), 0)
  }

  async load() {
    return await this.props.actions.fetchArticles(this.props.query, this.props.key, this.store.latest + 10);
  }

  render() {
    // ...
  }
}

export default connect(state => ({
    store: state.article
  }),
  (dispatch) => ({
    actions: bindActionCreators(articleActions, dispatch)
  })
)(ArticleList);

Его вызов:

                <ArticleList reduxKey="home" query="filter[tag__not_in]=44" articles={this.props.articles}/>

                <ArticleList reduxKey="recent" query="" articles={[]}/>

                <ArticleList reduxKey="life" query="filter[cat]=6" articles={[]}/>

Reducer:
import { UPDATE_ARTICLE } from '../actions/article';

export default function runtime(state = {}, action) {
  const { type, tag, articles = [], latest = 1, loading = false, max = 999 } = action;

  switch (type) {
    case UPDATE_ARTICLE:
      console.log("State before: ", state);
      let arts = state[tag] ? state[tag] : { articles: [] };

      arts = {
        articles: [
          ...arts.articles,
          ...articles,
        ],
        latest,
        loading,
        max
      };

      console.log("State after: ", state);
      return {
        ...state,
        [tag]: arts
      };
    default:
      return state;
  }
}

Action:
import fetch from '../core/fetch';

export const UPDATE_ARTICLE = "article.update";

export function setArticles(tag, articles, latest, loading, max) {
  return {
    type: UPDATE_ARTICLE,
    tag,
    articles,
    latest,
    loading,
    max
  }
}

export function initAll (tag) {
  return (dispatch) => (dispatch(setArticles(tag, [], 1, false, null)))
}

export function fetchArticles (filter, tag, latest) {
  return async (dispatch) => {
    let page = latest / 10;

    dispatch(setArticles(tag, [], latest, true, null)); // set loading indicator
    const resp = await fetch("http://local.dev/wp-json/wp/v2/posts?fields=categories,date,short,title,id&per_page=10&"+filter + "&page=" + (latest / 10), {
      method: 'get',
      headers: {
        Accept: 'application/json'
      },
      credentials: 'include',
    })

    const data = await resp.json();

    dispatch(setArticles(tag, data, latest, false, resp.headers.get("X-WP-Total"))); // dispatch action
    return data;
  }
}


text:
Q: Why does GRASS GIS output HTML files for r.stats when run from QGIS processing toolbox? Running r.stats in GRASS GIS from QGIS has no parameter for output, only one named html. Does anyone know why this is? It doesn't match the documentation https://grass.osgeo.org/grass78/manuals/r.stats.html
Is there any way to persuade r.stats to output a CSV file? It would be much more useful for my purposes. Even if separator is set to comma, and a file with .csv is chosen as the output, it still outputs html format.
 processing.run("grass7:r.stats",
        {'input':[input],
        'separator':'comma',
        'null_value':'*',
        'nsteps':255,
        'sort':0,
        '-1':False,
        '-A':True,
        '-a':True,
        '-c':False,
        '-p':False,
        '-l':True,
        '-g':False,
        '-x':False,
        '-r':False,
        '-n':False,
        '-N':False,
        '-C':False,
        '-i':False,
        'html':output,
        'GRASS_REGION_PARAMETER':None,
        'GRASS_REGION_CELLSIZE_PARAMETER':0})

A: The GRASS GIS module r.stats does not output html. it's quite easy to get the output as CSV by adding the parameter: separator=comma, i.e. (from the nc_spm_basin demo location):
micha@RMS:~$ r.stats -a -A -l slope separator=comma | head
 100%
0.075862,from zero slope to zero slope,2798016.389120
0.227585,from zero slope to zero slope,2459314.405205
0.379308,from zero slope to zero slope,2869916.810270
0.531031,from zero slope to 1 degree,3333719.526952
0.682754,from 1 degree to 1 degree,3757822.011093
0.834477,from 1 degree to 1 degree,4103424.035425
0.9862,from 1 degree to 1 degree,4390325.715925
1.137923,from 1 degree to 1 degree,4701927.541103
1.289646,from 1 degree to 1 degree,4906728.740707
1.44137,from 1 degree to 2 degrees,5138330.097291

Then a simple redirection (... >> stats_output.csv) would save to a file.
From the example in your question, it appears that you are using the QGIS processing framework. You neglected to mention this crucial detail, not in the title, nor the question, nor in the tags. So there's little chance that anyone with knowledge about the QGIS Processing toolbox will answer.  I'd suggest that you either rephrase the question, or ask a new question, indicating how exactly you are running the module.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Exclude a column from being sorted using jQuery tablesorter I am looking for a way to exclude a single column from being sorted using jQuery's tablesorter plugin. Specifically, I have a fairly large table and would like to keep a "row number" column fixed so that it is easy to see what position in the table a particular row is, after sorting.
For example:
#    name
-----------
1    papaya
2    apple
3    strawberry
4    banana

When sorted on the name column, should result in:
#    name
-----------
1    apple
2    banana
3    papaya
4    strawberry

Thanks.

A: Edit: I've made a sample of this technique at http://jsbin.com/igupu4/3. Click any column heading to sort...
While I don't have an answer to your question about jquery, here's an alternate way to get the specific behaviour you described here, fixed row numbers after sorting. (Using CSS, specifically the content property, and counter related properties/functions.)

  <title>test</title>

        Col 1
        Col 2

foo

quuz

        bar
        quux

        baz
        baz

        Rownums
        Col 1
        Col 2
        More Rownums

foo

bar

        quuz
        baz

        fred
        quux

If your browser is sufficiently CSS2.1 compatible, you can use tr:before instead of td:first-child:before in sample 1. (Mozilla only supports this in trunk for now...)
In sample 2, you can see how to position your row-number columns anywhere, not just in the first column.

A: $("table").tablesorter({
    headers: {4: {sorter: false},8: {sorter: false}}
});

A: For those who find this while looking for a way to exclude a column from being sortable (i.e. clickable header on the column), the below example excludes column 4 (zero-indexed) from being sorted):
$("table").tablesorter({
    headers: {4: {sorter: false}}
});

A: This would skip sorting for the first column, and allow it for the second one. Just set true/false for all columns starting with first column as zero.

A: Here is a widget you can use that will accomplish what you are looking for:
$(function() {
    // add new widget called indexFirstColumn
    $.tablesorter.addWidget({
        // give the widget a id
        id: "indexFirstColumn",
        // format is called when the on init and when a sorting has finished
        format: function(table) {
            // loop all tr elements and set the value for the first column
            for(var i=0; i < table.tBodies[0].rows.length; i++) {
                $("tbody tr:eq(" + i + ") td:first",table).html(i+1);
            }
        }
    });

    $("table").tablesorter({
        widgets: ['zebra','indexFirstColumn']
    });

});

A: The answer of Brian Fisher is correct, but it is too slow in large tables (+1600 rows in my example). I improved the way of iterating through every rows. Everything else is the same.
$(function() {
    // add new widget called indexFirstColumn
    $.tablesorter.addWidget({
        // give the widget a id
        id: "indexFirstColumn",
        // format is called when the on init and when a sorting has finished
        format: function(table) {
            // loop all tr elements and set the value for the first column
            $(table).find("tr td:first-child").each(function(index){
                $(this).text(index+1);
            })
        }
    });

    $("table").tablesorter({
        widgets: ['zebra','indexFirstColumn']
    });
});

A: Hrm. From tablesorter's method of reorganizing the table, I'm pretty sure that this isn't entirely possible. Tablesorter pulles each tr out of the DOM one by one and sorts them based on an indexed field, reinserting the entire tr without changing the tr's contents in any way. Your requested solution would then need to iterate back through the table after each sort and re-enumerate the first column. Tablesorter does have a plugin method, which is used by the zebrastripe and other extensions. Perhaps this could be used to hook the sort methods?

A: The answer of Stobor is perfect. The only problem is that needs to wait until the table is rendered completly to put the numbers.
Some observations:

*

*You need to give an empty column for this method put the numbers.

*If you have headers in the table you have to use the tags THEAD and TBODY to let tablesorter to sort only the data in the TBODY section.

*If you have a footer in your tables, you have to let this out of the TBODY section to avoid tablesorter to sort his content, also you have to use tags TH instead TD to avoid numerating the footer.

Note:
The method shown by Abdul only restricts to the user to sort by the indicated columns, but his content is always ordered with the rest of the row when an order by other unrestricted column is selected.

A: Just an update on this question. While the top voted answer is a wonderful solution, the jstablesorter team added this feature so in your html cell add the following attribute:
data-sorter="false"

And that is a seamless way to disable any header from sorting.


text:
Q: Strange errors with stream management in ejabberd I'm building an instant messenger app on iOS that uses ejabberd. I'm currently testing the stream management feature and in particular the resumption that seems to work in most cases. However there is a case I don't understand, that I can replicate through the following steps, taking in account the settings: resume_timeout: 30, resend_on_timeout: if_offline

*

*at the beginning client A and client B are connected, no other resources are connected

*client B crashes or disconnects in a not clean way

*client A starts to send a bunch of messages (10+) very quickly

*ejabberd sends an ack to A for each message sent to confirm that the messages reached the server

*around 20 seconds since the crash, B reconnects. At this instant A receives an error for each message sent before

<message xmlns="jabber:client" from="clientB@mydomain" to="clientA@mydomain/resourceID" type="error" id="CFBF4583-209A-4453-2567-CCCC7894827E">
   <body>test</body>
   <active xmlns="http://jabber.org/protocol/chatstates" />
   <request xmlns="urn:xmpp:receipts" />
   <error code="503" type="cancel">
       <service-unavailable xmlns="urn:ietf:params:xml:ns:xmpp-stanzas" />
   </error>
</message>

I tried with ejabberd 16.01.
This happens 80% of the time; sometimes messages sent by A are correctly delivered to B on reconnection within the 30 seconds.
My questions are:

*

*is this behavior correct? I would expect that no error is bounced to client A if an ack has already been received for a message.

*since resend_on_timeout is set to if_offline and no other resource is connected, I would expect no errors at all. Am I correct?

A: *

*Stream Management acks only indicate that the message has been received by your server. It doesn't imply that the message has been processed or delivered to the specified address. Even if it were delivered to the address, then that device can still return an error for the stanza.

*This is really just a stab in the dark, but after having a glance over the ejabberd code, this could be what happens:

*

*clientB@mydomain/ResourceB drops their connection, there is now a session awaiting resumption using ResourceB.

*Client B reconnects, doesn't resume (because it crashed and lost its state).

*Client B binds resource ResourceB again.

*Now the server has to terminate the sleeping session that was waiting for resumption because client B requested the same resource.

*The server checks whether there are other sessions because it is set to if_offline.

*The server sees there is a session (the new session) and therefore chooses to bounce instead of resend.

So my theory is that if_offline only checks if there are other sessions when queue of unacknowledged messages needs to be handled, not at the time the message was originally received.

A: @xnyhps' response is correct, and I fixed this particular corner case for the next ejabberd release. However, @xnyhps is also correct that there are other corner cases, so if you want reliable message delivery, you should be using XEP-0313. The main feature of XEP-0198 is session resumption.


text:
Q: Is it possible to modify a data.frame in-place (destructively)? It appears that one can add/delete a column to a data.table in-place, i.e., without copying all the other columns over to a new table.
Is it possible to do that with a vanilla data.frame?
PS. I know how to add/delete columns "functionally", i.e., creating a new frame without modifying the original one.

A: You can delete or modify an existing column from a data.frame by reference with data.table::set. I doubt you can add a column without making a copy.  The reason that you can add a column to a data.table without making a copy is that data.table over allocates memory.  See ?alloc.col for more.
R> library(data.table)
R> data(mtcars)
R> tracemem(mtcars)
[1] "<0x59fef68>"
R> set(mtcars, j="mpg", value=NULL)        # remove a column
R> set(mtcars, j="cyl", value=rep(42, 32)) # modify a column
R> untracemem(mtcars)
R> str(mtcars)
'data.frame':   32 obs. of  10 variables:
 $ cyl : num  42 42 42 42 42 42 42 42 42 42 ...
 $ disp: num  160 160 108 258 360 ...
 $ hp  : num  110 110 93 110 175 105 245 62 95 123 ...
 $ drat: num  3.9 3.9 3.85 3.08 3.15 2.76 3.21 3.69 3.92 3.92 ...
 $ wt  : num  2.62 2.88 2.32 3.21 3.44 ...
 $ qsec: num  16.5 17 18.6 19.4 17 ...
 $ vs  : num  0 0 1 1 0 1 0 1 1 1 ...
 $ am  : num  1 1 1 0 0 0 0 0 0 0 ...
 $ gear: num  4 4 4 3 3 3 3 4 4 4 ...
 $ carb: num  4 4 1 1 2 1 4 2 2 4 ...

Compare that with normal data.frame operations
R> data(mtcars)
R> tracemem(mtcars)
[1] "<0x6b3ec30>"
R> mtcars[, "mpg"] <- NULL
tracemem[0x6b3ec30 -> 0x84de0c8]:
tracemem[0x84de0c8 -> 0x84de410]: [<-.data.frame [<-
tracemem[0x84de410 -> 0x84de6b0]: [<-.data.frame [<-
R> tracemem(mtcars)
[1] "<0x84dca30>"
R> mtcars[, "cyl"] <- rep(42, 32)
tracemem[0x84dca30 -> 0x84dcc28]:
tracemem[0x84dcc28 -> 0x84dd018]: [<-.data.frame [<-
tracemem[0x84dd018 -> 0x84dff70]: [<-.data.frame [<-
R> untracemem(mtcars)
R> data(mtcars)


text:
Q: One-to-one differentiable function with zero derivative in every neighborhood Is it possible to have a one-to-one, differentiable function $f: (a,b) \to \mathbb{R}$ such that, at some point $c \in (a,b)$, we have $f'(c) = 0$, and every neighborhood of $c$ has a point $d \neq c$ such that $f'(d) = 0$ as well?

A: Let $F(x)=x^{2}\sin^{2}(1/x)$ for $x\ne 0$ and $F(0)=0$.
$F$ is integrable, now we let $f(x)=\int_{0}^{x}F(t)dt$.
Note that $f(x)-f(y)=\int_{y}^{x}F(t)dt>0$ for $x>y$.

A: Yes. As the example by user284331 suggests, just consider any continuous function $F: (a,b) \to \mathbb{R}$ such that:
(1) $F(c) = 0$ for some $c \in (a,b)$.
(2) For every $\delta > 0$, there is $d \in (c-\delta) \cup (c+\delta)$ such that $F(d) = 0$.
(3) $\int_x^y F(t)\,dt > 0$ for every $x, y \in (a,b)$ with $x < y$.
By the fundamental theorem of calculus, $f(x) = \int_c^x F(t)\,dt$ satisfies $f' = F$, and $f$ is one-to-one because $x < y$ implies $f(y) - f(x) = \int_x^y F(t)\,dt > 0$.
Basically, $F$ is a continuous function that is zero at $c$ and at infinitely many points close to $c$, and $F$ has positive integral between any two points. There are many possible examples of such a function $F$.
(E.g. consider $F(x) = |x|g(x)$ at $c = 0$, where $g$ is the "zig-zag" function defined by: $g(0) = 0$; for each $k \in \mathbb{Z}$, $g(1/k) = 0$ if $k$ is even and $g(1/k) = 1$ if $k$ is odd; and in between $1/k, 1/(k+1)$, connect the two points on the graph by a straight line.)


text:
Q: Message: Undefined property: Session::$session I have a problem with my code
I'm doing a shopping cart and when I add a product this is giving error in the session
A PHP Error was encountered
Severity: Notice

Message: Undefined property: Carrinho::$Carrinhocompra

Filename: loja/Carrinho.php

Line Number: 31

Backtrace:

File: C:\Users\Dell\Desktop\loja_virtual_V1.4\application\controllers\loja\Carrinho.php
Line: 31
Function: _error_handler

File: C:\Users\Dell\Desktop\loja_virtual_V1.4\index.php
Line: 315
Function: require_once

aqui esta o codigo

minha library
<?php
    if ( ! defined('BASEPATH')) exit('No direct script access allowed');

    class Carrinhocompra {

        public function __construct(){

            if (!isset($_SESSION['Carrinho'])) {
                $_SESSION['Carrinho'] = [];
            }
        }

        //  ADICIONAR UM PRODUTO Carrinho
        public function add($id, $qtd){

            if ( isset($_SESSION['Carrinho'][$id]) ) {

                $_SESSION['Carrinho'][$id] = $_SESSION['Carrinho'][$id] + $qtd;
            }
            else {
                $_SESSION['Carrinho'][$id] = $qtd;
            }
        }
}

meu controller

<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Carrinho extends CI_Controller {

    public function __construct(){
        parent::__construct();
        $this->load->model('Loja/Loja_model');
        $this->load->library('Carrinhocompra');

    }

    public function index(){
        echo '<pre>';
            print_r($_SESSION['Carrinho']);
        exit;

        $query = $this->Loja_model->getDadosLoja();

        $data['titulo'] = 'Carrinho de compras';
        $data['dados_loja'] = $query;
        $data['categorias'] = $this->Loja_model->getCategoriaLoja();
        $data['redes'] = $this->Loja_model->getRedeSociais();
        $data['view'] = 'loja/carrinho/listar';

        $this->load->view('loja/index', $data);
    }

    public function add(){

        $this->Carrinhocompra->add(1, 5);
    }

}


text:
Q: php array loop with an array loop to find values I have a two-dimensional array $array_userinfo with approx. 21,000 elements. Each element has 'login' in first position and 'email' in the second position. What I need to do is to loop through this array and find any matching 'login' from another $array_usermeetingfolder, which is a one dimensional array with approx. 700 elements.
Here are the two arrays populated:
foreach ($child->children() as $node_principalid) {
array_userinfo[$i][0] = (string) $node_principalid->login;
$array_userinfo[$i][1] = (string) $node_principalid->email;
i++;
}

foreach (.......) {
$endusersconame =  (string) $usermeetingsfoldersco->children()->name;
$array_usermeetingfolder[$j] = $endusersconame;//
 $j++;
}

What is the best/efficient way way to do this? I have a loop like this:
for ($k=0;$k < count($array_userinfo);$k++) {
//tempecho($array_userinfo[$k][0]);//will yield login, such as, 'joeblow'
}

Thanks.

A: One possible solution:
Transform the $array_usermeetingfolder so yuo have an array where the user logins are keys and values are anything. E.g.
$temp = array('joeblow' => 1,
      'someoneelse' => 1,
      ...);

Then in the loop you can just check if the key exists:
if (isset($temp[$array_userinfo[$k][0]]) {
    echo 'Hoozah!';
}

You can also use array_key_exists() instead of the isset. You will have to run some tests which is more efficient.

A: if it is possible you should use the login as an array key, then you can fast access the key and I think you don't need to think about performance. Arrays in PHP are Hashmaps and if you know the key you can access it fast if you have to check the whole array it takes a lot longer. If you can not change it, you should think about creating a data structure from the array to habe this performance increase. Don't know wether it's worth, measure it :)
like:
<?php
foreach($array_userinfo as $info) {
    $checkAgainst[$info[0]] = $info[1];
}

foreach($array_usermeetingfolder as $mail) {
    if(isset($checkAgainst[$mail]) {
        $return[$mail] = $checkAgainst[$mail];
    }
}

// use $return

A: The following should work.
for($i=0;$i <= count($firstarray);$i++)
    {
    for ($j=0;$j <= count($secondarray);$j++)
    {
        while($firstarray[$i][0] == $secondarray[$j])
        {
            echo $firstarray[$i][0]; // or $secondarray[$j]
        }

    }

    }


text:
Q: Facebook Graph API - Page - Scheduled posts not coming back in promotable posts call I'm trying to list all future scheduled posts for a business page but when I request promotable posts as per the documentation graph.facebook.com//promotable_posts its not pulling back unscheduled posts with one exception - directly after I initially create a new scheduled post.
I can't figure out why but this is the only time it will pull back the list and it will only do it for the first request after a new post not subsequent.
Any ideas ?


text:
Q: how to remove shade on compose view? I use compose button in android view, but there is some shade at the bottom. How can I remove it?
    @Composable
fun VisibilityAnimationFAB() {
    var expanded by remember { mutableStateOf(true) }
    FloatingActionButton(
        onClick = { expanded = !expanded },
        modifier = Modifier
    ) {
        Row(Modifier.padding(start = 16.dp, end = 16.dp)) {
            Icon(
                vectorResource(id = R.drawable.ic_twitter),
                Modifier.align(Alignment.CenterVertically)
            )
            AnimatedVisibility(
                expanded,
                modifier = Modifier.align(Alignment.CenterVertically)
            ) {
                androidx.compose.material.Text(modifier = Modifier.padding(start = 8.dp), text = "Tweet")
            }
        }
    }

}

A: You can use the elevation attribute in the FloatingActionButton
FloatingActionButton(
        onClick = { expanded = !expanded },
        modifier = Modifier,
        elevation = FloatingActionButtonDefaults.elevation(0.dp,0.dp)
    ){ /* .. */ }

A: Use the elevation parameter in FloatingActionButton. In material design, elevation is the relative distance between two surfaces along the z-axis. Shadows make differences in surface elevation perceptible. (source)
You have to pass FloatingActionButtonElevation, which can be created using the elevation(...) method.
FloatingActionButton(
  elevation = elevation(
    defaultElevation = 0.dp
    pressedElevation = 0.dp
  ),
  // ...
) {
  // ...
}

A: this code disable all shadows
    FloatingActionButton(
        onClick = { expanded = !expanded },
        modifier = Modifier,
        elevation = null
    )

A: You can write:
FloatingActionButton(
            onClick = {},
            elevation = FloatingActionButtonDefaults.elevation(
                defaultElevation = 0.dp
            )
        )


text:
Q: I installed Xampp on Windows 8. When I try to start MySql in XAMPP control panel I have the following message and MySql does not start
Remove prev. installed and install new than start mysql . but when start next day same facing problem, I already check Skype(Not start)
How to slove problem

A: Run a netstat and see what program on port 3306 (MySQL default) is using. Typically this is Skype or other similar programs.

A: Try to change the port of MySQL. Just go to
config -> Services and Port Setting -> MySQL -> Main Port
It is default 3306 change it to 3308 and try again.


text:
Q: Argument of type 'Object' is not assignable to parameter of type 'Blob | MediaSource' The blob in URL.createObjectURL(blob) gives the error:Argument of type 'Object' is not assignable to parameter of type 'Blob | MediaSource'. Any solution to fixing this?
async downloadPDF(): Promise<void> {
 try{
   this.http.post(environment.pdf_url, { responseType: 'blob'}).subscribe(
     (blob) => {
       const a = document.createElement('a')
       const objectUrl = URL.createObjectURL(blob)
       a.href = objectUrl
       a.download = `xxxxx.pdf`;
       a.click();
       URL.revokeObjectURL(objectUrl);
     }
   )
 } catch (err) {
   console.log(err)
   }

}

A: You are doing a post method and you are missing your body parameter, you are going straight to the options param with your code. Change it to this:
this.http.post(environment.pdf_url, {}, { responseType: 'blob'})


text:
Q: Magento 2 Plugins / Interceptors accessing and modifying $this object I have a plugin that i want to modify functionality of a method within specific class in Magento 2 however am not quite sure on how to access the original object and return the modified data.
Original Method
protected function _initTotals()
{
    $source = $this->getSource();

    $this->_totals = [];
    $this->_totals['subtotal'] = new \Magento\Framework\DataObject(
        ['code' => 'subtotal', 'value' => $source->getSubtotal(), 'label' => __('Subtotal')]
    );

    /**
     * Add shipping
     */
    if (!$source->getIsVirtual() && ((double)$source->getShippingAmount() || $source->getShippingDescription())) {
        $this->_totals['shipping'] = new \Magento\Framework\DataObject(
            [
                'code' => 'shipping',
                'field' => 'shipping_amount',
                'value' => $this->getSource()->getShippingAmount(),
                'label' => __('Shipping & Handling'),
            ]
        );
    }

    /**
     * Add discount
     */
    if ((double)$this->getSource()->getDiscountAmount()) {
        if ($this->getSource()->getDiscountDescription()) {
            $discountLabel = __('Discount (%1)', $source->getDiscountDescription());
        } else {
            $discountLabel = __('Discount');
        }
        $this->_totals['discount'] = new \Magento\Framework\DataObject(
            [
                'code' => 'discount',
                'field' => 'discount_amount',
                'value' => $source->getDiscountAmount(),
                'label' => $discountLabel,
            ]
        );
    }

    $this->_totals['grand_total'] = new \Magento\Framework\DataObject(
        [
            'code' => 'grand_total',
            'field' => 'grand_total',
            'strong' => true,
            'value' => $source->getGrandTotal(),
            'label' => __('Grand Total'),
        ]
    );

    /**
     * Base grandtotal
     */
    if ($this->getOrder()->isCurrencyDifferent()) {
        $this->_totals['base_grandtotal'] = new \Magento\Framework\DataObject(
            [
                'code' => 'base_grandtotal',
                'value' => $this->getOrder()->formatBasePrice($source->getBaseGrandTotal()),
                'label' => __('Grand Total to be Charged'),
                'is_formated' => true,
            ]
        );
    }
    return $this;
}

This i have set to have a plugin to modify functionality of method above with di.xml:
<type name="Magento\Sales\Block\Order\Totals">
    <plugin disabled="false" name="Harrigo_EverDiscountLabel_Plugin_Magento_Sales_Block_Order_Totals" sortOrder="10" type="Harrigo\EverDiscountLabel\Plugin\Magento\Sales\Block\Order\Totals"/>
</type>

Plugin
class Totals
{

    public function after_initTotals(
        \Magento\Sales\Block\Order\Totals $subject,
        $result
    ) {
        if ((double)$subject->getSource()->getDiscountAmount() != 0 OR $subject->getSource()->getDiscountDescription() != null) {
            if ($subject->getSource()->getDiscountDescription()) {
                $discountLabel = __('Offer (%1)', $source->getDiscountDescription());
            } else {
                $discountLabel = __('Offer');
            }
            $subject->_totals['discount'] = new \Magento\Framework\DataObject(
                [
                    'code' => 'discount',
                    'field' => 'discount_amount',
                    'value' => $source->getDiscountAmount(),
                    'label' => $discountLabel,
                ]
            );
        }
        return $subject;
    }
}

Have used $subject instead of $this within the plugin, this does not work for me however. How do I access the $this object within the plugin to add / overwrite $this->_totals['discount'] and return the updated $this object from within the plugin. I have it working fine with a standard preference but would rather use a plugin if possible.

A: I think you should check this before implementing above code.
http://devdocs.magento.com/guides/v2.0/extension-dev-guide/plugins.html
As per devdocs for Magento2 protected functions can not be intercepted so We can not use plugins for that.
May be that is causing issue in your case.
Hope this helps!


text:
Q: Error when opening a new downloaded Office file I download an Office file(eg.Excel,Word) from internet and open it in my local computer. It will raise a error message
"Microsoft Excel cannot open or save any more documents because there is not enough available memory or disk space. [...].".
The file is in protected view if it is downloaded from internet.
Disabling Protected View allows the files to be opened.  But this is not a solution.  We need the protection of Protected View.
Also, my computer has plenty of free hard drive space and RAM.
Anyone has idea on this issue in Office?
I have reinstalled the Office but the problem still exist.

A: Goto file -> right click -> properties
Attributes -> unblock in attribute section


text:
Q: Altium Designer 16 - CurrentDate Special String Format In previous projects, I used the CurrentDate special string, in the format YYYY-MM-DD (see the image below).

Opening the same project on a different installation of Altium, the format has been automatically changed to MM/DD/YYYY. Is there a way to change this format?
I'm unsure if I changed it in the past. If I did, I don't remember where this setting lives, and I can't seem to find it in the Altium documentation. Any help would be really appreciated.

A: It most likely uses your Regional Setting from Windows.


text:
Q: iOS InApp receipt validation and unlock the app I'm validating receipts with the App Store for auto renewing subscription using my own server. And returns status, receipt, latest_receipt, latest_receipt_info, latest_expired_receipt_info, pending_renewal_info and is-retryable in response as mentioned in the Apple documentation. So after getting above response what are the parameters we need to check before unlock the app.

A: First, you should check if receipt status is valid. If the status code returns a value between 21100-21199 (Internal data access error), check is_retyrable flag. Make sure to retry in case the status is a retryable Internal data access error.
You also want to check the latest active receipt. latest_receipt_info includes the list of purchases. You should check end-date of the latest receipt and make sure that it is not in the past
(see https://developer.apple.com/documentation/appstorereceipts/expires_date_ms)


text:
Q: Download files from UIDocumentPicker and wait until download has finished I'm trying to download a file from the
-documentPicker:didPickDocumentAtURL:

method.
I've tried to get the data of the file using
NSData *data = [NSData dataWithContentsOfURL:url];

but it didn't work how I expected, because the UIDocumentPicker fires the -documentPicker:didPickDocumentAtURL: -method before the file is downloaded.
How can I get the NSData from the file when it's downloaded?
Thanks in advance, Fabian.

A: The file actually is downloaded, but you need to use a file coordinator to read the file contents.  Something like this should do:
- (void)documentPicker:(UIDocumentPickerViewController *)controller didPickDocumentAtURL:(NSURL *)url
{
    NSFileCoordinator *coordinator = [[NSFileCoordinator alloc] initWithFilePresenter:nil];
    NSError *error = nil;
    [coordinator coordinateReadingItemAtURL:url options:0 error:&error byAccessor:^(NSURL *newURL) {
        NSData *data = [NSData dataWithContentsOfURL:newURL];
        // Do something
    }];
    if (error) {
        // Do something else
    }
}


text:
Q: What is signal dimension Estimating Unknown Sparsity in Compressed Sensing is a paper about sparse signal. I am just learning the concepts. In the first paragraph, it says that when the number of observation data samples $n$ is less than the signal dimension $p$, then the desired signal $x$ is sparse. I have never come across he term signal dimension. Can somebody please explain what is signal dimension ?

A: Signal dimension is just the dimension of the random variable that is the signal. "Dimension $p$" is a slightly sloppy way of stating the dimension of the support of the random variable is $p$. That is, it's a multivariate signal with $p$ components.

A: The signal dimension $p$ refers to the dimension of the signal. The paper in question specifies that it is working in $R^p$, not ($R^1$) because the author wants to take into account multiple dimensions. For example, if your data is a geographic location, you have dimension $p=3$ because the complete description requires 3 numbers: longitude, latitude and altitude.


text:
Q: is there an R function for consolidating the two columns (min + max) into one "range column"? I realize that my question might have two or three parts to it in total.

gender
MINsal
MAXsal

Man
50000
59999

Woman
20000
24999

Context: I am working with salary range data. My df is salary data. It has a MINsalary and MAXsal attribute. Now I don't know if my target goal is possible, but would like to combine the two columns into one column that somehow stores the data in a range, formatted (min - max). As well as work with it as numeric data. Because I need to order the salary data somehow for my end-goal.
My goal is to ultimately group by gender and plot a histogram to show the values (salary ranges) by gender. Hope that made sense.
I have tried merging the columns together. But the one thing I'm facing issues in is ordering or arranging the new combined merged column. I think the dash in between gets in the way of computing the data into numeric. I understand R syntax for range data is x:x, or 1:30.
Some functions I think are relevant: cut(), cbind(), paste(), as.numeric(), and summary() to see range distribution.
That said, my expected output would be:

gender
salary_range

Man
100000-124999

Woman
25000-29999

Woman
0-999

Man
20000-24999

Woman
15000-19999

Then that would hopefully allow me to group by gender and arrange by salary range (low to high).
my original df:

A: You can use forcats::fct_reorder() to make salary_range a factor with level order based on MINsal:
library(dplyr)
library(forcats)

salary_data %>%
  mutate(
    salary_range = paste0(
      format(MINsal, trim = TRUE),  # format() to prevent scientific notation in result
      "-",
      MAXsal
    ),
    salary_range = fct_reorder(salary_range, MINsal)
  ) %>%
  arrange(gender, salary_data)

# A tibble: 5 × 4
  gender MINsal MAXsal salary_range
  <chr>   <dbl>  <dbl> <fct>
1 Man     20000  24999 20000-24999
2 Man    100000 124999 100000-124999
3 Woman       0    999 0-999
4 Woman   15000  19999 15000-19999
5 Woman   25000  29999 25000-29999


text:
Q: How to make linker fail for undefined references when building shared library in Linux I'm trying to build a shared library in C++ in Ubuntu (which I will load at runtime using dlopen), but I noticed that the shared library builds just fine even if there's some missing dependencies. If I were to build an executable I would get an undefined reference linker error, which is what I would like to see here.
There might be a little too much detail in this example, but I wasn't entirely sure how to pare it down and also make it representative.
Base.h
class Base{
 public:
 virtual void foo()=0;
};

extern "C" {
Base* CreateBase();
}
extern "C" {
void DestroyBase(Base* b);
}

Derived.h
#include "Base.h"

class Derived : public Base {
 public:
 void foo();
};

extern "C" {
Base* CreateBase() {
   return new Derived;
}
}
extern "C" {
void DestroyBase(Base* b) {
   delete b;
}
}

Derived.cc
#include "Derived.h"
#include "OtherClass.h"

#include <iostream>

void Derived::foo(){
  std::cout << "Derived::foo()" << std::endl;
  std::cout << "Calling OtherClass::bar()" << std::endl;
  OtherClass other;
  other.bar();
}

OtherClass.h
class OtherClass{
  public:
  void bar();
};

My command line to build the shared library is
g++ -shared -fPIC -o libtest_dll.so Derived.cc
The problem is that I have no definition of OtherClass::bar() which is called by Derived::foo(), but libtest_dll.so builds without error or warning. It's my understanding that in Visual Studio in Windows if I were to build a DLL out of this code, it would fail to link. How can I get that behavior using g++ in Ubuntu/Linux?
Running g++ 8.3.0-6 on Ubuntu 19.04

A: When I'm building and want to avoid this situation, I compile the library with the options: -Wl,--no-allow-shlib-undefined -Wl,-z,defs
The first option causes the link of the shared library to fail in the situation that a symbol is not defined in the code, when used in combination with the second option, which causes the linker to report the missing symbols.
This works well to prevent missing symbols at run-time by detecting them at link time. I do, however, need to link the .so with all the libraries it uses, as otherwise it will fail to build.
sample (src.c):
#include <math.h>

extern
double share_the_stuff(double val)
{
    return acos(val * val);
}

Build with missing symbol:
gcc -shared -o src.so src.c -Wl,--no-allow-shlib-undefined -Wl,-z,defs
/usr/bin/ld: /tmp/ccFmD5uY.o: in function `share_the_stuff':
src.c:(.text+0x17): undefined reference to `acos'
collect2: error: ld returned 1 exit status

link in libm.so:
gcc -shared -o src.so src.c -Wl,--no-allow-shlib-undefined -Wl,-z,defs -lm

It behaves the same with missing internal symbols.


text:
Q: After Removing Hot Towel SPA Package BundleConfig Does Not Exist in Current Context I am writing my first Single page application and started out with the Hot Towel Template.  However, requirements have changed and I no longer want to use Hot Towel.  So, I removed it using package manager taking care to leave all the other files for existing dependencies.
Unfortunatley, my build thorws the error:
Error   1   The name 'BundleConfig' does not exist in the current context

Global.asax.cs is comprised of:
using System.Web;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;

namespace MMG.Legacy.StudySiteComm.Web
{
// Note: For instructions on enabling IIS6 or IIS7 classic mode,
// visit http://go.microsoft.com/?LinkId=9394801

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
 }
}

How do I resolve this build error?

A: If you're not creating any bundles, then you can just remove the offending line entirely.
The BundleConfig class is not a special class - it's just a standard static class that provides a convenient, single place to add bundles to the System.Web.Optimization.BundleCollection.
If you create a brand-new MVC project using the Visual Studio "basic" MVC project template, you'll see it creates its own BundleConfig file under the App_Start folder.


text:
Q: Why does not the GET resource respond to the request I have developed a project in Spring and I have created a GET service. Whenever I send a GET request from postman to the url localhost:8080/studentsystem2/students, basically nothing happens and the resource is said to be not available. What is going wrong? Why can't it find the resource?
This is the StudentResource class.
package studentsystem2.ikubinfo.resource;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import studentsystem2.ikubinfo.model.StudentModel;
import studentsystem2.ikubinfo.service.StudentService;

@RestController
@RequestMapping(value = "/students", consumes="application/json", produces="application/json")
public class StudentResource {
    @Autowired
    private StudentService studentService;
    public StudentResource () {

    }

    @GetMapping
    public ResponseEntity<List<StudentModel>> getAll() {
        return new ResponseEntity<List<StudentModel>>(studentService.getAll(), HttpStatus.OK);
    }
}

pom.xml
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>2.0.1.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aop -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-logging/commons-logging -->
        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.1.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.2.0.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-commons -->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-commons</artifactId>
            <version>2.2.0.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.modelmapper</groupId>
            <artifactId>modelmapper</artifactId>
            <version>2.3.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.hibernate.javax.persistence/hibernate-jpa-2.1-api -->
        <dependency>
            <groupId>org.hibernate.javax.persistence</groupId>
            <artifactId>hibernate-jpa-2.1-api</artifactId>
            <version>1.0.2.Final</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.postgresql/postgresql -->
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.8</version>
        </dependency>

Here is the application.properties
# DATASOURCE (DataSourceAutoConfiguration & DataSourceProperties)

# JDBC URL of the database.
spring.datasource.url=jdbc:postgresql://localhost:5432/postgres
# Login username of the database.
spring.datasource.username=********
# Login password of the database.
spring.datasource.password=*********

# JPA (JpaBaseConfiguration, HibernateJpaAutoConfiguration)

# DDL mode. This is actually a shortcut for the "hibernate.hbm2ddl.auto" property. Defaults to "create-drop" when using an embedded database and no schema manager was detected. Otherwise, defaults to "none".
spring.jpa.hibernate.ddl-auto=update
# Whether to enable logging of SQL statements.
spring.jpa.show-sql=true

# Hibernate additional native properties to set on the JPA provider.
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.current_session_context_class=thread
spring.jpa.properties.hibernate.format_sql=true

# Fix Postgres JPA Error (Method org.postgresql.jdbc.PgConnection.createClob() is not yet implemented).
spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
server.servlet.context-path=/studentsystem2
management.server.servlet.context-path = /studentsystem2

Here is web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>studentsystem2</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

<servlet>
    <servlet-name>rest</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>rest</servlet-name>
    <url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>


text:
Q: Spacy script running on terminal but throws import error when executed via PHP I am running a Shell script from PHP via
shell_exec("path/to/script path/to/argument");

The same script when executed via terminal, runs perfectly but when executed via PHP it throws the following error:
Traceback (most recent call last):
  File "/home/file1.py", line 9, in <module>
    import spacy
File "/home/myusername/.local/lib/python3.5/site-packages/spacy/__init__.py", line 5, in <module>
from .deprecated import resolve_model_name
File "/home/myusername/.local/lib/python3.5/site-packages/spacy/deprecated.py", line 8, in <module>
from .cli import download
File "/home/myusername/.local/lib/python3.5/site-packages/spacy/cli/__init__.py", line 1, in <module>
from .download import download
File "/home/myusername/.local/lib/python3.5/site-packages/spacy/cli/download.py", line 9, in <module>
from .link import link_package
File "/home/myusername/.local/lib/python3.5/site-packages/spacy/cli/link.py", line 4, in <module>
import pip
File "/usr/lib/python3/dist-packages/pip/__init__.py", line 16, in <module>
from pip.vcs import git, mercurial, subversion, bazaar  # noqa
File "/usr/lib/python3/dist-packages/pip/vcs/subversion.py", line 9, in <module>
from pip.index import Link
File "/usr/lib/python3/dist-packages/pip/index.py", line 30, in <module>
from pip.wheel import Wheel, wheel_ext
File "/usr/lib/python3/dist-packages/pip/wheel.py", line 39, in <module>
from pip._vendor.distlib.scripts import ScriptMaker
File "/usr/share/python-wheels/distlib-0.2.2-py2.py3-none-any.whl/distlib/scripts.py", line 14, in <module>
File "/usr/share/python-wheels/distlib-0.2.2-py2.py3-none-any.whl/distlib/compat.py", line 66, in <module>
ImportError: cannot import name 'HTTPSHandler'

In the above code /home/file1.py is executed in the shell script somewhere.
So basically I think that spacy is not found by python when executed via PHP but is found when executed via terminal.
Kindly suggest a way in which I can solve the problem.
UPDATE
So I tried looking for where Spacy is installed and on the official website, I found that the path can be found by running the following command in terminal.
python -c "import os; import spacy; print(os.path.dirname(spacy.__file__))"

So I did this and on the terminal I got this output :
/home/myusername/.local/lib/python3.5/site-packages/spacy

But when I executed the same via PHP using
echo shell_exec('python3.5 -c "import os; import spacy; print(os.path.dirname(spacy.__file__))" 2>&1');

I got this output:
Traceback (most recent call last):
File "", line 1, in
File "/home/myusername/.local/lib/python3.5/site-packages/spacy/__init__.py", line 5, in
from .deprecated import resolve_model_name
File "/home/myusername/.local/lib/python3.5/site-packages/spacy/deprecated.py", line 8, in
from .cli import download
File "/home/myusername/.local/lib/python3.5/site-packages/spacy/cli/__init__.py", line 1, in
from .download import download
File "/home/myusername/.local/lib/python3.5/site-packages/spacy/cli/download.py", line 9, in
from .link import link_package
File "/home/myusername/.local/lib/python3.5/site-packages/spacy/cli/link.py", line 4, in
import pip
File "/usr/lib/python3/dist-packages/pip/__init__.py", line 16, in
from pip.vcs import git, mercurial, subversion, bazaar # noqa
File "/usr/lib/python3/dist-packages/pip/vcs/subversion.py", line 9, in
from pip.index import Link
File "/usr/lib/python3/dist-packages/pip/index.py", line 30, in
from pip.wheel import Wheel, wheel_ext
File "/usr/lib/python3/dist-packages/pip/wheel.py", line 39, in
from pip._vendor.distlib.scripts import ScriptMaker
File "/usr/share/python-wheels/distlib-0.2.2-py2.py3-none-any.whl/distlib/scripts.py", line 14, in
File "/usr/share/python-wheels/distlib-0.2.2-py2.py3-none-any.whl/distlib/compat.py", line 66, in
ImportError: cannot import name 'HTTPSHandler'


text:
Q: How to align a div centered-below another while keeping them separate divs I am learning CSS and trying to center a div below another. I want them to be separate divs but I can't get it to work despite trying several suggestions such as using: relative, absolute, etc. The first div contains the name XYZ in this case and the image while the second div contains the small red icons. I need to make them separate divs but still, keep them aligned as shown in the image below. Here is a link to my codepen.

Please help me solve this. Thanks.
https://codepen.io/danongu/pen/LYYevMv
HTML

Team

LLLLL

CSS
@media all{a:active,a:hover{outline:0}
img{max-width:100%;height:auto;vertical-align:middle;border:0;-ms-interpolation-mode:bicubic}
@media print{*{text-shadow:none!important;color:#000!important;background:0 0!important;box-shadow:none!important}
a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}
img{page-break-inside:avoid}img{max-width:100%!important}h2,p{orphans:3;widows:3}h2{page-break-after:avoid}}p{margin:0 0 11px}h2{margin:11px 0;font-family:inherit;font-weight:700;line-height:22px;color:inherit;text-shadow:0 1px 0 #fff}h2{font-size:32px;line-height:40px}h2 a:hover{text-decoration:none}@media print{a[href]:after{content:""}}@media (max-width:767px){h2{font-size:25.6px;line-height:25.6px}}}@media all{a:focus{outline:thin dotted #333;outline:thin auto grey;outline-offset:-2px}a{color:#5a5a5a;text-decoration:none}a:focus,a:hover{color:#343434;text-decoration:underline}}h2{font-family:Verdana,Geneva,sans-serif;font-weight:inherit}h2{text-shadow:none}*{-webkit-box-sizing:border-box;box-sizing:border-box}:before{-webkit-box-sizing:border-box;box-sizing:border-box}:after{-webkit-box-sizing:border-box;box-sizing:border-box}img{height:auto}a{text-decoration:none}img{max-width:100%;height:auto}.form-icon.form-loss{background-color:#ef362a}.form-icon.form-loss:hover{background-color:#f27272}a{text-decoration:none;cursor:pointer}a.form-icon{margin:1px;display:inline-block}.form-icon{text-indent:0;background:0 0;border:0 solid transparent;border-radius:6px;color:#fff;line-height:15px;font-weight:700;font-size:10px;opacity:1;width:17px;text-align:center}@media screen and (max-width:700px){.form-icon{width:13.7px}}p{margin:0;padding:0;border:0;font:inherit;vertical-align:baseline}*{-webkit-font-smoothing:antialiased;text-rendering:optimizelegibility;-moz-osx-font-smoothing:grayscale}.bold{font-weight:700}.ac{text-align:center!important}.bold{font-weight:700}a{text-decoration:none}a,div,h2,img,p{margin:0;padding:0;border:0;font-size:100%;font:inherit;vertical-align:baseline}*{-webkit-font-smoothing:antialiased;text-rendering:optimizelegibility;-moz-osx-font-smoothing:grayscale}a:hover{text-decoration:underline}h2{font-size:1.8em;font-weight:700}.black,.black *{color:#222!important}.m0Auto{clear:both;display:block;margin:0 auto}.mt01e{margin-top:.1em!important}.bold{font-weight:700}.ac{text-align:center!important}.hover-none:hover{text-decoration:none!important}.bold{font-weight:700}.col-lg-4{width:33.333333%;float:left;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}.club-image-border{border:1px solid #666;background:#fff;padding:.2em}.club-image-size{width:138px;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box}@media screen and (max-width:1000px){h2{font-size:1.4em}.col-sm-12{width:100%!important;max-width:100%!important}.col-sm-3{width:25%;max-width:25%;float:left}.h2h-team-intro h2{font-size:1em}.h2h-team-intro p{font-size:.9em}.black{color:#111!important}}img{vertical-align:text-bottom!important}

A: you should move the div contains little icons in to the div with class "h2h-team-intro" :

Team

       L
       L
       L
       L
       L

and add this css:
.currform {
   text-align: center;
}
.currform > a.form-icon {
   // style your icon
}

and you dont need "&nbsp" for space. you can manage space with margin.


text:
Q: Tikz-qtree label alignment issue Is there anyway I can obtain that those labels get correct vertical alignment ?
\documentclass{article}
\usepackage{tikz}
\usepackage{tikz-qtree}

\tikzset{every tree node/.style={align=center, anchor=north}} % Allows including labels as parts of the terminal node, by using \\.

\begin{document}
\tikzset{level 2/.style={level distance=50pt}}
\Tree
    [.Manners [.{Eventualities\\{[}+ quantized{]}}
        [.{Events\\{[}+ dynamic{]}} ][.{Stages\\{[}-- dynamic{]}} ] ][.{Tropes\\{[}-- quantized{]}}
            [.Results ][.Qualities ] ] ]

\end{document}

A: I have just discovered forest and it appears to be a far superior package.
\documentclass{article}
\usepackage[linguistics]{forest}

\begin{document}

    \begin{forest}
        [Manners
           [Eventualities\\{[}+ quantized{]}
            [Events\\{[}+ dynamic{]}][Stages\\{[}-- dynamic{]}]]
        [Tropes\\ {[}-- quantized{]}
           [Results][Qualities]]]
    \end{forest}

\end{document}


text:
Q: Objective C: Boolean not working. Need outside opinion When the user touches the screen, it looks at the boolean with an if and triggers a timer when value is NO. It sets it to YES so the user can't trigger it again when it's going. When the timer finishes what it's doing, it sets it back to NO. The value is initialized in the viewDidLoad method. It works once, but will not work again. From the way things look, it SHOULD work. Can anyone see what's wrong with this:
 - (void) fireLoop {

    fireImage.hidden = 0;
    fireImage.center = CGPointMake(fireImage.center.x, fireImage.center.y - 20);
    if (fireImage.center.y == -5) {
        [fireTimer invalidate];
        fireImage.hidden = 1;
        firedOn = NO;
    }
}

- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {

if (firedOn == NO) {
    firedOn = YES;
     //set fire image position to player position
    fireImage.center = CGPointMake(playerImage.center.x, playerImage.center.y);
    fireTimer = [NSTimer scheduledTimerWithTimeInterval:1.0/30 target:self selector:@selector(fireLoop) userInfo:nil repeats:YES];
}
}

A: You reset firedOn variable only if fireImage.center.y is exactly -5 - check if that it is really so. If not - you probably need to tweak that condition (check if y is less then -5 for example or if it lies in some interval instead of 1 exact value)


text:
Q: Toggle do JQuery não funciona Eu estou utilizando a função toggle do jQuery, está funcionando perfeitamente, porém eu coloquei 12 divs com texto e quando eu clico em abrir somente uma, todas estão abrindo.
Segue o código do JavaScript:

O que eu quero é o seguinte, quando eu clicar em uma div, vai expandir o texto somente dela e quando eu abrir a outra div com outra informação de texto, vai fechar a anterior e abrir somente essa.
O que está acontecendo é que ao clicar no botão para abrir o texto, abre todas as div, ou seja, o toggle está pegando em todas.

A: Você pode pegar o índice da classe da seta clicada e aplicar o .toggle no respectivo índice da classe .perguntas-conteudo, já que cada seta corresponde a um p, então cada índice da classe da seta .seta-baixo corresponde ao mesmo índice da classe do p .perguntas-conteudo:

$(document).ready(function(){
    $("span.seta-baixo").click(function(){
        // pega o índice da seta clicada dentro da classe
        var idx = $(this).index(".seta-baixo");
        // pega o respectivo
 pelo índice usando :eq
        var per = $("p.perguntas-conteudo:eq("+idx+")");
        // oculta todos os
 visíveis exceto o relacionado à seta clicada
        $("p.perguntas-conteudo:visible").not(per).hide();
        // abre ou esconde o respectivo
 da seta
        per.toggle();
    });
});
.seta-baixo{
   display: block;
}

.perguntas-conteudo{
   display: none;
}

   Seta 1

pergunta 1

   Seta 2

pergunta 2


text:
Q: awk: split datetime column into three separate columns in a csv I am trying to use substr to split a datetime column, the fifth one (previous_test) into three different ones at the end.
Input:
id,tester,company,chief,previous_test,test,date,result,cost
6582983b-61d4-4371-912d-bbc76bb8208b,Audrey Feest,Pagac-Gorczany,Claudine Moakson,18/02/2019,Passwords,20/05/2020,none,£11897.96

Expected Output:
id,tester,company,chief,previous_test,test,date,result,cost,day,month,year
6582983b-61d4-4371-912d-bbc76bb8208b,Audrey Feest,Pagac-Gorczany,Claudine Moakson,18/02/2019,Passwords,20/05/2020,none,£11897.96,18,02,2019

I've tried using:
awk -F, -v OFS="," '{s = substr($5, 1, 2)} {g = substr($5, 4, 2)} {l = substr($5, 7, 4)} {print s, g, l}' file.csv

And all I get is only the date separated by commas, but not as three additional columns appended to the existing columns.
I am missing how to append the output into three separate columns.

A: Your code prints only the substring values that are intended for the new columns, not the existing columns.
You need a special handling for the first line.
awk -F, -v OFS="," 'NR==1 { print $0,"day,month,year"; next }
{ s = substr($5, 1, 2);
  g = substr($5, 4, 2);
  l = substr($5, 7, 4);
  print $0, s, g, l}' file.csv

prints
id,tester,company,chief,previous_test,test,date,result,cost,day,month,year
6582983b-61d4-4371-912d-bbc76bb8208b,Audrey Feest,Pagac-Gorczany,Claudine Moakson,18/02/2019,Passwords,20/05/2020,none,£11897.96,18,02,2019

Explanation:

*

*The condition NR==1 is valid for the first record/line.

*$0 is the whole input record/line

*The next command jumps to the next record/line and skips all remaining commands for the current record/line. This means the other commands will be executed for all records/lines except the first one.

Edit: As suggested in a comment by Olivier Dulac, the splitting of the date string can be simplified with the split function.
awk -F, -v OFS="," 'NR==1 { print $0,"day,month,year"; next }
{ split($5,a,"/"); print $0, a[1], a[2], a[3] }' file.csv

A: You don't need to split $5, just change the /s to ,s then print it. With GNU awk for gensub():
$ awk -F, '{print $0 FS (NR>1 ? gensub("/",FS,"g",$5) : "day,month,year") }' file
id,tester,company,chief,previous_test,test,date,result,cost,day,month,year
6582983b-61d4-4371-912d-bbc76bb8208b,Audrey Feest,Pagac-Gorczany,Claudine Moakson,18/02/2019,Passwords,20/05/2020,none,£11897.96,18,02,2019

With any awk:
$ awk -F, '{d=$5; gsub("/",FS,d); print $0 FS (NR>1 ? d : "day,month,year") }' file
id,tester,company,chief,previous_test,test,date,result,cost,day,month,year
6582983b-61d4-4371-912d-bbc76bb8208b,Audrey Feest,Pagac-Gorczany,Claudine Moakson,18/02/2019,Passwords,20/05/2020,none,£11897.96,18,02,2019

A: Done by below command
 awk -F "," 'NR==1{print $0",day,month,year"}NR == 2{print $0","substr($5,1,2)","substr($5,4,2)","substr($5,7,4)}' file

output
id,tester,company,chief,previous_test,test,date,result,cost,day,month,year
6582983b-61d4-4371-912d-bbc76bb8208b,Audrey Feest,Pagac-Gorczany,Claudine Moakson,18/02/2019,Passwords,20/05/2020,none,£11897.96,18,02,2019


text:
Q: Running a Windows Forms app. from a service I have a strange application in that for development and testing I need a windows forms application so that I can monitor what it is doing. For production, the application will be started from a service and no visible UI is needed. I dont really want to re-write the app. once it is completed into a console app so I would like to leave it as it but start it from the service.
My question is will this application work fine from a service? At the moment it has UI elements and I have been able to successfully start the application from a service using the Process class (System.Diagnostics).
Could anything go wrong with this approach?

A: Use the configuration manager to create a gui build and a service build for your application and then use the following structure to control the way your application starts:
#ifdef GUI
  // load gui
#else
  // run as service
#endif

A: I think generally the way this is usually done is to have a separate GUI application that communicates to the service in some way.

A: I think there is no issue.
If the application is a console app, you could have controlled the visibility using a configuration only. Now, you need to have another application (Winform) to do the same thing.

A: If your logic is in a seperate library and your GUI application is just calling to this, then it should be trivial to also have a console application doing the same thing.  You only change your logic in one place, and have two front ends...

A: You will need to tweak the value of Type field in registry SYSTEM\CurrentControlSet\Services\YourServiceName registry location. See this article.
Just as a side note; services aren't meant to work like that - they're meant to be entirely in the background.
Better would be to expose some sort of external control API, probably over network sockets for instance. And then you can have a separate windows forms app running in the system tray or in Hide mode and pops up every time the it receives something from the service.


text:
Q: Boxplot with ggplot2 in R I have a dataframe called cells, with cells in rows and samples in columns, here is a dput sample:
structure(c(8.10937548981953e-20, 0.095381661829093, 0.054868371418562,
0.0523687378840825, 0.0100173293159538, 0.0332395245437795, 3.37811149975583e-20,
0.048191378909587, 0.13314908462763, 0, 0.00612878313809124,
0, 0.00209460699328093, 0.205599458004829, 0.318048653115709,
4.21796249339787e-05, 0.00844407692255898, 0, 0.00613007026042523,
0.0300024082993193, 0.0405191646567986, 0.00654087887823056,
0.0111094954094255, 1.30617589099212e-19, 0.0398730537850546,
0.0390946117756341, 0.239413780024853, 2.07521807718399e-19,
0.00116980239850497, 0, 0, 0.00971921247886335, 0.0588607291731613,
3.8563512241696e-21, 0.00247621905821516, 0), .Dim = c(6L, 6L
), .Dimnames = list(c("Adipocytes", "B-cells", "Basophils", "CD4+ memory T-cells",
"CD4+ naive T-cells", "CD4+ T-cells"), c("Pt1", "Pt10", "Pt103",
"Pt106", "Pt11", "Pt17")))

number of rows in cells is 38 and number of columns is 49.
My target cell type that I want to build a boxplot for is: CD4+ memory T-cells
In addition, have another data frame called Metadata, which contains the response column, if a sample responded to a certain therapy or not - Metadata$Benefit. So for each sample in cells I can know whether they responded or not.
Goal: make a boxplot with Response/No Response in the x axis and values on the y axis, and I need the boxplot with the indiviudal data points on it.
My code:
cells %>%
  ggplot( aes(x = as.factor(Metadata$Benefit), y = as.numeric(cells['CD4+ memory T-cells',]), fill= c('red','lightblue'))) +
  geom_boxplot() +
  scale_fill_viridis(discrete = TRUE, alpha=0.6) +
  geom_jitter(color="black", size=0.4, alpha=0.9) +
  theme_ipsum() +
  theme(
    legend.position="none",
    plot.title = element_text(size=11)
  ) +
  ggtitle("A boxplot with jitter") +
  xlab("")

Error: Aesthetics must be either length 1 or the same as the data (38): x, y and fill
I don't get what's the problem because both length(as.factor(Metadata$Benefit)) and length(as.numeric(cells['CD4+ memory T-cells',])) is 49, it's the same so what's the problem?

A: There are a few issues with your attempt here as mentioned in the comments. You can't take x and y aesthetics from different data sources so you should merge them first. This also means rotating (for which I used t() while it was still a matrix) the original data prior to merging so each sample is a row. To demonstrate this I made up some response metadata.
library(tidyverse)

d <- structure(c(8.10937548981953e-20, 0.095381661829093, 0.054868371418562, 0.0523687378840825, 0.0100173293159538, 0.0332395245437795, 3.37811149975583e-20, 0.048191378909587, 0.13314908462763, 0, 0.00612878313809124, 0, 0.00209460699328093, 0.205599458004829, 0.318048653115709, 4.21796249339787e-05, 0.00844407692255898, 0, 0.00613007026042523, 0.0300024082993193, 0.0405191646567986, 0.00654087887823056, 0.0111094954094255, 1.30617589099212e-19, 0.0398730537850546, 0.0390946117756341, 0.239413780024853, 2.07521807718399e-19, 0.00116980239850497, 0, 0, 0.00971921247886335, 0.0588607291731613, 3.8563512241696e-21, 0.00247621905821516, 0), .Dim = c(6L, 6L), .Dimnames = list(c("Adipocytes", "B-cells", "Basophils", "CD4+ memory T-cells", "CD4+ naive T-cells", "CD4+ T-cells"), c("Pt1", "Pt10", "Pt103", "Pt106", "Pt11", "Pt17")))

metadata <- data.frame(sample = c("Pt1", "Pt10", "Pt103", "Pt106", "Pt11", "Pt17"), response = c(T, T, T, F, F, F))

d %>%
  t() %>%
  as.data.frame() %>%
  rownames_to_column("sample") %>%
  right_join(metadata, .) %>%
  ggplot(aes(x = response, y = `CD4+ memory T-cells`)) +
  geom_boxplot(aes(fill = response)) +
  scale_fill_manual(values = c('red','lightblue'))
#> Joining, by = "sample"

Created on 2022-02-16 by the reprex package (v2.0.1)


text:
Q: Ubuntu 16.04 wifi button not turning on I just installed Ubuntu 16.04 on a Compaq Presario CQ57 laptop (came out around 2012). The machine has a Realtek RTL8188CE wifi adapter. It's still going strong! However, now that I've switched to Ubuntu the wifi is not working. The wifi discovery button on the keyboard is always red, even if I press it. And when I turn on "Enable Wi-Fi" in the network settings under Wi-Fi Networks "Wi-Fi is disabled" is shown in grey. I'm stumped.
UPDATE: I just got a USB wifi adapter to try. The laptop recognizes it, but won't let me turn it on via command line or GUI. In the GUI I click the on/off switch to "on" and it instantly returns to "off". So strange.
First I followed all the suggestions on this similar question post Can't view Wifi networks after upgrading to Ubuntu 16.04.
Output of iwconfig:
lo    no wireless extensions.

wlo1  IEEE 802.11bgn ESSID:off/any
      Mode:Managed Access Point: Not-Associated Tx-Power=off
      Retry short limit:7  RTS thr=2347 B  Fragment thr:off
      Power Management:on

eno1  no wireless extensions.

Output of iwlist scan:
lo    Interface doesn't support scanning.

wlo1  Failed to read scan data : Network is down

eno1  Interface doesn't support scanning.

After service network-manager restart, ethernet disconnected but still could not activate wifi.
Output of sudo rfkill list:
0: phy0: Wireless LAN
         Soft blocked: no
         Hard blocked: yes

1: hp-wifi: Wireless LAN
            Soft blocked: yes
            Hard blocked: yes

So then I tried:
sudo ifconfig wlp4s0 up
service network-manager restart

wifi is still disabled...
I then went into the BIOs and could not find Secure Boot (to turn it off). I did find Boot Order, and enabled the Network Adapter to power on at boot.
bcmwl-kernel-source
sudo apt-get purge bcmwl-kernel-source
sudo apt-get install linux-generic bcmwl-kernel-source
reboot

EDIT: I purged bcmwl-kernel-source by recommendation.
I followed the similar AskUbuntu question over here Wireless not working on Toshiba Satellite C55-A5281 answer by @chili555, and installed some headers with sudo apt-get install linux-headers-generic build-essential, all of which were already installed and up to date. Then I downloaded a backport from 07/30/2013 and unzipped it.
Output of make defconfig-rtlwifi:
Generating local configuration database from kernel....kernel version parse failed!
Makefile:40: recipe for target 'defconfig-rtlwifi' failed
make: ***[defconfig-rtlwifi] Error 1

So now I'm stuck again. Should I download another backport or try something else?


text:
Q: Tomcat security realm per session or per request? I am looking into the security model of Tomcat and have a question regarding when security realms come into effect.  I have secured a portion of my web app:
<security-constraint>
  <display-name>My Realm</display-name>
    <web-resource-collection>
      <web-resource-name>MyServices</web-resource-name>
      <url-pattern>/service/*</url-pattern>
    </web-resource-collection>
  <auth-constraint>
    <description>AUser</description>
    <role-name>AUser</role-name>
  </auth-constraint>
</security-constraint>

and have configured this web app to use JDBCRealm.
I have an initial Filter defined where getSession() is invoked, and thus a cookie is returned to the client's browser during the response.  When the client makes another request, is the security realm bypassed when the cookie is returned (current authenticated session)?  What class makes this decision (to invoke a security realm or not)?  JDBCRealm has no notion of cookies or sessions, and RealmBase looks like it has some cookie logic, but not much.

A: It happens per session if possible, and happens here in AuthenticatorBase


text:
Q: Behavior async await console application vs. WPF I am quite new to async await. I think I understood the example of the console application. When transferring the identical code to the WPF, there is a deadlock and I do not know exactly why.
// All as expected
// Output:
// LongOperationAsync Start
// Before task.Wait();
// LongOperationAsync End
// After task.Wait();
// Result: 4711

class Program {
    public static void Main() {
        Task<int> task = LongOperationAsync();
        //Console.ReadKey();
        Console.WriteLine("Before task.Wait();");
        task.Wait();
        Console.WriteLine("After task.Wait();");
        var result = task.Result;
        Console.WriteLine("Result: {0}", result);
        Console.ReadKey();
    }

    static async Task<int> LongOperationAsync() {
        Console.WriteLine("LongOperationAsync Start");
        await Task.Delay(1000);
        Console.WriteLine("LongOperationAsync End");
        return 4711;
    }
}

and here is the blocking WPF code:
// WPF handler Output:
// LongOperationAsync Start
// Before task.Wait(); => Blocking

private void button2_Click(object sender, EventArgs e) {
    Task<int> task = LongOperationAsync();
    Debug.WriteLine("Before task.Wait();");
    task.Wait();
    Debug.WriteLine("After task.Wait();");
    var result = task.Result;
    Debug.WriteLine("Result: {0}", result);
}

private async Task<int> LongOperationAsync() {
    Debug.WriteLine("LongOperationAsync Start");
    await Task.Delay(1000);
    Debug.WriteLine("LongOperationAsync End");
    return 4711;
}

A: The code blocks in both cases. Both examples are bad. Neither executes asynchronously.
The correct Console code would be :
public static async Task Main()
{
    Console.WriteLine("Before LongOperationAsync");

    int result = await LongOperationAsync();

    Console.WriteLine("After LongOperationAsync");
    Console.WriteLine("Result: {0}", result);
    Console.ReadKey();
}

The equivalent WPF code would be :
private async void button2_Click(object sender, EventArgs e)
{
    Debug.WriteLine("Before LongOperationAsync");

    int result = await LongOperationAsync();

    Debug.WriteLine("After LongOperationAsync");
    Debug.WriteLine("Result: {0}", result);
}

async is syntactic sugar that allows the use of the await keyword. await awaits asynchronously for an already asynchronous operation like Task.Delay() to complete, without blocking the original thread. When that asynchronous operation completes, await resumes execution in the original synchronization context. In the WPF application's case, that's the UI thread. That's what allows updating the UI after an await.
async void is only meant for event handlers, like button2_click. In all other cases async Task should be used. async void methods can't be awaited and the application can't know whether they completed or not.

A: In your example you can modify your button-click to async. Your Task is blocking because you never start him, you can never pass the "wait()" call without starting the task.
Below the modified button click method.
private async void button2_Click(object sender, EventArgs e)
{
    var result = await LongOperationAsync();
    Debug.WriteLine("Result: {0}", result);
}


text:
Q: Boost ptree iteration over two nodes i have an xml like this
<examples>
<example>
<test name="img">testme</test>
<test name="img1">testme1</test>
<test name="img1">testme2</test>
</example>
<example>
<test name="text">testme</test>
<test name="text">testme1</test>
<test name="text">testme2</test>
</example>
</examples>

I tried this code it extracts only first example node
ptree ptree;
        read_xml(doc_path, ptree);

        BOOST_FOREACH(ptree::value_type & value, ptree.get_child("examples.example")){
           cout<<value.second.get("<xmlattr>.name", "")<<endl;
           cout<<value.second.data()<<endl;

}

A: The ptree.equal_range method has the behavior you are looking for.  Note, I've got several pieces of C++11 in there - you'll need a modern compiler.
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <sstream>

const char xml[] = R"(<examples>
<example>
<test name="img">testme</test>
<test name="img1">testme1</test>
<test name="img1">testme2</test>
</example>
<example>
<test name="text">testme</test>
<test name="text">testme1</test>
<test name="text">testme2</test>
</example>
</examples>)";

int main(int argc, char **argv)
{

    boost::property_tree::ptree ptree;
    std::istringstream xml_str(xml);
    read_xml(xml_str, ptree);

    auto example_range = ptree.get_child("examples").equal_range("example");

    for( auto it = example_range.first; it != example_range.second; ++it )
    {
        auto test_range = it->second.equal_range("test");
        for( auto test_it = test_range.first; test_it != test_range.second; ++test_it )
        {
            std::cout << test_it->second.get("<xmlattr>.name","") <<std::endl;
            std::cout << test_it->second.data() << std::endl;
        }
    }

    return 0;
}


text:
Q: How to find the stationary points of $f(x,y)=\cos x \cos y$ for all real numbers? When solving $f(x,y)=\cos x \cos y$ for its critical points, I am not sure how to handle all the values for any integer multiple of pi $\pi
n$ and pi ($2\pi n + \pi$), and even after this, I am not sure how I would be able to classify the points (max, min, saddle) in accordance with the parity of $n$.

A: The conditions $f'_x(a,b)=f'_y(a,b)=0$
give
$$a=n\pi \;,\; b=m\pi $$
or
$$a=\frac {\pi}{2}+n\pi \; ,\; b=\frac {\pi}{2}+m\pi $$
$m,n\in\mathbb Z $.

A: It looks like you've already determined that there are two sets of critical points: those of the form $(m\pi,n\pi)$ and those of the form $\left(\frac\pi2+m\pi,\frac\pi2+n\pi\right)$, both with $m,n\in\mathbb Z$.
The first set is easily disposed of: $f(m\pi,n\pi)=\pm1$, but these are the absolute max/min values of $f$, so these points must also be local maxima/minima as well. There's no other possibility because all of the critical points are isolated.
As for the other set of critical points, it's obvious from the graph of this function that they're saddle points, but we should show this rigorously. The graph suggests that looking at the behavior of the function along lines parallel to $x=y$ and $x=-y$ near these points is instructive. Near the point $\left(\frac\pi2,\frac\pi2\right)$, for $\epsilon\ne0$ We have $\cos(\frac\pi2+\epsilon)\cos(\frac\pi2+\epsilon)=\sin^2t\gt0$ and $\cos\left(\frac\pi2+\epsilon\right)\cos\left(\frac\pi2-\epsilon\right)=-\sin^2\epsilon\lt0$. That is, as we move away from this point $f$ increases in both directions along one line and decreases in both direction along another, so we have a saddle point. The situation is the same at all other critical points in this set, albeit with the signs reversed when $m+n$ is odd.
Alternatively, just as we examine the second derivative of single-variable functions to determine the behavior at critical points, we can consult the function's Hessian matrix, which is the matrix of all of the second-order partial derivatives. For this function $$H(x,y)=\left[\begin{array}{rr}-\cos x\cos y & \sin x\sin y\\ \sin x\sin y & -\cos x\cos y \end{array}\right].$$ If this matrix is positive-definite, we have an isolated local minimum, if negative definite, a maximum. If the matrix is nonsingular and has both positive and negative eigenvalues, then the critical point is a saddle point. $\det H\left(\pm\frac\pi2,\pm\frac\pi2\right)=-1$, which means that one eigenvalue is positive and one negative, so these are saddle points, consistent with what we found above.
Since $H$ is symmetric in $x$ and $y$, we only need to check $H(0,0)$ and $H(\pi,0)$ to determine the nature of the rest of the critical points. $$H(0,0)=\left[\begin{array}{rr}-1 & 0\\ 0 & -1 \end{array}\right]$$ which is obviously negative-definite—a local maximum—and $$H(\pi,0)=\left[\begin{array}{rr}1 & 0 \\ 0 & 1 \end{array}\right]$$ which is positive definite—a local minimum.


text:
Q: Can you play audio directly from a CMSampleBuffer? I have mic audio captured during an ARSession that I wish to pass to another VC and play back after the capture has taken place, but whilst the app is still running (and audio in memory).
The audio is currently captured as a single CMSampleBuffer and accessed through the didOutputAudioSampleBuffer ARSessionDelegate method.
I've worked with audio files and AVAudioPlayer before, but am new to CMSampleBuffer.
Is there a way of taking the raw buffer as is and playing it? If so, which classes enable this? Or does it need to be rendered/converted into some other format or file first?
This is the format description of the data in the buffer:
mediaType:'soun'
    mediaSubType:'lpcm'
    mediaSpecific: {
        ASBD: {
            mSampleRate: 44100.000000
            mFormatID: 'lpcm'
            mFormatFlags: 0xc
            mBytesPerPacket: 2
            mFramesPerPacket: 1
            mBytesPerFrame: 2
            mChannelsPerFrame: 1
            mBitsPerChannel: 16     }
        cookie: {(null)}
        ACL: {Mono}
        FormatList Array: {
            Index: 0
            ChannelLayoutTag: 0x640001
            ASBD: {
            mSampleRate: 44100.000000
            mFormatID: 'lpcm'
            mFormatFlags: 0xc
            mBytesPerPacket: 2
            mFramesPerPacket: 1
            mBytesPerFrame: 2
            mChannelsPerFrame: 1
            mBitsPerChannel: 16     }}
    }
    extensions: {(null)}

Any guidance appreciated, as Apple's docs aren't clear on this matter, and related questions on SO deal more with a live-stream of audio than capture and subsequent playback.

A: It's possible to pass mic to audio engine in parallel with recording, at minimum lag:
let audioEngine = AVAudioEngine()
...
self.audioEngine.connect(self.audioEngine.inputNode,
    to: self.audioEngine.mainMixerNode, format: nil)
self.audioEngine.start()

If sample buffer use is important --
Roughly, it can be done with conversion into PCM buffer:
import AVFoundation

extension AVAudioPCMBuffer {
static func create(from sampleBuffer: CMSampleBuffer) -> AVAudioPCMBuffer? {

    guard let description: CMFormatDescription = CMSampleBufferGetFormatDescription(sampleBuffer),
          let sampleRate: Float64 = description.audioStreamBasicDescription?.mSampleRate,
          let channelsPerFrame: UInt32 = description.audioStreamBasicDescription?.mChannelsPerFrame /*,
     let numberOfChannels = description.audioChannelLayout?.numberOfChannels */
    else { return nil }

    guard let blockBuffer: CMBlockBuffer = CMSampleBufferGetDataBuffer(sampleBuffer) else {
        return nil
    }

    let samplesCount = CMSampleBufferGetNumSamples(sampleBuffer)

    //let length: Int = CMBlockBufferGetDataLength(blockBuffer)

    let audioFormat = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: sampleRate, channels: AVAudioChannelCount(1), interleaved: false)

    let buffer = AVAudioPCMBuffer(pcmFormat: audioFormat!, frameCapacity: AVAudioFrameCount(samplesCount))!
    buffer.frameLength = buffer.frameCapacity

    // GET BYTES
    var dataPointer: UnsafeMutablePointer<Int8>?
    CMBlockBufferGetDataPointer(blockBuffer, atOffset: 0, lengthAtOffsetOut: nil, totalLengthOut: nil, dataPointerOut: &dataPointer)

    guard var channel: UnsafeMutablePointer<Float> = buffer.floatChannelData?[0],
          let data = dataPointer else { return nil }

    var data16 = UnsafeRawPointer(data).assumingMemoryBound(to: Int16.self)

    for _ in 0...samplesCount - 1 {
        channel.pointee = Float32(data16.pointee) / Float32(Int16.max)
        channel += 1
        for _ in 0...channelsPerFrame - 1 {
            data16 += 1
        }

    }

    return buffer
}
}

 class BufferPlayer {

let audioEngine = AVAudioEngine()
let player = AVAudioPlayerNode()

deinit {
    self.audioEngine.stop()
}

init(withBuffer: CMSampleBuffer) {

    self.audioEngine.attach(self.player)

    self.audioEngine.connect(self.player,
                             to: self.audioEngine.mainMixerNode,
                             format: AVAudioPCMBuffer.create(from: withBuffer)!.format
    )

    _ = try? audioEngine.start()
}

func playEnqueue(buffer: CMSampleBuffer) {
    guard let bufferPCM = AVAudioPCMBuffer.create(from: buffer) else { return }

    self.player.scheduleBuffer(bufferPCM, completionHandler: nil)
    if !self.player.isPlaying { self.player.play() }
}

}

A: It seems that the answer is no, you can't simply save and play back raw buffer audio, it needs to be converted to something more persistent first.
Looks like the main way to do this is to use AVAssetWriter to save the buffer data as an audio file, for playback later using AVAudioPlayer.


text:
Q: How can I bypass website visit_shared_page? So, I would like to visit a website with a proxy, but the targeted site has a visit_share_page, which shows my real ip and uid. How can I bypass that?
This is the code:
import pyuser_agent
import requests
from itertools import cycle
import random
from requests_html import HTMLSession
import json
import time

session = HTMLSession()
x = True
while x == True:
    ua = pyuser_agent.UA()
    proxy = set()
    session = HTMLSession()
    proxielist = open(r'C:\Users\skele\dsd\asa.txt')
    with proxielist as f:
        file_lines1 = f.readlines()
        for line1 in file_lines1:
            proxy.add(line1.strip())

    proxies = {
        'http': random.choice(list(proxy))
        #'https' : random.choice(list(proxy))
    }

    headers = {
        "user-agent" : ua.random,
        "sec-ch-ua-mobile" : "?1",
        "sec-ch-ua" : '" Not A;Brand";v="99", "Chromium";v="101", "Google Chrome";v="101"',
        "sec-ch-ua-platform" : "Android",
        "accept-encoding": "gzip, deflate, br",
        "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
        "upgrade-insecure-requests": "1",
        "accept-language": "en-US,en;0.9",
        "sec-fetch-site": "same-site",
        "sec-fetch-mode": "navigate",
        "sec-fetch-user": "?1",
        "sec-fetch-dest": "document"
    }
    try:
        uri = "https://hoop.photo/share/bFIgZr6ILNWBIPZnHtcVZ663sJi2"
        res = session.get(uri,headers=headers,proxies=proxies)
        print(res.text)
        res.html.render(4)
        print(res)
        print(proxies)
    except:
        print("Connection error.")

And this is the response: `
const visit_shared_page = firebase.functions().httpsCallable('visit_shared_page');
visit_shared_page({uid: "bFIgZr6ILNWBIPZnHtcVZ663sJi2", ip: "my ip(had to delete)"}).then(function(result) {
console.log(result);
`


text:
Q: passport.js with express-validator in signup form and passport doesnt work i dont know how to use express validator with passport.js in sign up form and which of them save the user in database i send these files to check of it and inspect the error
also when i use passport alone without expressvalidator, it gives me always failureRedirect no succesRedirect

``enter code here`this is user model

the user routes file
    var express = require('express');
var router = express.Router();
var User = require("../models/user");
var passport = require("passport");
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
router.get("/signup", function (req, res) {
    "use strict";
    res.render("signup", {title: "signup"});
});
router.get("/login", function (req, res) {
    "use strict";
    res.render("login", {title: "login"});
});
router.get("/profile", function (req, res, next) {
    "use strict";
    res.render("user/profile");
});
router.post("/signup", function (req, res, next) {
    "use strict";
    // form values
    var name = req.body.name;
    var username = req.body.username;
    var email = req.body.email;
    var password = req.body.password;
    var confirmpassword = req.body.confirmpassword;
    //check for profile image
    if (req.files && req.files.profileimage) {
        var profileImageOriginalNmae = req.files.profileimage.originalname;
        var profileImageName = req.files.profileimage.name;
        var profileImagePath = req.files.profileimage.path;
        var profileImageExt = req.files.profileimage.extention;
        var profileImageSize = req.files.profileimage.size;
        var profileImageMimeType = req.files.profileimage.mimetype;
    } else {
        var profileImageNmae = "noimage.png";
    }
    //check form validation
    req.checkBody("name", "name is required").notEmpty();
    req.checkBody("username", "username is required").notEmpty();
    req.checkBody("email", "email is invalid").isEmail();
    req.checkBody("password", "password is required").notEmpty();
    req.checkBody("confirmpassword", "password does not match").equals(req.body.password);
    //check for errors
    var errors = req.validationErrors();
    if (errors) {
        res.render("signup", {
            errors: errors,
            name: name,
            username: username,
            email: email,
            password: password,
            confirmpassword: confirmpassword
        });
    } else {
        var newUser = new User({
            name: name,
            username: username,
            email: email,
            password: password,
            profileimage: profileImageName
        });
        User.createUser(newUser, function (err, user) {
            if (err) {
                throw err;
            }
            console.log(user);
        });
         //success message
            req.flash("success_msg", "now you can login");

            res.redirect("/user/login");
    }
}, passport.authenticate("local-signup", {
    successRedirect: "/user/profile",
    failureRedirect: "/user/login",
    failureFlash: true

}));
module.exports = router;

this is my passport file
    // importing passport modules
    var passport = require("passport");
    var LocalStrategy = require("passport-local").Strategy;
    var User = require("../models/user");
    passport.serializeUser(function (user, done) {
        "use strict";
        done(null, user.id);
    });
    passport.deserializeUser(function (id, done) {
        "use strict";
        User.findById(id, function (err, user) {
            done(err, user);
        });
    });
    passport.use("local-signup", new LocalStrategy({
        usrnameField: "username",
        passwordField: "password",
        passReqToCallback: true
    }, function (req, username, password, done) {
        "use strict";
        User.findOne({"username": username}, function (err, user) {
            if (err) {
                return done(err);
            }
            if (user) {
                return done(null, false, {message: "username is already un use"});
            } else {
                var newUser = new User();
                newUser.username = username;
                newUser.password = password;
            }
        });
    }));
## this is user routes file ##
var express = require('express');
var router = express.Router();
var User = require("../models/user");
var passport = require("passport");
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
router.get("/signup", function (req, res) {
    "use strict";
    res.render("signup", {title: "signup"});
});
router.get("/login", function (req, res) {
    "use strict";
    res.render("login", {title: "login"});
});
router.get("/profile", function (req, res, next) {
    "use strict";
    res.render("user/profile");
});
router.post("/signup", function (req, res, next) {
    "use strict";
    // form values
    var name = req.body.name;
    var username = req.body.username;
    var email = req.body.email;
    var password = req.body.password;
    var confirmpassword = req.body.confirmpassword;
    //check for profile image
    if (req.files && req.files.profileimage) {
        var profileImageOriginalNmae = req.files.profileimage.originalname;
        var profileImageName = req.files.profileimage.name;
        var profileImagePath = req.files.profileimage.path;
        var profileImageExt = req.files.profileimage.extention;
        var profileImageSize = req.files.profileimage.size;
        var profileImageMimeType = req.files.profileimage.mimetype;
    } else {
        var profileImageNmae = "noimage.png";
    }
    //check form validation
    req.checkBody("name", "name is required").notEmpty();
    req.checkBody("username", "username is required").notEmpty();
    req.checkBody("email", "email is invalid").isEmail();
    req.checkBody("password", "password is required").notEmpty();
    req.checkBody("confirmpassword", "password does not match").equals(req.body.password);
    //check for errors
    var errors = req.validationErrors();
    if (errors) {
        res.render("signup", {
            errors: errors,
            name: name,
            username: username,
            email: email,
            password: password,
            confirmpassword: confirmpassword
        });
    } else {
        var newUser = new User({
            name: name,
            username: username,
            email: email,
            password: password,
            profileimage: profileImageName
        });
        User.createUser(newUser, function (err, user) {
            if (err) {
                throw err;
            }
            console.log(user);
        });
         //success message
            req.flash("success_msg", "now you can login");

            res.redirect("/user/login");
    }
}, passport.authenticate("local-signup", {
    successRedirect: "/user/profile",
    failureRedirect: "/user/login",
    failureFlash: true

}));
module.exports = router;

`


text:
Q: `ListPlot` with `Association` as input It seems ListPlot will somehow drop the trailing list of Associations when the Association label names are different (here I use three different labels: Sin, Cos and Tan):
asscTest0 = Table[Association[{"t" -> t, ToString[fun] -> fun[t]}], {fun, {Sin, Cos, Tan}}, {t, 0, 2 Pi, Pi/3}];
ListPlot[asscTest0,Joined -> True]
(*error message: ListPlot::lpn: {{{0.,0.},{1.0472,0.866025},{2.0944,0.866025},{3.14159,0.},{4.18879,-0.866025},{5.23599,-0.866025},{6.28319,0.}},{},{}} is not a list of numbers or pairs of numbers.*)

However, if the Association label names are kept the same (i.e., "fun"), ListPlot can work:
asscTest1 = Table[Association[{"t" -> t, "fun" -> fun[t]}], {fun, {Sin, Cos}}, {t, 0, 2 Pi, Pi/3}]

Should this be considered as a bug? Or I missed something?

A: Though not documented, the following works :
asscTest3=
Association[
    Table[ToString[fun]->
        Table[
            Association[{"t" -> t, "anything" -> fun[t]}],
            {t, 0, 2 Pi, Pi/3}
             ],
         {fun, {Sin, Cos, Tan}}
         ]
     ];

asscTest3 //N

ListPlot[asscTest3,Joined -> True]

<|"Sin" -> {<|"t" -> 0.,
      "anything" -> 0.|>, <|"t" -> 1., "anything" -> 0.9|> ...},
      "Cos" -> {<|"t" -> 0.,
      "anything" -> 1.|>, <|"t" -> 1., "anything" -> 0.5|> ..},
      "Tan" -> {<|"t" -> 0.`,
      "anything" -> 0.|>, <|"t" -> 1., "anything" -> 1.7|> ..}|>

Note that a legend has appeared. This legend corresponds to the option PlotLegends -> "Expressions" (or "AllExpressions") which seems to be the default (at least on my version, 11.3). You can remove it whith PlotLegends -> None

A: We could, theoretically, make this work, but I suspect that people then wouldn't like the result of
ListPlot[{
 Table[<|"a" -> i, "b" -> i^2|>, {i, 5}],
 Table[<|"b" -> i + 1, "a" -> i|>, {i, 5}]
 }]

Right now ListPlot consistently maps "a" to the $x$ coordinate and "b" to $y$.  Once ListPlot gives a meaning to a particular association key, it uses that for the rest of the evaluation.


text:
Q: Does 'feelings of solitude' sound good or correct? I always see/read sentences like :
'..and this can cause you to have feelings of loneliness.'
or
'but it's hard to cope when feelings of worthlessness and loneliness persist.'
So I wonder if it will still sound correct to say feelings of solitude also.

A: The words "loneliness" and "worthlessness" are pretty much always emotions or mental states, so they are appropriate objects for "feelings of". The word "solitude" on the othe hand, most often means the actual fact of being alone. However it can also be used to describe the metal state resulting from being alone, and in that sense could be used with "feelings of".
"feelings of solitude" seems a bit odd, i think because of the primary meaning of "solitude" not being a feelign or mental state. But I don't see anything actually wrong with it.


text:
Q: slash at the start of a mvc parameter I use this route in my controller
[HttpGet("Check/{*code}")]

this work in almost all cases, but this does't work with slash at the start in parameter, like "/1HCZ0hVPloeftdvDHgGNg==" this generate next url
api/check//1HCZ0hVPloeftdvDHgGNg==

so, the controller read "1HCZ0hVPloeftdvDHgGNg==" and crash decrypt code.
How solve this?

A: You didn't say version of ASP.NET you're using but I think
using System.Web.HttpUtility;
string queryString = UrlEncode("/1HCZ0hVPloeftdvDHgGNg==");

should work for you.  It will convert the slash (and any other weird characters) to Uri-safe values.  In your case, queryString = "%2f1HCZ0hVPloeftdvDHgGNg%3d%3d"
On the other end, you will need to use UrlDecode to get it back to the original string also.
Function documentation is here.


text:
Q: Wordpress - Create Page with custom CSS and JS only I am creating a Wordpress plugin that adds a page that embeds a React app.
On plugin activation, a post is inserted with wp_insert_post() function, and then the load_app_template() function is triggered to set the post template.
This template contains wp_head() in the head section and my React app.
The problem is that some other plugins are loading some JS and CSS in the head that are disturbing the React app behavior. I am trying to remove all JS and CSS given by Wordpress & other plugins and add my own.
If I remove wp_head() from the post template, then I cannot register styles and scripts with my plugin through wp_register_script.
How to remove all JS and CSS from Wordpress and plugins and add my own from my plugin ?
There could be two ways :

*

*Remove wp_head() and manually add links to my JS and CSS in the HTML template. I can do that for Jquery and Bootstrap but I don't know how to put links of JS files from my plugin directory.

*Keep wp_head(), deregister all CSS and JS and add my own afterwards with Wordpress hooks. I am not able to remove some Javascript from other plugins with this solution. I tried deregistering all following this answer.
Thank you !

A: Try to remove unnecessary scripts and styles using wordpress hooks
(this might help you figure out how to do so: https://wordpress.stackexchange.com/questions/233140/how-can-i-get-a-list-of-all-enqueued-scripts-and-styles) if your template is used on page.

A: You can remove unused CSS/JS from that page. Put this code on your function.php
function remove_unused_css_js() {
// remove only from that page
if(get_the_ID() == 'Your Page ID'){
    wp_dequeue_style('css-id'); // remove css
    wp_dequeue_script('js-id'); // remove js
}
}
add_action( 'wp_print_styles', 'remove_unused_css_js', 100 );

Hope this will help.