text:
Q: Updating state of a component responsible for displaying status during data fetch I am trying to create a status component in my application, which will be updated during data fetch and other network related events.
componentWillReceiveProps(nextProps){
// This check is required otherwise setting state
// from here will end up in a rendering loop
if(!_.isEqual(this.props, nextProps)){
  if(nextProps.services.length != 0){
    if(nextProps.filters.length == 0){
      nextProps.setStatus('Fetching filters...');
      const { serviceId } = nextProps.params;
      const serviceIndex = nextProps
                            .services
                            .findIndex(
                                (service) => service.id == serviceId
                              );
      const serviceObj = nextProps.services[serviceIndex];
      nextProps.getFilters(serviceObj);
    }
  }
}

}
Here I am using componentWillReceiveProps life cycle event to load some data based on another set of data in store (due to dependency). The setStatus method is responsible for updating the store with the new status message and according to that a Status component will be updated. Here  you can see, I am checking if the  filters are empty, I am setting the status and trying to fetch the data. Now when I am setting the status it is updating the store thus firing the "render" process again. This will call the life cycle events again and as the filters are still empty it will do the data fetch request again. Currently, I have stopped this using
// Setting status will set the state and invoke data collection
      // again as filters are still empty due to re-render
      if(_.isEqual(this.props.status,nextProps.status) &&
        _.isEqual(this.props.filters,nextProps.filters)) {
        const { serviceId } = nextProps.params;
        const serviceIndex = nextProps
                              .services
                              .findIndex(
                                  (service) => service.id == serviceId
                                );
        const serviceObj = nextProps.services[serviceIndex];
        nextProps.getFilters(serviceObj);
      }

But this approach is more like a hack. Can you please suggest any better design approach for this status component? Can I maintain a controlled component?

A: I'll admit that what you are specifically trying to accomplish is a bit unclear to me, but from what it seems, I should think you should be creating a Redux event to inform your component of the different steps of this process and hitting action creators in response. If you're trying to track state in some way outside of the Redux store, you'll get yourself into trouble.


text:
Q: Parse XML file using SQL Server, and return child node section as XML I have an XML file that looks like this:
<NodeA Type="A" Date="2015-10-28">
  <NodeB Amount="0.00">
    <Items />
  </NodeB>
  <NodeB Amount="0.00">
    <Items>
      <Item code="2" val="50.00" />
      <Item code="8" val="50.00" />
    </Items>
  </NodeB>
</NodeA>

I am trying to use SQL Server and XPath to extract the child nodes of NodeA as XML.
Based on the above XML, I need to return a table with 2 rows, containing the following fields:
Type (nvarchar) | Date (Date) | ChildNode (XML)
-----------------------------------------------
A                 2015-10-28    <NodeB Amount="0.00"><Items /></NodeB>
A                 2015-10-28    <NodeB Amount="0.00"><Items>...</NodeB>

I know I can do this using C#, but is there a way to do this using XPath?  I've some success with xPath returning the field values from NodeA, but can't seem to get NodeB to display as XML.

A: Try this -
DECLARE @xml AS XML

SET @xml = '<NodeA Type="A" Date="2015-10-28">
  <NodeB Amount="0.00">
    <Items />
  </NodeB>
  <NodeB Amount="0.00">
    <Items>
      <Item code="2" val="50.00" />
      <Item code="8" val="50.00" />
    </Items>
  </NodeB>
</NodeA>'

SELECT c.value('(/NodeA/@Type)[1]', 'varchar(50)') AS Type,
    c.value('(/NodeA/@Date)[1]', 'varchar(50)') AS Date,
    c.query('.') AS ChildNodeXML
FROM @xml.nodes('/NodeA/NodeB') as T(C)

Result
Type   Date          ChildNodeXML
----   ------        ----------------------------------
A      2015-10-28   <NodeB Amount="0.00"><Items /></NodeB>
A      2015-10-28   <NodeB Amount="0.00"><Items><Item code="2" val="50.00" /><Item code="8" val="50.00" /></Items></NodeB>

redpajama_set_name: RedPajamaStackExchange


text:
Q: maven-jaxb2-plugin forceRegenerate=false not working? I'm trying to configure maven-jaxb2-plugin to only generate java if XSD changes.
That doesn't seem to work because java classes are always regenerated.
This is the plugin configuration :
<plugin>
            <groupId>org.jvnet.jaxb2.maven2</groupId>
            <artifactId>maven-jaxb2-plugin</artifactId>
            <version>0.8.3</version>
            <configuration>
                <generateDirectory>${basedir}/src/main/java/</generateDirectory>
                <strict>true</strict>
                <verbose>true</verbose>
                <readOnly>true</readOnly>
                <episode>true</episode>
                <forceRegenerate>false</forceRegenerate>
                <removeOldOutput>false</removeOldOutput>
            </configuration>
            <executions>
                <execution>
                    <id>commun-generate</id>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                        <generatePackage>my.package.dest</generatePackage>
                        <schemaDirectory>${basedir}/src/main/resources/schemas/wsrest</schemaDirectory>
                        <bindingDirectory>${basedir}/src/main/resources/schemas/wsrest</bindingDirectory>
                        <bindingIncludes>
                            <include>bindings.xml</include>
                        </bindingIncludes>
                        <episodeFile>${basedir}/src/main/java/META-INF/sun-jaxb_commun.episode</episodeFile>
                    </configuration>
                </execution>

When building (maven clean install or maven install) i can observe this output :
[INFO] File [D:\IDE\Data\Eclipse\workspace\MyProject\src\main\resources\schemas\wsrest\myXSD.xsd] was changed since the last build.
[INFO] File [D:\IDE\Data\Eclipse\workspace\MyProject\src\main\resources\schemas\wsrest\bindings.xml] was changed since the last build.
[INFO] File [D:\IDE\Data\Eclipse\workspace\MyProject\pom.xml] was changed since the last build.

But i didn't change anything in theses files since the last build!
What am i doing wrong?
Thanks in advance
Clément

A: As a partial workaround you can add <noFileHeader>true</noFileHeader> to your configuration so that generated sources are the same for unchanged XSD. Solves my problems with repository commits, if that matters to you as well...
Can't stop XJC from re-generation it checks just timestamps it seems.

A: There's no way to stop regenerate because of the following:
I'd the same issue and I dug through the plugin code to find out the root cause:
The up-to-date check in org.jvnet.jaxb2.maven2.RawXJC2Mojo.isUpToDate uses if (getBuildContext().hasDelta(dependsFile)) which delegates to org.sonatype.plexus.build.incremental.DefaultBuildContext.hasDelta which is hard-coded to return true. This is because the concept of incremental build is broken in Maven c.f. Incremental Build
That logic can be changed to check if the output directory exists and if yes, if the XSD have changed. I may file a bug if I find time.

A: Are the files actually regenerated? I have the following:
[INFO] File [C:\Projects\workspace-juno\maven-jaxb2-plugin-project\tests\po\src\main\resources\purchaseorder.xsd] was changed since the last build.
[INFO] File [C:\Projects\workspace-juno\maven-jaxb2-plugin-project\tests\po\pom.xml] was changed since the last build.
[INFO] Checking up-to-date depends [[C:\Projects\workspace-juno\maven-jaxb2-plugin-project\tests\po\src\main\resources\purchaseorder.xsd, C:\Projects\workspace-juno\maven-jaxb2-plugin-project\tests\po\pom.xml]].
[INFO] Checking up-to-date produces [[C:\Projects\workspace-juno\maven-jaxb2-plugin-project\tests\po\target\generated-sources\xjc\generated\Items.java, C:\Projects\workspace-juno\maven-jaxb2-plugin-project\tests\po\target\generated-sources\xjc\generated\ObjectFactory.java, C:\Projects\workspace-juno\maven-jaxb2-plugin-project\tests\po\target\generated-sources\xjc\generated\PurchaseOrderType.java, C:\Projects\workspace-juno\maven-jaxb2-plugin-project\tests\po\target\generated-sources\xjc\generated\USAddress.java, C:\Projects\workspace-juno\maven-jaxb2-plugin-project\tests\po\target\generated-sources\xjc\META-INF\sun-jaxb.episode]].
[INFO] Depends timestamp [1.395.259.386.093], produces timestamp [1.395.259.394.765].
[INFO] Skipped XJC execution. Generated sources were up-to-date.

It seems that the provided org.sonatype.plexus.build.incremental.BuildContext says that the file has changed. But when the plugin checks the timestamps specifically, it sees that files are up-to-date. I think the problem is just in the log message, it should read may have been changed.
Please file an issue here.


text:
Q: In newer Windows, window is tiny with no borders I've been working on updating an old (Windows 95-era C API) application. While it works fine on Windows XP, on Vista and newer it always displays in a tiny 240x160 window with no menus or borders. What are the differences between Vista and XP that could cause this behavior?
On Windows 7, it looks like this (actual size):

This is what it should look like, and what it does look like in Windows XP:


text:
Q: Matrix with column and row headings I am trying to produce an nxn bmatrix that has both column and row headings. By following this manual with amsmath package and the code below:
\begin{figure}
\[\begin{bmatrix}
a_{11}&a_{12}&\cdots &a_{1n} \\
a_{21}&a_{22}&\cdots &a_{2n} \\
\vdots & \vdots & \ddots & \vdots\\
a_{n1}&a_{n2}&\cdots &a_{nn}
\end{bmatrix}\]
\caption{Correlation Matrix}\label{fig:vulnmatrix}
\end{figure}

I can  produce this:

However, I aim at producing a bmatrix with column and row headings like this:

So far I have researched and all the examples I have encountered do not have  headings. Can anyone suggest a solution for me?

A: A solution with blkarray, and another with gauss:
\documentclass{article}
\usepackage[T1]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage{mathtools}
\usepackage{blkarray, bigstrut}
\usepackage{gauss}

\newenvironment{mygmatrix}{\def\mathstrut{\vphantom{\big(}}\gmatrix}{\endgmatrix}

 \begin{document}%

 \begin{figure}[!ht]
\[
\begin{blockarray}{ccccc}
 & C_1 & C_2 & \dots & C_n \\
\begin{block}{c[cccc]}
N_1 & a_{11}&a_{12}&\cdots &a_{1n}\bigstrut[t] \\
N_2 & a_{21}&a_{22}&\cdots &a_{2n} \\
 & \vdots & \vdots & \ddots & \vdots\\
N_n & a_{n1}&a_{n2}&\cdots &a_{nn}\bigstrut[b]\\
\end{block}
\end{blockarray}\vspace*{-1.25\baselineskip}
\]
\caption{Correlation Matrix}\label{fig:vulnmatrix}
\end{figure}

\begin{figure}[! htb]
    \[
    \begin{gmatrix}[b]
    \mathllap{N_1\quad}a_{11}&a_{12}&\cdots &a_{1n} \\
     \mathllap{N_2\quad}a_{21}&a_{22}&\cdots &a_{2n} \\
    \vdots & \vdots & \ddots & \vdots\\
     \mathllap{N_n\quad}a_{n1}&a_{n2}&\cdots &a_{nn}\colops
\def\colmultlabel#1{\makebox[1.2em]{$#1$}}
\mult0{C_1}
\mult1{C_2}
\mult3{C_n}
     \end{gmatrix}
    \]
\caption{Correlation Matrix}\label{fig:vulnmatrix}
\end{figure}

\end{document}


text:
Q: Doctrine 2.1 - Removing from collection I am trying to remove comments from a parent entity, I remember doing this on my last website but now it's not working..
My entity - users
namespace Application\Entities;

use Doctrine\ORM\Mapping AS ORM,
    Doctrine\Common\Collections\ArrayCollection;

/**
 * Loan
 *
 * @ORM\Table(name="users")
 * @ORM\Entity
 */
class Users{

    /**
     * @var integer $id
     *
     * @ORM\Column(type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var string $username
     *
     * @ORM\Column(type="string", length=45, nullable=false)
     */
    private $username;

    /**
     * @var ArrayCollection
     *
     * @ORM\OneToMany(targetEntity="Comments", mappedBy="author", cascade={"persist", "remove"})
     */
    private $comments;

    public function getComments(){

          return $this->comments;

    }

and my comments table:
    namespace Application\Entities;

    use Doctrine\ORM\Mapping AS ORM,
        Doctrine\Common\Collections\ArrayCollection;

/**
 * Loan
 *
 * @ORM\Table(name="comments")
 * @ORM\Entity
 */
class Comments{

    /**
     * @var integer $id
     *
     * @ORM\Column(type="integer", nullable=false)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    private $id;

    /**
     * @var integer $user_id
     *
     * @ORM\Column(type="integer", length=15, nullable=false)
     */
    private $user_id

    /**
     * @var Loan
     *
     * @ORM\ManyToOne(targetEntity="Users", inversedBy="comments",cascade={"persist"})
     * @ORM\JoinColumns({
     *   @ORM\JoinColumn(name="user_id", referencedColumnName="id")
     * })
     */
    private $author;

This is fine, it works and I get all collections called comments in the users repository..
Now, I usually do this when I need to delete:
$commentToDelete = $this->em->getRepository('Entities\Comments')->findOneById(375);
$userResults = $this->em->getRepository('Entities\Users')->findOneById(23);
$userResults->getComments()->removeElement($commentToDelete);
$this->em->flush();

Nothing deletes, neither it throws an exception to tell me it hasn't.
I doctrine flushed it too, checked the db, and it's still there..
UPDATE:
Straight after I removeElement, I looped through the user id = 23 dataset, and the comment data for id375 is not there...  so it removed it from the collection but not from the DB, and I thought $em->flush() is supposed to do this?
Please advise
Thanks

A: You need to use
$em->remove($commentToDelete);
$em->flush();

Because the mapping is held in the comment you need to remove this entity to remove the reference before you flush which will save the state to the db.


text:
Q: Hashable subclasses of mutable classes in Python I want to build a subclass of a class which is basically a wrapper around a list/dictionary, and I want to use instances of this class as keys. In order to have easy access to the list/dictionary methods, I figured I can just subclass them, but then I lose hashability.
I understand that this is incompatible with the __eq__ of the mutable classes (and I don't need it), so I came up with the following solution.
class Foo(list):
    __hash__ = object.__hash__
    __eq__ = object.__eq__

Though I doubt this will come up in my specific applications, I guess this might cause problems if another class (with its own __hash__) would appear between Foo and list in the MRO of a subclass.

*

*Is there a more Pythonic way of doing this? I could just add a list/dictionary as an attribute and then simply use the attribute (which would make code elsewhere more cumbersome) or the list/dictionary methods I need (but that'd be much more messy if I need more than a couple of methods).

*Is there some pattern/recipe that would allow me to do this sort of thing in a cooperative setting (in other words, how should I change the code if I do in fact anticipate another class between Foo and list in MRO)?

A: I decided a provide an answer based on my comment, with a lot if IFs
As stated, I would rather change the implementation of the dict, to take a list as a key. This however does come with problems, that as others mentioned, is the reason why lists SHOULDN'T be keys.
A little explanation:
When looking at a mutable variable, it comes with two properties, that it can be compared by:

*

*Its identity

*Its content
Identity
When a variable is created such as a=[1,2,3] it is allocated a memory position which can be called with id(a). This id identifies a even after a is modified. However with a second variable b=[1,2,3] when comparing ids we get id(a) == id(b) = False
Content
We can also look at the content of a variable in a very simple way by converting it to a String, so with above example str(a) == str(b) = True. However if we do
a = [1,2,3]
str_a = str(a)
a.append(4)
str_new_a = str(a)

we get str_a == str_new_a = False, which is problematic in the case of application as a key in a dict, because at the moment of saving the value, we take a 'snapshot' of a and later if we lookup by a after it changed, it wont match.
Therefore you will have to decide, if in your case content or identity is the relevant lookup criterion.
An example implementation with hashableKey1 as an ID match and hashableKey2 as a content mach is provided below.
from collections import Hashable

class CoolDict(dict):
    hashableKeyType = 1
    def __setitem__(self, name, value):
        print(name, value)
        if isinstance(name, Hashable):
            super().__setitem__(name, value)
        else:
            super(CoolDict, self).__setitem__(self.hashableKey(name), value)
    def __getitem__(self, name):
        if isinstance(name, Hashable):
            return super().__getitem__(name)
        else:
            return super().__getitem__(self.hashableKey(name))

    def hashableKey(self, name):
        if self.hashableKeyType == 1:
            return self.hashableKey1(name)
        elif self.hashableKeyType == 2:
            return self.hashableKey2(name)
    def hashableKey1(self, name):
        return id(name)

    def hashableKey2(self, name):
        return str(name)

coolDict  = CoolDict()

### hashableKey1:

#Working
key = [1,2,3]
coolDict[key] = 123
print(coolDict[key])

#Not Working
coolDict[[2,3,4]] = 234
print(coolDict[[2,3,4]])

### hashableKey2:
coolDict.hashableKeyType = 2

#Working
coolDict[[2,3,4]] = 234
print(coolDict[[2,3,4]])

#Not Working
key = [1,2,3]
coolDict[key] = 123
key.append(4)
print(key)
print(coolDict[key])


text:
Q: Angular Error Console Vendor Not Component my angular app showing error as vendor before it was showing error in which component .
how can i show in it as component not vendor .

vendor.js:166222 ERROR TypeError: Cannot read properties of null (reading 'setValue')
at FormGroupDirective.updateModel (vendor.js:395930:14)
at FormControlName.ngOnChanges (vendor.js:396351:32)
at FormControlName.rememberChangeHistoryAndInvokeOnChangesHook (vendor.js:161713:14)
at callHook (vendor.js:162732:14)
at callHooks (vendor.js:162699:17)
at executeCheckHooks (vendor.js:162631:5)
at selectIndexInternal (vendor.js:168430:17)
at Module.ɵɵadvance (vendor.js:168419:5)
at CanvasComponent_Template (main.js:37562:64)
at executeTemplate (vendor.js:169565:9)

i want the console show me error like in which component line


text:
Q: Encrypt Windows remote desktop session, when using Microsoft Remote Desktop for Mac as the host client How can i set encryption of the traffic sent between the host / client and visa versa in a Windows remote desktop session, when using Microsoft Remote Desktop for Mac as the client ?
In the setup where looking at using :

*

*CLIENT : Remote Desktop for Mac v 10.x (latest at time of writing)

*HOST : W10 pro (latest at time of writing)

A: The Microsoft RDP client for macOS (and IOS) always uses the highest encryption level supported by the OS on the server side. (It will fall back to no encryption if the server can't do encryption, which should normally never be the case.)
So there is no need to enable it yourself (and there is no way to manually do it as far as I know). It is always on.


text:
Q: Why is my post request working in POSTMAN but not in my react application? Below is my POSTMAN headers as well as the settings I used to send my POST. Only when I changed the Content-Type to appplication/json  then it works.

This is my web application server side.
const express = require("express");
const bodyParser = require('body-parser');
const app = express();
const cors = require("cors");
const pool = require("./db");

//middleware
app.use(cors());
app.use(express.json());
app.use(express.urlencoded({ extended: true }))

//POST
app.post("/species", async (req, res) => {
  try {

      console.log(req.body)
      const {name, description, img} = req.body
      const newSpecies = await pool.query("INSERT INTO speciesdata (name, description, img ) VALUES ($1, $2, $3) RETURNING *",
      [name, description, img]
      );

    console.log(newSpecies)
    res.json(newSpecies.rows);

  } catch (err) {
    console.error(err.message);
  }
});

app.get('/species', async (req, res) => {
  try {
    const allspecies = await pool.query("SELECT * FROM speciesdata");
    res.json(allspecies.rows);

  } catch (err) {
    console.log(err.message)
  }
})

//DELETE
app.delete("/species/:id", async (req, res) => {
  try {

    const {id} = req.params
    const deletespecies = await pool.query("DELETE FROM speciesdata WHERE id = $1",[id]);
    res.json(deletespecies.rows);

  } catch (err) {
    console.error(err.message);
  }
});

app.listen(5000, () => {
  console.log("server has started on port 5000")
})

My other requests such as the app.get as well as app.delete works. It is only the first one app.post that is not working. When using POSTMAN, the req.body returns me { name: 'name', description: 'description', img: 'img' } and i can see it being displayed on my web application which is what I want.
However, on my frontend application side, upon submitting the form, nothing was being displayed both on the frontend and the backend side. This is my react client side.
function AddSpeciesForm() {

  const [Nameinput, setName] = useState('');
  const [Descriptioninput, setDescription] = useState('');
  const [imageinput, setImage] = useState('');

  const onSubmitForm = async e => {
    e.preventDefault();
    try {

      const response = await fetch("http://localhost:5000/species", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
           "name" : Nameinput,
           "description": Descriptioninput,
           "img": imageinput
        })
      });

      console.log(response)
    } catch (err) {
      console.error(err.message);
    }
  };
  return (
    <AddSpeciesContainer>
      <AddSpeciesWrapper>
        <AddSpeciesform>
          <AddSpeciesH1>Add new species</AddSpeciesH1>
            <InputWrapper>
              <NameInput
                placeholder="Name"
                type="text"
                value={Nameinput}
                onChange={e => setName(e.target.value)}
              />
              <DescriptionInput
                placeholder="Description"
                type="text"
                value={Descriptioninput}
                onChange={e => setDescription(e.target.value)}/>
              <ImgInput
                placeholder="Image"
                type="text"
                value={imageinput}
                onChange={e => setImage(e.target.value)}/>
            </InputWrapper>
          <AddButton onSubmit= {onSubmitForm}>Add</AddButton>
        </AddSpeciesform>
      </AddSpeciesWrapper>
    </AddSpeciesContainer>
  )
}

export default AddSpeciesForm

The previous time I asked this I was able to solve the POSTMAN side but right now on my application side even when I had change the Content-Type: application/JSON it is still not working. I have been strugguling with this for the past few days, would really appreciate some help.

A: I think the only missing argument in the fetch call is
in the header section.
You can do something like below  -
  const addDevice = async (device) => {
  const { hostname: location } = window.location;
  const settings = {
    method: 'POST',
    body: JSON.stringify(device),
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
    }
  }

  const response = await fetch(`http://${location}:9000/api/sensors/`, settings);
  if (!response.ok) throw Error(response.message);

  try {
    const data = await response.json();
    return data;
  } catch (err) {
    throw err;
  }
};

For more information please read this answer -
Proper Way to Make API Fetch 'POST' with Async/Await


text:
Q: Passing ResultSet to other method I have an application which gets data from database and create excel. I wanted to separete dao class which gets the resultSet from db and the class which is creating excel with this resultset.
In this way I was passing ResultSet from Dao to the other class to create excel file. But when I run the rs.next(), it gives me "Closed Resultset:next" error.
I read on the internet that passing ResultSet is not good idea therefore I just try to do it in dao class and it worked.
But in that way I do not like to do other task (creasting excel) in dao class and I do not want to create a class and then send them as a list. So my question is why it is bad to pass resultset to other class or function? Why I got exception when I pass it and try to call rs.next()?
To Summarize my code looks like these:
ResultSet rs = myDao.getResult();
ExcelCreator excelCreator = new ExcelCreator();
excelCreator.createExcel(rs);

A: Because it may lead to resource leaking by forcing connection open and closing connection causes closing result set. Hence we use collection of Objects to return it.

A: Why you are getting "Closed resultset:next" error, see here:
Why am I getting ResultSet is closed error when I never closed any
I suppose you are not using some ORM framework like Hibernate.
In this case, map the resultset data in the DAO or build an object mapper yourself, which maps the ResultSet to a some Data Transfer Object. Then pass this object to the createExcel() method.
Something like this:
ResultSet rs = myDao.getResult();
List<ExcelDto> excelDtos = new ArrayList<>();
ExcelDto excelDto;
while (rs.next()) {
    excelDto = new ExcelDto();
    dto.setXCol(rs.getString("XColumn"))
    excelDtos.add(dto);
}
excelCreator.createExcel(excelDtos);

Then in the excelCreator you can work with an ArrayList instead of ResultSet.


text:
Q: (Vue.js) On the github page, the inside of '#app' is empty import Vue from 'vue'
import Router from 'vue-router'
import Home from '@/views/Home.vue'
import Load from '@/views/Load.vue'
import Login from '@/views/Login.vue'
import Main from '@/views/Main.vue'

Vue.use(Router)

export default new Router({
  mode: 'history',
  routes: [{
    path: '/',
    name: 'home',
    component: Home
  },
  {
    path: '/load',
    name: 'loading',
    component: Load
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/main',
    name: 'main',
    component: Main
  }]
})

I connected the router correctly.
But https://sh031224.github.io/portfolio/ the inside of '#app' is empty.
How can I do?
My github is https://github.com/Sh031224/portfolio
And github page is https://sh031224.github.io/portfolio/

A: You need to set base in your router configuration to "/portfolio/"
See the docs


text:
Q: Android using AndroidAnnotations in Library Project Eclipse I'm making a paid/free version of my app so have a 'Library Project' that the two apps use.
I'm trying to use Android Annotations to clean up my code:
http://code.google.com/p/androidannotations/
Unfortunately when I use this in my shared library project, one of my projects gets the error in Eclipse:
The type xActivity_ is already defined  xActivity_.java /ProjectName/.apt_generated/lib/activities/
Because Android Annotations automatically creates a new activity with an extra '_' in the folder .apt_generated one of the apps is allowed to create this file, but the other gets the error "already defined".
Is there a way in Eclipse to resolve this? Or is it a problem with the Android Annotations?

A: This seems to be an AndroidAnnotations bug, and should be reported on the dedicated bug tracker.
AndroidAnnotations wasn't designed with this use case in mind, but this is still a very valid use case. The problem seems to be that the activity is generated in the shared library project, when it should be generated in each depending project, am I right ?
(please answer in the bug tracker)

A: This question is quite old, but I thought that I should mention android annotations now supports being used in libaries:
https://github.com/excilys/androidannotations/wiki/Library-projects
One caveat is that due to the way android library projects generate the R class, you cannot reference resouces directly inside the annotations.  Eg, you cant do this:
@EActivity(R.layout.myLayout)
public class MyActivity extends Activity {

 @Click(R.id.myButton1, R.id.myButton2})
 public void someButtonClicked() {
 }
}

Instead you must do this:
@EActivity(resName="myLayout")
public class MyActivity extends Activity {

  @Click(resName={"myButton1", "myButton2"})
     public void someButtonClicked() {
  }
}

A: I just knew AndroidAnnotations (which seems a great tool!) but I think that if you do this using different projects (sharing the same library) your problem should be solved.


text:
Q: Generalization of Sylvester's law of inertia If we have a symmetric matrix $B$ and an invertible matrix $S$, such that the following holds:  $A = S^TBS$.
Then Sylvester's law of inertia states that the number of negative eigenvalues of $A$ is equal to the number of negative eigenvalues of $B$.
Question: Is there some generalization of this result which does not assume $B$ to be symmetric? In particular, I am interested in the case where $B$ is a block diagonal matrix.
Thoughts: There is probably no generalization to arbitrary matrices. However, since the theorem holds for a diagonal matrix $B$, I thought that there might be some similar result (maybe weaker) for the block diagonal case.


text:
Q: convert std::string to const BYTE* for RegSetValueEx() I have a function that gets a std::string. That function calls
RegSetValueEx
the 5th parameter is the value of the registry value and expects a variable of type const BYTE*.
So I have to convert the std::string to const BYTE* and also give the length of the resulting array as the 6th parameter.
I have found a way to do it, but it feels ugly and I don't really understand what is going on. Here is a slimmed down version of that function:
void function(const std::string& newValue)
{
    HKEY keyHandle;
    if(RegOpenKeyEx(HKEY_CLASSES_ROOT, TEXT("some key"),0,KEY_ALL_ACCESS,&keyHandle) == ERROR_SUCCESS)
    {
        std::wstring wNewValue;
        wNewValue.assign(newValue.begin(),newValue.end());

        if (RegSetValueEx(keyHandle, TEXT("some value"), NULL, REG_SZ, (const BYTE*)(LPCTSTR)(wNewValue.c_str()), wNewValue.size()*2)==ERROR_SUCCESS)
        {
            //do something
        }
        RegCloseKey(keyHandle);
    }
}

As you can see, i first make a wide string (UNICODE is defined), then use a double cast, and for the length i have to do *2, else it will only set half of the input string.
Is this form of cast the normal/best way to do it?
Why the * 2, what would be a better way?

A: The * 2 is because RegSetValueEx wants to know the number of bytes to write und each char (wchar_t) in a wstring is two bytes wide. So the resulting byte-array has twice the size!

A: void function(const std::string& newValue)
{
    HKEY keyHandle;
    if(RegOpenKeyEx(HKEY_CLASSES_ROOT, TEXT("some key"),0,KEY_ALL_ACCESS,&keyHandle) == ERROR_SUCCESS)
    {

        if (RegSetValueExA(keyHandle, "some value", NULL, REG_SZ, (const BYTE*)newValue.c_str(), newValue.size() + 1)==ERROR_SUCCESS)
        {
                //do something
        }
        RegCloseKey(keyHandle);
    }
}

I removed the part where you convert your string to a wstring, instead you'll be using the ANSI version of RegSetValueEx explicitly.
quote from RegSetValueEx remarks in MSDN:

If dwType is the REG_SZ, REG_MULTI_SZ,
  or REG_EXPAND_SZ type and the ANSI
  version of this function is used
  (either by explicitly calling
  RegSetValueExA or by not defining
  UNICODE before including the Windows.h
  file), the data pointed to by the
  lpData parameter must be an ANSI
  character string. The string is
  converted to Unicode before it is
  stored in the registry.

Also note that the cbData parameter should include the size of the null termination aswell.

A: Shouldn't it be wNewValue.size()*2+2 ? The +2 for the null character?
MSDN says: The size of the information pointed to by the lpData parameter, in bytes. If the data is of type REG_SZ, REG_EXPAND_SZ, or REG_MULTI_SZ, cbData must include the size of the terminating null character or characters.

A: You could also copy the unicode string into a byte array:
LPWSTR pData = L"SampleGrabber";
int dwSize = wcslen(pData)*sizeof(TCHAR);
BYTE slump[256];
memset((void*) slump, 0, 256*sizeof(BYTE));
memcpy((void*) slump, (const void *) pData, dwSize*sizeof(BYTE));

globit = RegSetValueEx(hKey, NULL, 0, REG_SZ, (const BYTE*) slump, dwSize);

If you had the misfortune to be writing code for a WINCE 5.0 device and it lacked part of the regedit API.


text:
Q: Django4: Ajax AttributeError I'm trying to create this Ajax request:
The views file is as follows:
reports/views.py
from django.shortcuts import render
from profiles.models import Profile
from django.http import JsonResponse
from .utils import get_report_image
from .models import Report
from .forms import ReportForm
# Create your views here.

def create_report_view(request):
    form = ReportForm(request.POST or None)
    if request.is_ajax():
        image = request.POST.get('image')
        name = request.POST.get('name')
        remarks = request.POST.get('remarks')
        img = get_report_image(image)
        author = Profile.objects.get(user=request.user)

        if form.is_valid():
            instance = form.save(commit=False)
            instance.image = img
            instance.author = author
            instance.save()
        #   Report.objects.create(name=name, remarks=remarks, image=img, author=author)

        return JsonResponse({'msg': 'send'})
    return JsonResponse({})

utils.py
import base64, uuid
from django.core.files.base import ContentFile

def get_report_image(data):
    _ , str_image = data.split(';base64')
    decoded_img = base64.b64decode(str_image)
    img_name = str(uuid.uuid4())[:10] + '.png'
    data = ContentFile(decoded_img, name=img_name)
    return data

urls.py
from django.urls import path
from .views import create_report_view

app_name = 'reports'

urlpatterns = [
    path('save/', create_report_view, name='create-report'),
]

forms.py
from django import forms
from .models import Report

class ReportForm(forms.ModelForm):
    class Meta:
        model = Report
        fields = ('name', 'remarks')

I'm not sure why but this is the error I'm getting. Does this mean that is_ajax() is no longer accepted with Django 4.1.1? If so how would I need to adjust the code?
if request.is_ajax():
AttributeError: 'WSGIRequest' object has no attribute 'is_ajax'
[21/Sep/2022 07:23:39] "POST /reports/save/ HTTP/1.1" 500 98007

A: here is a way to implement is_ajax to every request:

*

*create a middlewares.py in any of your app, in my case, common app. (it does not matter which app you add this in, middlewares are wrapper functions called globally to perform action before or after view).

class AjaxMiddleware:
def init(self, get_response):
self.get_response = get_response
    def __call__(self, request):
        def is_ajax(self):
            return request.META.get('HTTP_X_REQUESTED_WITH') ==
                   'XMLHttpRequest'

        request.is_ajax = is_ajax.__get__(request)
        response = self.get_response(request)
        return response

this will define a is_ajax method on every request before it is received by the view.

*plug this in settings.py:
MIDDLEWARE = [
'common.middleware.AjaxMiddleware',
]
And this will solve your error.

A: Ok, seems to be working now. request.is_ajax is deprecated since django 3.1 and has been removed since django 4
if request.headers.get('x-requested-with') == 'XMLHttpRequest':

instead of
if request.is_ajax:


text:
Q: Use cfdirectory to find unmatched files in two directories and perform function In my application the user uploads a photos and the cfc resizes the photo, creates a new image and resizes that new image to a thumbnail. Trouble is, this function wasn't available earlier on in the game. I want to now look at the images directory and figure out which images don't have thumbnails.
I'm thinking that I could use cfdirectory to output a struct of both directories then loop over the files that only exist in the images and not in the thumbnails directory and run a function to resize the images and send them to the thumbnails directory.
Is this flawed thinking? Is there an easier way?

A: That's a perfectly reasonable approach, and you don't even have to use recursive code. Just use the recursive option in CFDirectory to get a list of all files and use both the file name and path combined as the key, which guarantees a unique file you're checking. You may have to modify the result a bit so you know exactly where to put the new thumbnail, but this should get you pretty close.
<cfset originals_path = expandPath('originals') />
<cfset thumbs_path = expandPath('thumbs') />

<cfset no_thumbs = find_missing_thumbs(originals_path, thumbs_path) />
<cfdump var="#no_thumbs#" />

<cffunction name="find_missing_thumbs">
    <cfargument name="o" />
    <cfargument name="t" />

    <cfset var originals = 0 />
    <cfset var thumbs = 0 />
    <cfset var missing_thumbs = [] />
    <cfset var massaged_originals = 0 />
    <cfset var massaged_thumbs = 0 />
    <cfset var qSearch = 0 />

    <cfdirectory action="list" directory="#arguments.o#" name="originals" recurse="true" />
    <cfdirectory action="list" directory="#arguments.t#" name="thumbs" recurse="true" />

    <cfquery name="massaged_originals" dbtype="query">
        select name, directory + name as fullpath from originals
    </cfquery>
    <cfquery name="massaged_thumbs" dbtype="query">
        select name, directory + name as fullpath from thumbs
    </cfquery>

    <cfloop query="massaged_originals">
        <cfquery name="qSearch" dbtype="query">
            select massaged_thumbs.name from massaged_thumbs where massaged_thumbs.fullpath = '#massaged_originals.fullpath#'
        </cfquery>
        <cfif qSearch.recordCount eq 0>
            <cfset arrayAppend(missing_thumbs, massaged_originals.name) />
        </cfif>
    </cfloop>
    <cfreturn missing_thumbs />
</cffunction>


text:
Q:  and  seem have different line-heights, how to go around it? The button is 2px bigger then the a tag with same styles. Any ideas why is it doing it and how to fix it?
jsfiddle
Some Text
<button> Some Text</button>

a, button {
  background-color: red;
  border: none;
  text-decoration: none;
  font-size: 14px;
  line-height: 14px;
  font-family: Verdana;
  display: inline-block;
  color:black;
  padding:0;
}

A: The button has padding.
Set padding : 0; on the button and they will look the same
Firefox has its own thing...
Try adding the following:
button::-moz-focus-inner {
    border: 0;
    padding: 0;
}


text:
Q: Instantiating a generic type from a dictionary I have a few classes that implement the ITerminalCommand interface:
public class TerminalCommandHelp : MonoBehaviour, ITerminalCommand { //... }
public class TerminalCommandExit : MonoBehaviour, ITerminalCommand { //... }

In a separate class, I would like to be able to look up a string in a dictionary and create a new instance of the ITerminalCommand, but I don't know how I would go about doing this, so below I have written some sort of pseudo-code in the hopes that someone might understand what I am trying to do.
Dictionary<string, ITerminalCommand> validInputs = new Dictionary<string, ITerminalCommand>()
    {
        {
            "help",
            //Some reference to the TerminalCommandHelp class so I can instantiate it at my own will
        },

        {
            "exit",
            //Some reference to the TerminalCommandExit class so I can instantiate it at my own will
        }
    };

    //Create a new object based on the key I am looking up, and supply some arguments to the constructor
     ITerminalCommand genericTerminalCommand = new validInputs["help"](arguments);

    //Run a method on the newly instantiated object
    genericTerminalCommand.Execute();

How can I 'abstractly' reference a class type in a dictionary so I can instantiate it and also supply some arguments to it?

A: Try this code:
Dictionary<string, Type> validInputs = new Dictionary<string, Type>()
{
    { "help", typeof(TerminalCommandHelp) },
    { "exit", typeof(TerminalCommandExit) },
};

ITerminalCommand genericTerminalCommand = (ITerminalCommand)Activator.CreateInstance(validInputs["help"]);


text:
Q: BizTalk mapper does not display element of external Data Structure Type residing in other assembly I am having trouble mapping to a target element, which is an imported element in the destination schema, specified via the Data Structure Type setting. The actual import is from another assembly (NuGet - no source xsd).
The schema editor displays the actual entity schema correctly and I am able to navigate the schema tree in editor:

Then when I try to use that schema in a map, the imported node is displayed only with its parent node, it is not possible to expand its child nodes.

Anyone? 2020 issue?

A: Some options:

*

*Install the NuGet reference in your map project as you did in your schema project for the imported element.

*Try using another value for 'Origin' since you now have a nested Origin - Origin structure that might be too complicated.

*Try setting the reference path as an absolute or relative, see if it makes a difference.

*Try to use the complex or simple type on the Data Structure Type dropdown if that's available on the imported schema.

A: As described, this seems to be a bug.


text:
Q: User systemd service to call rfkill (from NetworkManager) does not work at Shutdown I writing my first systemd service which is a radio manager service. It is oneshot and is meant to run at system boot and system shutdown. It will call rfkill to either block or unblock Wifi and/or bluetooth so it depends on NetworkManager. I would like to try and keep the service as a user service unless I have to make it a system service.
I have also setup the system so that user pi with loginctl so it lingers.
My problem is that the service is called at shutdown but wifi and bluetooth radios are not blocked as I would have expected. Any suggestions are appreciated. Thanks!!!!!
Here is my service file:
    [Unit]
    Description=RAL Radio Manager BT and Wifi Service
    After=network.target

    [Service]
    Type=oneshot

    WorkingDirectory=/home/pi/RAL/radio-manager
    Environment=PYTHONUNBUFFERED=1
    ExecStart=/usr/bin/python3 /home/pi/RAL/radio-manager/radio_manager.py -bs=1
    ExecStop=/usr/bin/python3 /home/pi/RAL/radio-manager/radio_manager.py -bs=0
    RemainAfterExit=yes
    Restart=no

    [Install]
    #WantedBy=multi-user.target
    WantedBy=default.target

Here is my python script
def radio_manager(args):
    MAGNET_OR_SWITCH_GPIO = 4
    PROGRAM_EXIT_GPIO = 22

    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM )                               # .BCM refs the GPIO by the GPIO#, .BOARD by Pin number
    GPIO.setup( MAGNET_OR_SWITCH_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_UP)      # RPi Header Pin  7,  GPIO4, reads the onboard swx state S2.
    GPIO.setup(PROGRAM_EXIT_GPIO, GPIO.IN, pull_up_down=GPIO.PUD_DOWN )

    #radio_list = rfkill.rfkill_list()

    if (args.boot_state == 0):
        #Power Down

        rfkill.rfkill_blockby('wlan')
        print ("Blocking WIFI!!!!!")

        rfkill.rfkill_blockby('bluetooth')
        print ("Blocking Bluetooth!!!!!")

    elif(args.boot_state == 1):
        #Power Up
            program_exit_pin = GPIO.input(PROGRAM_EXIT_GPIO)
            user_requests_wifi = os.path.exists(WIFI_ON_FILE_PATH)
            if (program_exit_pin or user_requests_wifi):
                rfkill.rfkill_unblockby('wlan')
                print ("UnBlocking WIFI!!!!!")

            magnet_pin = GPIO.input(MAGNET_OR_SWITCH_GPIO)
            if(magnet_pin == 0):
                rfkill.rfkill_unblockby('bluetooth')
                print ("UnBlocking Bluetooth!!!!!")

    return

def main(argv):

     args=cli(argv)

     radio_manager(args)

     return 0

if __name__ == '__main__':
     sys.exit(main(sys.argv))

Edit:
First I re-enabled and started my service. See timestamp 22:17:42 onwards
pi@raspberrypi:~$ systemctl --user enable radio_manager.service
Created symlink /home/pi/.config/systemd/user/default.target.wants/radio_manager.service â /home/pi/.config/systemd/user/radio_manager.service.
pi@raspberrypi:~$ systemctl --user start radio_manager.service
pi@raspberrypi:~$ journalctl --user-unit radio_manager.service
-- Logs begin at Thu 2020-08-20 20:04:47 BST, end at Thu 2020-08-20 22:17:43 BST
Aug 20 20:05:14 raspberrypi systemd[370]: Starting RAL Radio Manager BT and Wifi
Aug 20 20:05:16 raspberrypi systemd[370]: Started RAL Radio Manager BT and Wifi
Aug 20 21:42:49 raspberrypi systemd[370]: Stopping RAL Radio Manager BT and Wifi
Aug 20 21:42:51 raspberrypi python3[650]: Blocking WIFI!!!!!
Aug 20 21:42:51 raspberrypi python3[650]: Blocking Bluetooth!!!!!
Aug 20 21:42:51 raspberrypi systemd[370]: radio_manager.service: Succeeded.
Aug 20 21:42:51 raspberrypi systemd[370]: Stopped RAL Radio Manager BT and Wifi
Aug 20 22:17:42 raspberrypi systemd[370]: Starting RAL Radio Manager BT and Wifi
Aug 20 22:17:43 raspberrypi systemd[370]: Started RAL Radio Manager BT and Wifi

rfkill showed both interfaces were unblocked as expected. After sudo shutdown and boot up
pi@raspberrypi:~$ journalctl --user-unit radio_manager
-- Logs begin at Thu 2020-08-20 22:22:23 BST, end at Thu 2020-08-20 22:25:04 BST
Aug 20 22:22:51 raspberrypi systemd[359]: Starting RAL Radio Manager BT and Wifi
Aug 20 22:22:53 raspberrypi systemd[359]: Started RAL Radio Manager BT and Wifi
lines 1-3/3 (END)
pi@raspberrypi:~$
pi@raspberrypi:~$ rfkill list
0: phy0: Wireless LAN
        Soft blocked: no
        Hard blocked: no
1: hci0: Bluetooth
        Soft blocked: no
        Hard blocked: no
pi@raspberrypi:~$

Edit:
I turned on persistent systemd journal and I now see that my service is called at Shutdown but perhaps after the rfkill is shutdown or stops listening for commands. I have attached a truncated system log from shutdown with key points
Aug 21 16:18:23 raspberrypi sshd[522]: pam_unix(sshd:session): session opened fo
Aug 21 16:18:23 raspberrypi systemd-logind[253]: New session c1 of user pi.
Aug 21 16:18:23 raspberrypi systemd[1]: Started Session c1 of user pi.
Aug 21 16:18:30 raspberrypi systemd[1]: systemd-hostnamed.service: Succeeded.
Aug 21 16:23:20 raspberrypi sudo[560]:       pi : TTY=pts/0 ; PWD=/home/pi ; USE    <----------- Sudo shutdown now issued
Aug 21 16:23:20 raspberrypi sudo[560]: pam_unix(sudo:session): session opened fo
Aug 21 16:23:21 raspberrypi sudo[560]: pam_unix(sudo:session): session closed fo
Aug 21 16:23:21 raspberrypi systemd[1]: Unmounting RPC Pipe File System...
Aug 21 16:23:21 raspberrypi sshd[522]: pam_unix(sshd:session): session closed fo
Aug 21 16:23:21 raspberrypi sshd[522]: pam_systemd(sshd:session): Failed to rele
Aug 21 16:23:21 raspberrypi systemd[1]: Stopping Session c1 of user pi.
Aug 21 16:23:21 raspberrypi systemd[1]: systemd-rfkill.socket: Succeeded.           <------------ Is this the service I need to set the radio status using rfkill
Aug 21 16:23:21 raspberrypi systemd[1]: Closed Load/Save RF Kill Switch Status /
Aug 21 16:23:21 raspberrypi systemd[1]: Stopped target Bluetooth.
Aug 21 16:23:21 raspberrypi systemd[364]: run-rpc_pipefs.mount: Succeeded.
Aug 21 16:23:21 raspberrypi systemd[1]: Stopping Authorization Manager...

Aug 21 16:23:23 raspberrypi systemd[1]: Stopping Manage Sound Card State (restor
Aug 21 16:23:23 raspberrypi systemd[364]: Stopping RAL Radio Manager BT and Wifi    <------ SystemD executing ExecStop for my service
Aug 21 16:23:23 raspberrypi systemd[1]: Removed slice system-getty.slice.
Aug 21 16:23:23 raspberrypi systemd[1]: rc-local.service: Succeeded.
Aug 21 16:23:23 raspberrypi systemd[1]: Stopped /etc/rc.local Compatibility.
Aug 21 16:23:23 raspberrypi alsactl[290]: alsactl daemon stopped
Aug 21 16:23:23 raspberrypi systemd[1]: systemd-logind.service: Succeeded.
Aug 21 16:23:23 raspberrypi systemd[1]: Stopped Login Service.
Aug 21 16:23:23 raspberrypi systemd[1]: raspi-config.service: Succeeded.
Aug 21 16:23:23 raspberrypi systemd[1]: Stopped LSB: Switch to ondemand cpu gove
Aug 21 16:23:23 raspberrypi systemd[1]: alsa-state.service: Succeeded.
Aug 21 16:23:23 raspberrypi systemd[1]: Stopped Manage Sound Card State (restore
Aug 21 16:23:24 raspberrypi systemd[1]: hciuart.service: Succeeded.
Aug 21 16:23:24 raspberrypi systemd[1]: Stopped Configure Bluetooth Modems conne
Aug 21 16:23:24 raspberrypi wpa_supplicant[282]: wlan0: CTRL-EVENT-DISCONNECTED
Aug 21 16:23:24 raspberrypi wpa_supplicant[282]: dbus: wpa_dbus_property_changed
Aug 21 16:23:24 raspberrypi dhclient[398]: receive_packet failed on wlan0: Netwo
Aug 21 16:23:25 raspberrypi python3[591]: Blocking WIFI!!!!!                        <------ My service is trying to Softblock WIFI
Aug 21 16:23:25 raspberrypi python3[591]: Blocking Bluetooth!!!!!                   <------ My service is trying to Softblock Bluetooth
Aug 21 16:23:24 raspberrypi wpa_supplicant[282]: wlan0: CTRL-EVENT-REGDOM-CHANGE
Aug 21 16:23:25 raspberrypi wpa_supplicant[282]: rfkill: WLAN soft blocked
Aug 21 16:23:25 raspberrypi wpa_supplicant[282]: rfkill: WLAN soft blocked
Aug 21 16:23:25 raspberrypi wpa_supplicant[282]: nl80211: Failed to open /proc/s
Aug 21 16:23:25 raspberrypi wpa_supplicant[282]: nl80211: Failed to set IPv4 uni
Aug 21 16:23:25 raspberrypi NetworkManager[269]: <info>  [1598023405.1102] manag
Aug 21 16:23:25 raspberrypi NetworkManager[269]: <info>  [1598023405.1197] devic
Aug 21 16:23:25 raspberrypi NetworkManager[269]: <info>  [1598023405.1415] dhcp4
Aug 21 16:23:25 raspberrypi NetworkManager[269]: <info>  [1598023405.1441] dhcp4
Aug 21 16:23:25 raspberrypi NetworkManager[269]: <info>  [1598023405.2310] dns-m
Aug 21 16:23:25 raspberrypi systemd[364]: radio_manager.service: Succeeded.
Aug 21 16:23:25 raspberrypi systemd[364]: Stopped RAL Radio Manager BT and Wifi     <------ Systemd stopped by service
Aug 21 16:23:25 raspberrypi systemd[364]: Stopped target Basic System.
Aug 21 16:23:25 raspberrypi systemd[364]: Stopped target Timers.
Aug 21 16:23:25 raspberrypi systemd[364]: Stopped target Sockets.

A:
After=network.target

User units cannot depend on system units. This includes "ordering dependencies" like After=.  network.target is a system unit.  So this line will not do anything.
On the other hand, user units run inside the system unit user@.service.  This unit is already (indirectly) ordered After=network.target.
On the gripping hand, I think polkit.service will quit immediately on shutdown, and probably cannot be re-activated.  Perhaps that is your problem.  polkit is used to grant permissions like allowing logged-in users to manipulate rfkill.


text:
Q: Converting Request body to DTO with different fields structure in Spring Web app Spring Web works perfectly in scenarios when rest controller takes a custom object, entity or dto, as parameter of handler method. You just need to annotate it with @RequestBody annotation. But how can I handle cases when the object has different field names or structure? I.e. for request json like
{"name":"FirstName", "address" : { "city" : "Rome" }}
to 'flattened' structure like
class Person { private String name; private String city; }
Is it possible to create a custom converter like HttpConverter, but for specific controller handler method only?

A: I think the easies way is to make a DTO matching the structure of the incomming json so Spring can map the json to this DTO. Then you can map this DTO to your Person class in your controller.
If your mapping is simple it is easiest to just write the mapping yourself. If not you can use a mapping tool like https://github.com/mapstruct/mapstruct or http://modelmapper.org/.
Please let me know if this is usefull.


text:
Q: woocommerce - get total purchased items I want to get count of total number of items purchased on my wordpress site and display this number somewhere. I am using woocomerce 1.6.6 plugin and i want some shortcode or function or db query to do this.
Please help.

A: I realise this question is well over a year old, but for anyone who stumbles upon it, like I just did, here's how to get the total number of sales of all products in Woocommerce. I needed this for a project since for each product purchased, one is to be donated to people in need. Hence, I wanted to show the total number of donations (= sales).
Each product has a total_sales meta field, so all we need to do is query the database for the sum of all products' total_sales:

function get_number_of_sales() {
  global $wpdb;

  $result = $wpdb->get_row("
      SELECT SUM(pm.meta_value) AS total_sales
      FROM $wpdb->posts AS p
      LEFT JOIN $wpdb->postmeta AS pm ON (p.ID = pm.post_id AND pm.meta_key = 'total_sales')
      WHERE p.post_type = 'product'
  ");

  return $result->total_sales;

}

Based on this answer.


text:
Q: Finding shortest distance from a point to line through direction vector Find the shortest distance from a point $P(1,3,-2)$ to the line through $P_0 (2,0,-1)$ with direction vector $d = (1, -1, 0)$.
I know how to find distance between a point $(x,y)$ and a line $ax+by+c=0$ but I have no idea how to find it through another point and what & how to use direction vector.

A: If you want to use cross-product: as you know, $$|a\times b|=|a||b|\sin\theta$$ where $\theta$ is the angle between vectors $a$ and $b$
The shortest distance you require is $$|PP_0|\sin\theta$$ where $\theta$ is the angle between the vector $PP_0$ and the direction vector of the line.
Can you take it from there?

A: A point along the line is parametrized as
$$\mathbf{r} = \mathbf{P}_0 + t\, \mathbf{d} $$
The distance to a point is $\| \mathbf{r}-\mathbf{P} \|$ and finding the minimum is equivalent to finding the value of $t$ that minimizes the following
$$ \rho^2 = \| \mathbf{r}-\mathbf{P} \|^2 = \left( \mathbf{r}-\mathbf{P}  \right) \cdot \left( \mathbf{r}-\mathbf{P}  \right) $$
$$ \rho^2 = \left( \mathbf{P}_0-\mathbf{P} + t\, \mathbf{d} \right) \cdot\left( \mathbf{P}_0-\mathbf{P} + t\, \mathbf{d} \right) $$
Distribute the expression before differentiating to get
$$\rho^2 =\left( (\mathbf{P}_0-\mathbf{P}) \cdot (\mathbf{P}_0-\mathbf{P})\right)^2 + 2 t \left((\mathbf{P}_0-\mathbf{P}) \cdot \mathbf{d}\right) + t^2\, (\mathbf{d} \cdot \mathbf{d})^2 $$
$$ \left. \frac{{\rm d} \rho^2}{{\rm d} t} = 0  \right\} t = \frac{\mathbf{d} \cdot (\mathbf{P}-\mathbf{P}_0)}{(\mathbf{d}\cdot\mathbf{d})} $$
The point is found by plugging $t$ into the equation of the line
$$ \mathbf{r} = \mathbf{P}_0 + t\, \mathbf{d} $$

 In your case I got $t=-2$ and $\mathbf{r}=(0,2,-1)$

A: The squared distance to any point on the line is
$$(2+t-1)^2+(-t-3)^2+(-1+2)^2=2(t+2)^2+3$$ so the shortest distance is $\sqrt3$ (when $t=-2$).


text:
Q: Missing column header when converting to excel After converting the datagridview data to excel i have a missing column header. Tried a few codes in different guide but still do not get the header am i missing any thing?
private void convert_Click(object sender, EventArgs e)
    {

        Microsoft.Office.Interop.Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
        Microsoft.Office.Interop.Excel.Workbook workbook = app.Workbooks.Add(Type.Missing);
        Microsoft.Office.Interop.Excel.Worksheet worksheet = null;
        worksheet = workbook.Sheets["Sheet1"];
        worksheet = workbook.ActiveSheet;
        worksheet.Name = "Unmatched";
        for (int i = 1; i < dataGridView2.Columns.Count + 1; i++)
        {
            if (dataGridView2.Columns[i - 1].Visible)
            {
                worksheet.Cells[i, 1] = dataGridView2.Columns[i - 1].HeaderText;
            }
        }
        for (int i = 0; i < dataGridView2.Rows.Count; i++)
        {
            for (int j = 0; j < dataGridView2.Columns.Count; j++)
            {
                if (dataGridView2.Rows[i].Cells[j].Value != null)
                {
                    worksheet.Cells[i + 2, j + 1] = dataGridView2.Rows[i].Cells[j].Value.ToString();
                }
            }
        }
        var saveFileDialog = new SaveFileDialog();
        saveFileDialog.FileName = "report";
        saveFileDialog.DefaultExt = ".xlsx";
        if (saveFileDialog.ShowDialog() == DialogResult.OK)
        {
            workbook.SaveAs(saveFileDialog.FileName, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
        }
        app.Quit();
    }

what excel have
What it should have and what is in datagridview

A: worksheet.Cells[i] = dataGridView2.Columns[i - 1].HeaderText;


text:
Q: Running test with "usbtest" on Ubuntu i am newbie to these modules and device drivers and all.I would like run some sample tests on ubuntu main tree USB driver. I have seen this document and was trying to do the same.I do inserted the "usbtest" module and while trying to run

usbtest

command, terminal says the command not found
I have tried to insert g_zero module by running

modprobe g_zero

,but it says

modprobe: ERROR: could not insert 'g_zero': No such device

and

modprobe --force g_zero says
modprobe: ERROR: could not insert 'g_zero': Exec format error

Anyone Please post better simple explanation..
I'm using Ubuntu 14.04.3 LTS and my kernel is 3.13.0-24-generic
Also please suggest any method to test linux main tree drivers through command line.


text:
Q: How to make iTerm autocomplete a partial command when pressing the 'up' arrow key? I currently have iTerm version 3.4.12.
In my old work computer I had a different version that would autocomplete a partial command based on the previous commands I had typed when pressing the up key, for example if at some point I ran:
cd Desktop
And then I went back to the folder where I ran it and tried typing
cd De
Followed by pressing the up key it would autocomplete to cd Desktop
Now I'm on a different computer and pressing the up key simply goes through the history of commands I've ran regardless of the folder I'm in or what I've typed, how can I make it so it autocompletes paritially based on my history instead?

A: Brief
Hi, actually this is what are you looking for oh-my-zsh.
It's a really complete framework for zsh that brings a lot of functionality and the capability to add external plugins.
Installation

*

*Execute the following in your terminal

$ sh -c "$(curl -fsSL https://raw.githubusercontent.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"

*it should updated your ~/.zshrc file with a bunch of stuff including some default useful plugin, you can restart your terminal or resource the configuration file just typing

$ zsh

Plugins
You can find other external plugin like zsh-autosuggestions, this actually brings you an autocomplete feature during the typing phase

To Install this as other plugin you can follow this

*

*Open your .zshrc configuration file inside your terminal

$ vi ~/.zshrc

Note
if vi does not work try to use nano or vim instead, if you don't have even nano you can just open the file via GUI using any text editor

*Inside the configuration file, find the plugin section, and inside the round brackets add zsh-autosuggestions

 # Which plugins would you like to load?
 # Standard plugins can be found in ~/.oh-my-zsh/plugins/*
 # Custom plugins may be added to ~/.oh-my-zsh/custom/plugins/
 # Example format: plugins=(rails git textmate ruby lighthouse)
 # Add wisely, as too many plugins slow down shell startup.
 plugins=(
 git
 bundler
 dotenv
 osx
 rake
 zsh-autosuggestions
 last-working-dir
 web-search
 brew
 extract
 history
 sudo
 yarn
 )

*Restart your terminal and you should be done! For more information you can find the github repo of oh-my-zsh


text:
Q: Can someone find my Stack Exchange account seeing my Google account? Because I don't want people in my Google+ circles to find about I have a stack exchange account (which I login with Google). I'm in many Q&A communities of Stack Exchange, since as Math SE, Super User and many others, and I don't want anyone who knows my Google account or has me in his circles to find the profile in Stack Exchange.
It's possible to find out the Stack Exchange accounts from the Google+ profile, or YouTube? Does Stack Exchange share something by default?

A: According to the privacy policy:

Other than on Careers, we won't share your personal information with non-agent third parties unless we are required to do so by law, or if we believe in good faith that disclosure is reasonably necessary to protect our property, rights or those of third parties or the public at large.

The "Legally Useless Summary for Short Attention Spans" version:

Outside of when you apply for job listings, we don't share your personal info with anyone.

It's possible to add a Google+ or YouTube profile to your Stack Exchange profile page. But we don't do that for you. It's also possible to put things, such as a distinctive avatar or display name, in your profile that will allow others to identify your Google+ account. Again, that's your choice, not ours.
Now, if you use Google as your OpenID provider, there is a connection between that account and your Stack Exchange account. But neither Google nor Stack Exchange expose that connection to third parties. I had to add my Stack Exchange profile to my Google+ about page manually; it wasn't added automatically. Google has its own privacy policy that you might want to examine.
If you are still concerned, you can use any number of other OpenID accounts, including the Stack Exchange OpenID system, to register your account. It's easy to change and we don't mind.


text:
Q: Can I remotely change configuration of applications monitored by MS Application Insights? I have very little experience with application insights, except for the "hello world" programs I have put together, created a few custom events, forwarded messages from log4net.
As I am beginning to add this into more applications I am wondering "Can I remotely turn on more detailed logging information, in an ad-hoc fashion?"  More specificly I would like to have App Insights doing what it normally does and continue to log exceptions, requests, and what not....but on particularly busy times I would like to enable more of a "performance monitoring" aspect for a couple of hours, but without having to deploy a new version of the application to everyone.
I haven't seen anything online that speaks about something close to this, but I also may not know the appropriate keywords to look for.

A: You need to have enabled App Insights in the package. There's no other way... but as a workaround:
You should publish the site and an additional deployment slot with fewer resources (to reduce costs). Every time you update your solution you should deploy it to production and the "other slot".
When you need to "turn on" App insights just swipe between "other slot" and "production slot" , get all data you have and then when you don't need insights anymore swipe again between them.
You can also shutdown the deployment slot and just power it on when you need to make the magic.

A: What other data would you like to see registered? Right now, all configuration for telemetry capture in Application Insights is directly related to what telemetry modules and context initializers you have configured in ApplicationInsights.config, and there's really no way to dynamically add more to that.
However, nothing prevents you from manually adding additional custom events through the use of TelemetryClient directly, and you could certainly control the code that calls this through other means.
Can you maybe expand on what other kind of data you'd like to see captured?

A: You can implement a Telemetry Channel (http://apmtips.com/blog/2015/09/03/more-telemetry-channels/) that will filter out (or not) some non-critical telemetry based on some state/flag. Or you can have two telemetry channels (one standard and one custom) and swap them based on flag.
Better yet, you can consider using the new extensibility point, called Telemetry Processor - https://azure.microsoft.com/en-us/blog/request-filtering-in-application-insights-with-telemetry-processor/ to do the same
Then you can implement a remote call to your app (e.g. have a special URL) that will change this flag.


text:
Q: Not showing device in target window after Android Studio update 2.3 I recently updated my Android Studio to 2.3. Now it doesn't show my usb device(Sony C2305) in Select Deployment Target window which was working fine just before updating. When I connect my android device through USB Nothing to show is displayed in Select Deployment Target window. When I disconnect it, all emulators are showing.
Device is shown in Android Monitor, so connection is fine. But not displaying in Select Deployment Target window.
Eveything was fine just before Android Studio updating to 2.3

A: 1)disconnect and connect again device
2) go win taskManger
         process tab
         select adb.exe and click endtask
      cancel device chooser and check again

A: I checked stack traces of studio and found that the issue was due to some error in Firebase plugin after Android Studio update. I'm not even using firebase in current project so I don't know how that makes a problem. I just disable firebase plugin and then now my device is showing in the Select Deployment Target window.

A: In Android Studio 2.3 v162.3764568 this issue occurs due to a crash in Firebase Testing plugin.
Solution: Disable Firebase Testing plugin by going to File -> Settings and select Plugins on the left. Search for Firebase Testing and uncheck it and then click on Apply and OK.
Restart Android Studio and the issue is fixed for now.

A: Open console in android studio and try this :
adb kill-server ,
adb start-server ,
and,
adb devices


text:
Q: How to combine 2 values to form a node in Python I am using Python to read data from a file and assign the strings in one column to the integers in another column. This is what I have so far:
flight_source_graph = {}

with open('flightinfo.csv') as csvfile:
  reader = csv.reader(csvfile, delimiter=',')
  next(reader, None)
  for row in reader:
    flight_source = row[0]     #'ABC','XYZ','TWR'
    flight_dep_time = row[2]   #'0','10','7'

    #departure information
    if flight_source in flight_source_graph:
      flight_source_graph[flight_source].append(flight_dep_time)
    else:
      flight_source_graph[flight_source] = [flight_dep_time]

Output:

{'ABC': ['0', '10', '7'], 'XYZ': ['4','7','10'], 'TWR': ['9','11','15','24']}

Now that I have this data showing what's assigned to what, how would I go about transforming it to create a list that looks like this:
[('ABC', '0'),('ABC','10'),('ABC','7')]
#Where each of the values in the parentheses () would signify a node

A: This is one way to combine the keys with the list values:
if __name__ == '__main__':
    flight_info = {'ABC': ['0', '10', '7'], 'XYZ': ['4', '7', '10'], 'TWR': ['9', '11', '15', '24']}
    flight_graph = []
    for k, v in flight_info.items():
        for i in v:
            flight_graph.append((k, i))
    print(flight_graph)
    # [('ABC', '0'), ('ABC', '10'), ('ABC', '7'), ('XYZ', '4'), ('XYZ', '7'), ('XYZ', '10'), ('TWR', '9'), ('TWR', '11'), ('TWR', '15'), ('TWR', '24')]


text:
Q: why im getting this error in my code function returned null? Why my widget give this error ?:
======== Exception caught by widgets library =======================================================
The following assertion was thrown building StreamBuilder<UserData>(dirty, state: _StreamBuilderBaseState<UserData, AsyncSnapshot<UserData>>#1e46f):
A build function returned null.

The offending widget is: StreamBuilder<UserData>
Build functions must never return null.

To return an empty space that causes the building widget to fill available room, return "Container()". To return an empty space that takes as little room as possible, return "Container(width: 0.0, height: 0.0)".

The relevant error-causing widget was:
  StreamBuilder<UserData> file:///Users/name/StudioProjects/project/lib/seitenleiste/meinacount.dart:356:16
When the exception was thrown, this was the stack:
#0      debugWidgetBuilderValue.<anonymous closure> (package:flutter/src/widgets/debug.dart:305:7)
#1      debugWidgetBuilderValue (package:flutter/src/widgets/debug.dart:326:4)
#2      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4592:7)
#3      StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4759:11)
#4      Element.rebuild (package:flutter/src/widgets/framework.dart:4281:5)
...
====================================================================================================

This is my widget

  @override
  Widget build(BuildContext context) {
final user = Provider.of<Userr>(context);
        return StreamBuilder<UserData>(
          stream: DatbaseService(uid:user.uid).userData,
          builder: (context, snapshot) {
            if(snapshot.hasData){
              UserData userData =snapshot.data;
              return Container(
                child: Scaffold(
                  appBar: AppBar(
                    backgroundColor: Colors.transparent,
                    elevation: 0.0,
                  ),
                  body: AnnotatedRegion<SystemUiOverlayStyle>(
                    value: SystemUiOverlayStyle.light,
                    child: GestureDetector(
                      onTap: () => FocusScope.of(context).unfocus(),
                      child: Form(
                        key: _formKey,
                        child: Stack(
                          children: <Widget>[
                            Container(
                              height: double.infinity,
                              child: SingleChildScrollView(
                                physics: AlwaysScrollableScrollPhysics(),
                                padding: EdgeInsets.symmetric(
                                  horizontal: 40.0,
                                  vertical: 10,
                                ),
                                child: Column(
                                  mainAxisAlignment: MainAxisAlignment.center,
                                  children: <Widget>[
                                    Center(
                                      child: Stack(
                                        children: [
                                          Container(
                                            width: 110,
                                            height: 110,
                                            decoration: BoxDecoration(

                                                borderRadius: BorderRadius.circular(100),
                                                image: DecorationImage(
                                                    fit: BoxFit.cover,
                                                    image: NetworkImage(
                                                      "https://images.pexels.com/photos/3307758/pexels-photo-3307758.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=250",
                                                    ))),
                                          ),
                                          Positioned(
                                              bottom: 0,
                                              right: 0,
                                              child: Container(
                                                height: 35,
                                                width: 35,
                                                decoration: BoxDecoration(
                                                  shape: BoxShape.circle,
                                                  border: Border.all(
                                                    width: 4,
                                                    color: Theme.of(context)
                                                        .scaffoldBackgroundColor,
                                                  ),
                                                  color: Colors.green,
                                                ),
                                                child: Icon(
                                                  Icons.edit,
                                                  color: Colors.white,
                                                ),
                                              )),
                                        ],
                                      ),
                                    ),
                                    SizedBox(
                                      height: 10,
                                    ),
                                    Text(
                                      'Mein Profil',
                                      style: TextStyle(
                                        color: Colors.black,
                                        fontFamily: 'OpenSans',
                                        fontSize: 20.0,
                                        fontWeight: FontWeight.w600,
                                      ),
                                    ),
                                    showAlert2(),

                                      _buildEmailTF(userData),
                                    SizedBox(
                                      height: 30.0,
                                    ),
                                    _buildName(userData ),
                                    SizedBox(
                                      height: 30.0,
                                    ),
                                    _builduserName(userData),
                                    SizedBox(
                                      height: 30.0,
                                    ),
                                    _buildPasswordTF(userData),
                                    SizedBox(height: 30,),

                                    _buildPassword2TF(userData),
                                    _buildUpdateDataButton(),
                                    // _buildEmailform(),
                                  ],
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    ),
                  ),

                ),
              );

            }else{
              return null;
            }

          }
        );

      }

A: The error message is quite straightforward:
The offending widget is: StreamBuilder<UserData>
Build functions must never return null.

In your StreamBuilder, you are returning null if the snapshot has no data:
@override
Widget build(BuildContext context) {
  final user = Provider.of<User>(context);
  return StreamBuilder<UserData>(
    stream: DatbaseService(uid: user.uid).userData,
    builder: (context, snapshot) {
      if (snapshot.hasData) {
        ...
      } else {
        return null;
      }
    },
  );
}

The error message is providing the solution here:
To return an empty space that causes the building widget to fill
available room, return "Container()". To return an empty space
that takes as little room as possible,
return "Container(width: 0.0, height: 0.0)".

So, instead of returning null, just return an empty Container:
@override
Widget build(BuildContext context) {
  final user = Provider.of<User>(context);
  return StreamBuilder<UserData>(
    stream: DatbaseService(uid: user.uid).userData,
    builder: (context, snapshot) {
      if (snapshot.hasData) {
      } else {
        return Container();
      }
    },
  );
}

A: The answer is right in the error message:

A build function returned null.
The offending widget is: StreamBuilder
Build functions must never return null.
To return an empty space that causes the building widget to fill available room, return "Container()". To return an empty space that takes as little room as possible, return "Container(width: 0.0, height: 0.0)".

You're returning null in your else


text:
Q: SQL list employees manager's phone number and name if they dont have a manager This is from my homework, I was able to get number three easy enough but number four says to do the same as number three but also include those who do not have a manager. I cannot figure this one out, I tried case, iif, if then, etc I must be formatting it the wrong way but I cannot find anyhting helpful in my book. Please help.

*

*From the employees table, list the employee_id, last_name, and phone_number of every employee, along with the last_name and phone number of his manager. Sort the rows by employee_id. (Hint:tables can be joined to themselves.Just give each table a different alias).

SQL:
  SELECT a.employee_id,
         a.last_name,
         a.phone_number,
         b.last_name AS manger_name,
         b.phone_number AS manger_phone
    FROM l_employees a,
         l_employees b
   WHERE a.manager_id = b.employee_id
ORDER BY a.employee_id

A: The trick you're looking for is a left join:
SELECT    a.employee_id, a.last_name, a.phone_number,
          b.last_name AS manger_name, b.phone_number AS manger_phone
FROM      l_employees a
LEFT JOIN l_employees b ON a.manager_id = b.employee_id
ORDER BY  a.employee_id

This can also be done with Oracle's implicit join syntax (notice the (+)):
SELECT   a.employee_id, a.last_name, a.phone_number,
         b.last_name AS manger_name, b.phone_number AS manger_phone
FROM     l_employees a, l_employees b
WHERE    a.manager_id = b.employee_id (+)
ORDER BY a.employee_id

A: Just to add a little clarification to Mureinik's answer.  What's happening here is that normally with a join only rows from both tables where the relationship in the where clause is true are returned.  The outer join (left Join) or (+) tells it to return all the rows from the table on the left side, regardless of whether there is a match in the table on the right hand side, but if there is a match in the table on the right hand side, go ahead and fill in those columns too.  Outer joins like this are very powerful but there are a few things to look out for.

*

*Make sure you really want everything from the table on the left side.  If you don't put in some other clauses in your where clause to limit what is considered by table "A".

*The empty values (not in table "B" (managers)) in your case, are going to be NULL.  If you are using this in PLSQL or as a recordset being returned to a program somewhere, you might want to put some NVL statements around the potential NULL columns just to avoid errors.


text:
Q: ¿Cómo crear diferentes instancias de una clase con un bucle for? Con la clase que puede ver en la actualizacion de esta pregunta quiero  crear diferentes instancias de una clase con un bucle. Intenté el siguiente :
objs = [WordTree(sent, sent[0].label()) for sent in enumerate(sentences)]

sentences esta oraciones separadas por en_nlp :
['Beyoncé Giselle Knowles-Carter (/biːˈjɒnseɪ/ bee-YON-say) (born September 4, 1981) is an American singer, songwriter, record producer and actress.', "Born and raised in Houston, Texas, she performed in various singing and dancing competitions as a child, and rose to fame in the late 1990s as lead singer of R&B girl-group Destiny's Child.", "Managed by her father, Mathew Knowles, the group became one of the world's best-selling girl groups of all time.", 'Their hiatus saw the release of Beyoncé\'s debut album, Dangerously in Love (2003), which established her as a solo artist worldwide, earned five Grammy Awards and featured the Billboard Hot 100 number-one singles "Crazy in Love" and "Baby Boy".']

Sin embargo, cuando hago la instanciación no tengo nada.
>>>objs = [WordTree(sent, sent[0].label()) for sent in enumerate(sentences)]
>>>objs
[]


text:
Q: Creating robust real-time monitors for variables We can create a real-time monitor for a variable like this:
CreatePalette@Panel@Row[{"x = ", Dynamic[x]}]

(This is more interesting and useful if x happens to be something like $Assumptions.  It's so easy to set a value and then forget about it.)
Unfortunately this stops working if the kernel is re-launched (Quit[], then evaluate something).  The palette won't show changes in the value of x any more.
Is there a way to do this so it keeps working even across kernel sessions?  I find myself restarting the kernel quite often.  (If the resulting palette causes the kernel to be automatically started after Quit that's fine.)

Update:  As mentioned in the comments, it turns out that the palette ceases working only if we quit by evaluating Quit[].  When using Evaluation -> Quit Kernel -> Local, it will keep working.

*

*Link to same question on MathGroup.

A: I can only guess, because on my Ubuntu here the situations seems buggy. The trick with the Quit from the menu like Leonid suggested did not work here. Another one is: on a fresh Mathematica session with only one notebook open:
Dynamic[x]
x = 1
Dynamic[x]
x = 2

gives as expected
2
1
2
2

Typing in the next line Quit, evaluating and typing then x=3 updates only the first of the Dynamic[x].
Nevertheless, have you checked the command
Internal`GetTrackedSymbols[]

This gives not only the tracked symbols but additionally some kind of ID where the dynamic content belongs. If you can find out, what exactly these numbers are and investigate in the other functions you find in the Internal context, you may be able to add your palette Dynamic-content manually after restarting the kernel.
I thought I had something like that with
Internal`SetValueTrackExtra

but I'm currently  not able to reproduce the behavior.

A: @halirutan's answer jarred my memory...
Have you ever come across: Experimental/ref/ValueFunction? (documentation address)
Although the documentation contains no examples, the 'more information' section provides the following tidbit:

The assignment ValueFunction[symb] = f specifies that whenever
  symb gets a new value val, the expression f[symb,val] should be
  evaluated.


text:
Q: GAC folders - too many? Im getting confused
one time and for all
the VS add reference (/net tab) says that dll's gac are here :

And I found this folder which contains GAC :  ( p.s. why 3 Gac's types ? )

And also  this folder which contains GAC :

Can someone  , please , fix my headache ?

A: %ProgramFiles%\Reference Assemblies\Microsoft\Framework\v4.0" folder contains those assemblies that ship with the .Net Framework which are useful for referencing during the design and build of new components. See http://blogs.msdn.com/b/msbuild/archive/2007/04/12/new-reference-assemblies-location.aspx. This is not at all a GAC.
There are two distinct GACs, one for CLR 2.0 and other for CLR 4.0. The one %windir%\assembly is used by CLR 2.0 (.Net 2.0 to 3.5) while %windir%\Microsoft.NET\assembly is used by the CLRs greater than 2.0 (currently 4.0 only).

A: After installing .NET 4 there are actually two GACs in your system, one for .NET version 2-3.5 and one for version 4. This is already explained here. Each of those directories has a number of subfolders which contain assembly images with code in x86, x64 and MSIL.
The "reference assemblies" directory inside Program Files is not a GAC.
To answer Alex Dn's comment as well: you should not care where the DLL goes once you install it in the GAC. The very purpose of gacutil is to hide this knowledge from you so that .NET doesn't go the familiar way of picking up dependencies from people who partially "reverse-engineer" how stuff works and then e.g. hardcode a path inside their application.

A: I thinks it's in two paths for historic reasons.
They must have split the assemblies for each platform (such as MSIL, Native 32, Native 64, Embedded, ARM, ...)
So depending on how you compile your process you will link one or another deps.
So between portable .net (only MSIL) and Managed C++ (only Native)...
But i'm not sure at all :)


text: Q: How to build the code for mobile app neglecting the web based components? I have to create an application which is supported for both web, and mobile devices. So I opted for React-native, which I am new to. I build the project completely for both the mobile view, and the web view. The problem now is, how to build the code only for the mobile app neglecting the code that is applied for the web view. The build size increases for the mobile app when I build it. Any solution for this?


text:
Q: How to install next-js with react 17? How I can install next.js with React 17? When I type:
npx create-next-app --ts, npx installed Next with React 18, but I can't use React 18, because Stripe not working at the moment with R18 (https://www.npmjs.com/package/stripe).

A: You'd need to use an older version of Next JS.
The latest one I can see with React 17 is 12.1.2, so you can start your project with the following:
npx create-next-app@12.1.2

You can check the release change logs for Next JS here:
https://github.com/vercel/next.js/releases

A: If you've already created the project:
remove new versions:
npm uninstall next react react-dom @types/react @types/react-dom

install old versions:
npm install next@12.1.2 react@17.0.2 react-dom@17.0.2
npm install -D @types/react@17.0.2 @types/react-dom@17.0.2

A: I found an alternative approach , first create a new nextjs typescript project using    npx create-next-app@latest --ts
. And then copied the versions of all the dependencies and devDependencies to package.json . after replacing the version delete node_modules folder and package-lock.json file . after that run this command npm install .
Here is a sample package.json. I got this after create new nextjs project.
   {
  "name": "demo",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "next": "12.2.4",
    "react": "17.0.2",
    "react-dom": "17.0.2"
  },
  "devDependencies": {
    "@types/node": "18.7.1",
    "@types/react": "18.0.17",
    "@types/react-dom": "18.0.6",
    "eslint": "8.21.0",
    "eslint-config-next": "12.2.4",
    "typescript": "4.7.4"
  }
}


text:
Q: Multi Key Multi Value map possible? I see there is a Multimap that allows duplicate values for a key http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html
I also noticed guava has a Table which allows multiple keys, but not duplicated values. http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Table.html
I can't find anywhere where there is a "Table" that allows duplicated values, or a "Multimap" that allows multiple keys.
Is this something that exists already, or would I have to implement this myself?
I just want to implement a Multimap with 2 keys i.e. <K1, K2, Value>

A: There's nothing I'm aware of that supports that need.  However, it's not terribly difficult to just e.g. use a Multimap<MyK1AndK2Pair, Value> where you write a custom pair class yourself, or conversely to use a Table<K1, K2, List<Value>> and manage things yourself.

A: What about nested maps?
Multimap<K1, Multimap<K2, Value>> doubleMultiMap = new HashMultiMap<>();

A: I think you can use MultiKeyMap of Apache Commons. Its description says -
A Map implementation that uses multiple keys to map the value.


text:
Q: Multiple statements on a single query with Adonisjs I'd like to pass a several statements on a single line query. It's possible?
const sql = 'update table set column where id = ?;
             delete from table where id = ?
             delete from table where id = ?
             select * from table where id IN (select id from table where id = ?)'
await Database.rawQuery(`sql`, [id, id, id, id])

I tried this way but doesn't work. Somente could helpe me? Thanks

A: I resolved this question with transaction. Like this.
await Database.transaction(async (trx) => {
      await trx.from('table').where('id', id).update({column: value})
      await trx.from('table').where('id', id).delete()

})


text:
Q: How do I use Blender models in Java? Just a general question really?
Let's say I am making a game and have made a character model in Blender. How would I use this model in Java?
Would I import it somehow?
Thanks.

A: There are input/output scripts available for Blender that will help you.
Blend2Java, for example, is a set of Python scripts for use with Blender that will export to Java XML, which can be decoded with the standard java.beans.XMLDecoder class.
There's a good overview of how to do this at http://blend2java.sourceforge.net/blend2java-howto.html

A: Here's a better idea: Use an existing Java 3D library (dzzd I highly recommend) and load in your model using the library's built in functions. Then, instead of just working with the data, you can actually display it. From Blender, it's a simple matter of exporting as 3DS.

A: Yet another solution: Java .Blend provides you with a type-safe Java API to all data in a Blender file. It supports even creating new Blender files from within Java ;)

A: Generally when making models in blender you export the model in a format which allows you to later import it in the game engine of your choice, which format you use differ in requirements.
The export-import cycle is often referred to as the "Asset Pipeline", and you generally want to keep it as simple and automated as possible since it is something you or your artists will perform on a regular basis.
So if we look at a few specific graphics engines and platforms;

*

*OGRE3D (or Ogre4J) supports it's own plain-text format (.scene, .mesh.xml, .material.xml) in order to load scenes, models and materials. It also has support for armature animations among other things, there is also some support for loading .blend-files directly. See their documentation for blender.

*JmonkeyEngine has support for loading both OGRE3D .scene's and .blend's directly. It also has it's own binary j3o format which these can be converted into when you want to package the game. For specific examples, see their tutorials.

There are multiple formats you can take into consideration when deciding how you want to use your model. When it is imported however, the game engine of choice represents it in an internal structure which usually allows you to be decoupled from the exact format of choice.
Picking which to use is and should not be written in stone since requirements might change and if done properly it should not have a considerable effect on the project. This is also something you should take into consideration if you are writing your own engine.


text:
Q: How do geometers define "locally looks like" in differential geometry? From reading some introductory texts on differential geometry, the author would usually invoke the phrase "locally looks like" when it comes to defining a manifold.
For example, the real line is a manifold because it locally looks like a real line.
Can someone provide a slightly more mathematical definition of "looks like"? Does the real line looks like the entire real line or some segment of it? What about a circle?

A: A space $M$ is locally euclidean of dimension of $n$ if for any point $p\in M$, there is an open neighborhood $U$ of $p$ and a map $\varphi: U\to \varphi(U)\subset \mathbb{R}^n$ which is a homeomorphism. These are called charts of $M$.
We usually also want some sort of smoothness condition, which is usually stated as having the transition maps $\psi\circ\varphi^{-1}:\varphi(U\cap V)\to \psi(U\cap V)$ are smooth as functions on $\mathbb{R}^n$, where $\psi:V\to\psi(V)$ is defined as above.
This is usually what is meant when an author writes "looks locally like" Euclidean space.


text:
Q: applepay is not working in real device I implemented apple pay with stripe in ios using swift. So when the time of testing a program it is runs fine with simulators but not in real device. To test the apple pay with real device it doesn't show the payment sheet to process the transaction. My doubt is to test with apple pay with real device can we add test cards to wallet or have the sandbox account ? is required adding test cards to wallet when using stripe gate way? Could you please give me a clarity?
This is my code :
import UIKit
import PassKit
import Stripe

class ViewController: UIViewController {

    let request = PKPaymentRequest()
    var paymentStatus = PKPaymentAuthorizationStatus.failure
    var paymentController: PKPaymentAuthorizationController?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func applepay(_ sender: Any) {
        let merchantIdentifier = "merchant.Appplepay"
        let paymentNetworks = [PKPaymentNetwork.masterCard, PKPaymentNetwork.visa,PKPaymentNetwork.amex,PKPaymentNetwork.discover,PKPaymentNetwork.interac]
        if PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: paymentNetworks)
        {

            request.merchantIdentifier = "merchant.Appplepay"
            request.countryCode = "US"
            request.currencyCode = "USD"
            request.supportedNetworks = paymentNetworks
            request.merchantCapabilities = .capability3DS
            request.requiredShippingAddressFields = [.phone, .email,.postalAddress,.all]
            request.paymentSummaryItems  = [PKPaymentSummaryItem(label: "Fancy Hat", amount: 50.00),
                                            // The final line should represent your company;
                // it'll be prepended with the word "Pay" (i.e. "Pay iHats, Inc $50")
                                            PKPaymentSummaryItem(label: "iHats, Inc", amount: 50.00),]
        } else {
            // Traditional checkout flow
        }
        func applePaySupported() -> Bool {
            return PKPaymentAuthorizationViewController.canMakePayments() && PKPaymentAuthorizationViewController.canMakePayments(usingNetworks: [.amex, .visa, .masterCard])
        }
           // Setup payment authorization view controller
        if Stripe.canSubmitPaymentRequest(request) {
            // Setup payment authorization view controller
            let paymentAuthorizationViewController = PKPaymentAuthorizationViewController(paymentRequest: request)
            paymentAuthorizationViewController?.delegate = self

            // Present payment authorization view controller
            self.present((paymentAuthorizationViewController)!, animated: true,completion: nil)
        }
        else {
            // There is a problem with your Apple Pay configuration
            print("Failed to present PaymentSheet");
        }

    }

}
extension ViewController : PKPaymentAuthorizationViewControllerDelegate {

    func paymentAuthorizationViewController(_ controller: PKPaymentAuthorizationViewController, didAuthorizePayment  payment: PKPayment, completion: @escaping (PKPaymentAuthorizationStatus) -> Void) {
        if payment.shippingContact?.emailAddress == nil || payment.shippingContact?.phoneNumber == nil {
            paymentStatus = .invalidShippingContact
        } else {
            STPAPIClient.shared().createToken(with: payment) { (token: STPToken?, error)-> Void  in
            print("Stripe token is \(String(describing: token!))")
                //self.paymentStatus = .success
                 completion(.success)

        }
        }

    }

    func paymentAuthorizationViewControllerDidFinish(_ controller: PKPaymentAuthorizationViewController) {
        controller.dismiss(animated: true, completion: nil)
    }

}

A: To answer your questions about testing on a real device: You can only add real cards to your wallet to use with Apple Pay, however if you use a test stripe api key, that is detected by stripe and your real card will not be charged
Not sure why the payment sheet isn't displaying on the real device without seeing some code, but you would want to make sure that the device is set up for apple pay, mainly that it has cards added to the wallet (that you support)
Not all countries support Apple Pay so there isn't always an option to add a card to the wallet, this would mean that the Apple Pay sheet wouldn't display due to if Stripe.canSubmitPaymentRequest(request) returning false.


text:
Q: Is there any way we can hide bars based on their values like negative / positive? I am using LightningChartJS to create chart with bars. I have data with both positive and negative values. Is there any available property using which I can hide negative bars or positive bars based on what i want to see?
Note: I can obviously write some basic logic to achieve this functionality but i am looking for some inbuilt functionality.
const rectangles = chart.addRectangleSeries()
const addValues = (entries) => {
      for (const entry of entries) {
        bars.push(add(entry))
      }
}

const add = (entry) => {
      // Create rect dimentions.
      const rectDimensions = {
        x: x - figureThickness,
        y: 0,
        width: figureThickness,
        height: entry.value
      }
      // Add rect to the series.
      x += figureThickness + figureGap
      // Return data-structure with both original 'entry' and the rectangle figure that represents it.
      return {
        entry,
        rect
      }
    }

    chart.addValues([
  { category: '', value: 20 },
  { category: '', value: 40 },
  { category: '', value: -23 },
  { category: '', value: -29 },
  { category: '', value: 15 }
])

A: To hide series/figures based on value, you do have to implement this logic on the application side.
For this you have two options:

*

*Separate the bars to two RectangleSeries, one which has positive values and the another with negative ones.

*Use just one RectangleSeries like you have now, but style each figure individually. You receive a reference to the figure when you add a rectangle with RectangleSeries.add().
In either case, you'll have to dispose to hide series/figures you dont want to see, and restore the things you want to see. Both RectangleSeries and figures have the dispose() and restore() methods.