text:
Q: How to get a particular xml node values using groovy script Here is my soap response. I am using free version of soapui.
Someone please help me to get the values 60,61  as an array from **<tRiseMedia:OSDConfiguration token="60"> ** node using groovy
            <tRiseMedia:StreamName>VideoEncoder_Encoder1</tRiseMedia:StreamName>
            <tRiseMedia:OSDConfiguration token="61">
             <tt:VideoSourceConfigurationToken>VideoSource_VisibleCamera</tt:VideoSourceConfigurationToken>
              </tRiseMedia:OSDConfiguration>
         </tRiseMedia:StreamOsdList>

Here is my groovy script snippet
import com.eviware.soapui.support.XmlHolder
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext
def TestCase = context.testCase
PropertiesTestStep = TestCase.getTestStepByName("Properties")
def response = testRunner.testCase.getTestStepByName('GetStreamOSDs').getPropertyValue("response")
def samplexmlreq=new XmlHolder(response)

def tokenFromResponse = samplexmlreq.getNodeValue("/*:OSDConfiguration/@token")

def envelope = new  XmlParser(false, false).parse(samplexmlreq)
def tokens = envelope.'**'.findAll { node -> node.name() == 'tRiseMedia:OSDConfiguration' }*.@token
log.info  token

A: You can do it like this if you just want a list of the tokens:
def xmlText = '''<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/">
   <SOAP-ENV:Header/>
   <SOAP-ENV:Body>
      <tRiseMedia:GetStreamOSDsResponse>
         <tRiseMedia:StreamOsdList>
            <tRiseMedia:StreamName>VideoEncoder_Encoder1</tRiseMedia:StreamName>
            <tRiseMedia:OSDConfiguration token="60">
              <tt:VideoSourceConfigurationToken>VideoSource_VisibleCamera</tt:VideoSourceConfigurationToken>
               <tt:Type>Text</tt:Type>
               <tt:Position>
                  <tt:Type>Custom</tt:Type>
                  <tt:Pos x="15" y="50"/>
               </tt:Position>
               <tt:TextString>
                  <tt:Type>Sector</tt:Type>
               </tt:TextString>
            </tRiseMedia:OSDConfiguration>
         </tRiseMedia:StreamOsdList>
         <tRiseMedia:StreamOsdList>
            <tRiseMedia:StreamName>VideoEncoder_Encoder1</tRiseMedia:StreamName>
            <tRiseMedia:OSDConfiguration token="61">
             <tt:VideoSourceConfigurationToken>VideoSource_VisibleCamera</tt:VideoSourceConfigurationToken>
               <tt:Type>Text</tt:Type>
               <tt:Position>
                  <tt:Type>Custom</tt:Type>
                  <tt:Pos x="35" y="35"/>
               </tt:Position>
               <tt:TextString>
                  <tt:Type>Sector</tt:Type>
               </tt:TextString>
            </tRiseMedia:OSDConfiguration>
         </tRiseMedia:StreamOsdList>
      </tRiseMedia:GetStreamOSDsResponse>
   </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
'''

def envelope = new  XmlParser(false, false).parseText(xmlText)

def tokens = envelope.'**'.findAll { node -> node.name() == 'tRiseMedia:OSDConfiguration' }*.@token

assert tokens == ['60', '61']

You can get the response XML like this:
import com.eviware.soapui.support.XmlHolder
def xmlText = new XmlHolder(context.response)

In SoapUI you'll use parse instead of parseText. The parseText is for the example because the XML string is in the source as text.

A: I got the solution as below
import com.eviware.soapui.support.XmlHolder
import com.eviware.soapui.impl.wsdl.testcase.WsdlTestRunContext
def TestCase = context.testCase
PropertiesTestStep = TestCase.getTestStepByName("Properties")
def response = testRunner.testCase.getTestStepByName('GetStreamOSDs').getPropertyValue("response")

def envelope = new  XmlParser().parseText(response)
//Getting all the token values from the response
def tokens = envelope.'**'.findAll { node -> node.name() == 'tRiseMedia:OSDConfiguration' }*.@token
log.info tokens


text:
Q: ReactJs throwing maximum update depth error I am building a react app to learn react. I have implemented context to store information about the user when they login and also am making a copy in the localstorage. I verify that users are logged in like this in the App component
function App() {
const [user, setUser] = useContext(UserContext);
return (
        <div className="App">
            <Router>
                <NavBar />
                    <Switch>
                        <Route path="/login" exact>
                            {!user.loggedIn ? <LoginForm /> : <Redirect to="/profile" />}
                        </Route>
                    </Switch>
            </Router>
        </div>
    );

And this works fairly well. But if the token has expired; I want the user to be forced into the login page. Which means I need to check the expiration time on every route request as users can be in there profile and if they click on another link they will be redirected to login component. How should I approach this?
I have tried to to use useEffect in app component that sets the state loggedIn to true true when it meets the condition and made a comparison like
    useEffect(function () {
        const ct = parseInt(Date.now().toString(), 10);
        const iat = parseInt(localStorage.getItem('iat'), 10);
        if (ct - iat < 60000) {
            setUser({ loggedIn: true });
        } else {
            setUser({ loggedIn: false });
        }
    });

From my understanding this should happen everytime App component is rendered hence I provide no input to useEffect but this obviously throws a maximum update depth reached error.
How should I implement this behaviour?

A: Edit:
App component won't rerender because it's never changing and only the subcomponents are. What you can do is, you can put history.location as your dependency in the useEffect, which will trigger the useEffect whenever the path changes. See: How to listen to route changes in react router v4?
If you console.log in your component body, you'll see that it rerenders a lot of times with every node updating. You need to add either an empty dependency array or some dependencies so it only runs the useEffect when it's needed.
useEffect(() => {
//your logic here
}, [])

I think you can also mitigate this error by having another check on your setUser method. This way you'll mitigate a lot of unnecessary calls to the setState method which is one of the reasons for this maximum depth reached error
useEffect(function () {
       //other code
        if (!loggedIn && ct - iat < 60000) {
            setUser({ loggedIn: true });
        } else if(loggedIn){
            setUser({ loggedIn: false });
        }
    });

Furthermore, there are usually better ways to check whether the user needs to reauthenticate, if you are using Axios, you can set up a check in the interceptor to do this comparison before making a call and if the user is unauthed, redirect them to login page.

A: Use useLocation from 'react-router-dom'. Then let location = useLocation() and useEffect(function(){//do stuff}, [location]). This way, we will run the useEffect when the url changes.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Destination URL for completed DocuSign envelope I'm using the DocuSign SOAP API to create and send envelopes (insurance application forms) with one or two signers.
I want the first signer to land on a specific url when signing is complete and the second signer to land on a different url when their signing (and therefore the entire envelope) is complete.
I can set a Destination URL in my brand for "Signing Completed" but that's at the signer level for all signers.
Is there a way to specify a landing page/url which the user can be redirected to when all signers have completed signing?

A: You can use specify a routingOrder for each recipient and set the appropriate URL for the recipient in the final routing order.
Once the final recipient sign, the user will be redirected to the URL.
Related API RequestSenderToken


text:
Q: Spring Boot rabbit mq spring.rabbitmq.listener.simple.concurrency never works In SpringBoot rabbit mq project,I have the configuration like that.
@EnableRabbit
@Configuration
public class MQConfig {

private final String primaryQueueName;
private final String deadLetterQueueName;

@Autowired
private ConnectionFactory cachingConnectionFactory;

public MQConfig(
                 @Value("${primaryQueue.name}")String primaryQueueName,
                 @Value("${deadLetterQueue.name}")String deadLetterQueueName){

    this.primaryQueueName=primaryQueueName;
    this.deadLetterQueueName=deadLetterQueueName;
}

@Bean
public Queue primaryQueue() {
    Map<String, Object> args = new HashMap<String, Object>();
    // The default exchange
    args.put("x-dead-letter-exchange", "");
    // Route to the incoming queue when the TTL occurs
    args.put("x-dead-letter-routing-key", deadLetterQueueName);
    // TTL 500 seconds
    args.put("x-message-ttl", 300000);
    return new Queue(primaryQueueName, false, false, false, args);
}

@Bean
public Queue deadLetterQueue() {
    return new Queue(deadLetterQueueName);
}}

And my listener looks like,
 @Component
public class Receiver {
 private static final Logger LOGGER = LoggerFactory.getLogger(Receiver.class);

    @Autowired
    private JavaMailSender mailSender;

@RabbitListener(queues = "${primaryQueue.name}")
public void receiveMessage(SimpleMailMessage message){
    LOGGER.info("Sending email message : "+message);
    try {
        mailSender.send(message);
    }catch(Exception e) {
        LOGGER.error("Failed to deliver email",e);
        throw e;
    }

}}

So far so good, the messages come to primary queue, the consumer consumes them and they are gone to dead letter queue if for some reason the consumer is not able to consume them in given TTL 300000.
Now, I want to configure the listener even further with spring application.properties, but they have no impact on it at all.
E.g. I set spring.rabbitmq.listener.simple.concurrency=3, still it creates a single consumer, explicitly setting it in code works however. Nether works other settings,
spring.rabbitmq.listener.simple.acknowledge-mode= # Acknowledge mode of container.
spring.rabbitmq.listener.simple.auto-startup=true # Start the container automatically on startup.
spring.rabbitmq.listener.simple.concurrency= # Minimum number of consumers.
spring.rabbitmq.listener.simple.default-requeue-rejected= # Whether or not to requeue delivery failures; default `true`.
spring.rabbitmq.listener.simple.idle-event-interval= # How often idle container events should be published in milliseconds.
spring.rabbitmq.listener.simple.max-concurrency= # Maximum number of consumers.
spring.rabbitmq.listener.simple.prefetch= # Number of messages to be handled in a single request. It should be greater than or equal to the transaction size (if used).
spring.rabbitmq.listener.simple.retry.enabled=false # Whether or not publishing retries are enabled.
spring.rabbitmq.listener.simple.retry.initial-interval=1000 # Interval between the first and second attempt to deliver a message.
spring.rabbitmq.listener.simple.retry.max-attempts=3 # Maximum number of attempts to deliver a message.
spring.rabbitmq.listener.simple.retry.max-interval=10000 # Maximum interval between attempts.
spring.rabbitmq.listener.simple.retry.multiplier=1.0 # A multiplier to apply to the previous delivery retry interval.
spring.rabbitmq.listener.simple.retry.stateless=true # Whether or not retry is stateless or stateful.
spring.rabbitmq.listener.simple.transaction-size=

https://docs.spring.io/spring-boot/docs/current/reference/html/common-application-properties.html
Any ideas? Am I configuring something incorrectly ?

A: You reference the docs for the current version of Spring Boot.  Is this what you are using, or something older?  This property used to be spring.rabbitmq.listener.concurrency without the "simple" in there.
Double check the version, for example: https://docs.spring.io/spring-boot/docs/1.4.3.RELEASE/reference/html/common-application-properties.html


text:
Q: Do I need Homebrew? I'm a .NET dev trying to get the hell out of MS and learn the other side.  That is the Mac OS and development...so please don't skip anything or make the assumnption that I know much here even after looking at the Home-brew site, etc.
If I'm not coding mobile apps using iOS or Swift, or I'm not coding Ruby (I'm coding all JS like Node, etc.) is Homebrew something I can still benefit from or do I not need it at all then?  What about XCode Utilities which installs the GCC compiler, do I still need those in a development environment that's going to be dealing with all JavaScript?
Homebrew is a package manager but if I'm using something like Node's npm, is Homebrew used for the same kind of deal but for Ruby?  I am kinda vague on all this.

A: You can do a whole lot of OS X without needing a third-party package manager such as Homebrew.  But the moment you find yourself installing software from third-party web sites, you should probably consider getting yourself organized.  The combination of Homebrew and Cask is useful for keeping track of what software you have installed and where it came from.  Plus, it's a lot easier than doing everything by hand.

A: Even if you are going to do purely Node.js development, there will come times when you need to install an npm module that contains a native C/C++ addon. When that happens, you will need to install the xCode developer tools (not sure if xCode itself is required...?).
xCode developer tools is an Apple-provided bundle of commandline stuff one usually needs to compile other stuff on Unix systems - make, configure, gcc, and a lot of other stuff which I know nothing about.
This alone should take you quite far. It might, in fact, be enough. However, there might again come times when you need to install an npm package that contains a native C/C++ addon that links against a shared library that is supposed to be installed on your system, but it is not (because Apple did not include it by default etc.) or, it requires a different (newer?) version of that library. And that would be the time when, instead of downloading and compiling the shared library yourself, you install Homebrew, type a command or two and voilá - the dependency is installed and ready.
Homebrew is a package manager for OS X as a whole, not just for a particular programming language. Usually (but not exclusively) it provides software that requires compilation (C/C++/Objective-C etc.). An example would be Node.js itself (so you can upgrade Node with a single command when there's an update), MariaDB, MongoDB, OpenSSL, OpenSSH, git, etc. Apple provides some of these, but they tend to get outdated very quickly - Homebrew helps you stay up to date.


text: Q: Proof of Cavalieri's Principle with the help of Fubini's theorem Suppose that $(X,A,\mu )$ is a measure space and $f:X\rightarrow \mathbb R$ a nonnegative $A$-measurable function, then the function $t\mapsto \mu(\left \{ f>t \right \})$ is also measurable and I want to show that $\int _{X}f\,d\mu=\int _{\mathbb R^{+}}\mu(\left \{ f>t \right \})\,dL^{1}(t)$; here $\left \{ f>t \right \}$ is the set  $\left \{ x;f(x)>t \right \}$ and $L^{1}$ is the 1-dimensional Lebesgue measure. I want to prove this theorem by using Fubini's theorem; I have already proved it without using Fubini's theorem but I don't know how to prove it with the help of Fubini's theorem. Can anyone help me? Thank you in advance!


text:
Q: donde esta el evento en crearDB.onupgradeneeded = e =>{} Estoy en un curso de js y estamos viendo como usar la base de datos del navegador. En la linea: "crearDB.onupgradeneeded = e =>{}" cuando paso el "e" entiendo que estoy pasando un evento por parametro pero no entiendo cual es el evento. O acaso es que el metodo "onupgradeneeded" genera un evento?
function crearDB(){
const crearDB = window.indexedDB.open('crm',1);
    crearDB.onerror = ()=> {console.log('Hubo un error al crear la DB!!');}
    crearDB.onsuccess = ()=> {console.log('DB creada con exito!!'); DB = crearDB.result;}

    crearDB.onupgradeneeded = e =>{
        const db = e.target.result;
        const objectStore = db.createObjectStore('crm', {keyPath: 'crm', autoIncrement: true});

        objectStore.createIndex ('nombre', 'nombre', {unique: false});
        objectStore.createIndex('correo', 'correo',{unique: true});
        objectStore.createIndex('telefono','telefono', {unique: false});
        objectStore.createIndex('empresa','empresa',{unique: false});
        console.log('Columnas creadas correctamente');
    }
}

A: El evento que estás pasando a la variable e es onupgradeneeded, el cual se activa cuando se intenta abrir una base de datos con un número de versión superior a su versión actual.


text:
Q: javascript window.onerror message contains only "Script error." how can i get the line number? you probably protect your js script by window.onerror to catch global exceptions,
the thing is, my files on production are compressed and the line number will be always 1 ,so i really don't know where is the error occurred? do you have any suggestion what can i do in this case?
window.onerror = function (errorMsg, fileName, lineNumber) { logger.sendError(errorMsg + " file name " + fileName, "window.onerror") };

A: As Ianzz says in his comment, in general it will be impossible for your browser to determine a meaningful line number for minified code. After all: if all code is on a single line, the correct (but quite useless) line number is always 1.
There is a movement however to allow the use of source maps, which are separate files that specify exactly how the (minified) JavaScript maps back to more meaningful input.
http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/
The specification is relatively new and not too far spread yet. But depending on your minification framework, there may be a tool available already to generate source maps.

A: If it says "Script error" then the browser has prevented your error handling code from accessing the stack due to a CSP (Content Security Policy) violation.
Usually this happens if your code comes from a different domain, or if it uses eval or JSONP.
Most bundlers (e.g. browserify/webpack) use eval or JSONP by default. For webpack you can set config.devtool to change this.


text:
Q: How to update running JobService with new request? I have an app with the option to download files. For this purpose, I've implemented DownloadService which will firstly do the database query to get download candidates and then build queue for download. Once the queue is built, it will start processing downloads 1 by 1 until the queue is empty and then will finish itself. While service is running user can add more download requests (send ACTION to running service to re-build queue).
But we can't use background service when targeting Oreo or newer version of Android anymore, and I would like to avoid implementing it as foreground service to avoid displaying notification while determining download queue and not doing actual file download.
I've tried to schedule it with setOverrideDeadline(0) using JobScheduler API but instead of updating running job, the old one was destroyed, and the new one created. I've also tried to enqueue JobWorkItem instead, but onStartJob of JobService (where I am supposed to dequeue work) is not called if the job is already running so I can't update it with new requests.
EDIT 1:
I have an experimental implementation where I will check if my JobService is running using this sample code
private boolean isServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)){
        if("com.example.MyJobService".equals(service.service.getClassName())) {
            return true;
        }
    }
    return false;
}

If job is not running I will schedule it, but if it is running I will send event to this job using EventBus and update job with new request. But I would prefer 'pure' JobScheduler's API solution.
EDIT 2: I have also option to download multiple files in parallel and to change priority of queued downloads.
Do anybody know how to keep posting new requests (actions) to running job without creating a new one with JobScheduler API? (without 3rd party libraries)


text:
Q: Why I got 'The computed initial AR coefficients are not stationary' while using aic_min_order? I generate some data like [1, 6, 1, 6, 1, 6] and add noises under normal distribution. I use arma_order_select_ic to select order. Then aic_min_order is used to fit the ARMA model. Sometime the model works well. But sometimes it raises ValueError.
ValueError: The computed initial AR coefficients are not stationary
Here is my code.
import statsmodels.api as sm
import numpy as np
x = [1 if i%2 == 0 else 6 for i in range(50)]
eta = np.random.normal(0, 0.01, 50)
x = x + eta
res = sm.tsa.stattools.arma_order_select_ic(x, ic=['aic'])
print res.aic_min_order
model = sm.tsa.ARMA(x, res.aic_min_order).fit(disp = 0)
print model.predict(45, 55)

Do I miss something or ARMA don't fit this kind of data?

A: ARMA is designed for stationary processes and by default imposes stationarity on the parameter estimates.
Your data is not stationary, i.e. it the lag polynomial has a seasonal unit root. The usual treatment is to use seasonal differencing or a deterministic seasonal pattern for example with dummy variables or splines.
Statsmodels has currently no automatic season detection and model selection, but SARIMAX can be used for seasonal integrated ARMA processes.


text:
Q: Is there a method to force delete or uninstall an app (i.e. dropbox ) other than removing it from Software Center? So far I've tried of course the go-to area for newbies: Ubuntu Software Center.
Fail#1
I clicked on the "remove" button and I left it overnight and it's still 'pending'. It seems like the progress bar is on an endless loop.
Dropbox Forever Uninstalling
Fail#2
Next I tried to run sudo dpkg --configure -a
However, it would show that dpkg is locked and I can't proceed.
DPKG Locked
Fail#3
So I proceeded to remove the lock file supposedly involved via:
sudo rm /var/lib/apt/lists/lock

and then
sudo rm /var/cache/apt/archives/lock

so that I can try
sudo apt-get update && sudo apt-get upgrade

I was almost happy when it started downloading the app thru the terminal. And then after another overnight, it never happens. It just gets stuck at like 31% download or some random percentage number.
Fail#4
And so I tried the developer's website and downloaded the .deb file and tried launching it, but then there's an error message saying there's a conflict.

Please help me force remove this app -or- is there still hope on how to successfully install it? Thank you for your time.

A: Uninstall the desktop app on Linux
Depending on your operating system and the package used during installation, certain command lines inputted into your terminal window will uninstall the desktop app. Copy and paste the following commands one-by-one into your terminal window, hitting Enter after each command. If some of the commands listed produce an error, do not be concerned. By the last command, the desktop app will be successfully uninstalled from your computer.
dropbox stop dropbox status # Should report "not running"
rm -rf ~/.dropbox-dist
rm -rf /var/lib/dropbox
rm -rf ~/.dropbox*
sudo apt-get remove nautilus-dropbox
sudo apt-get remove dropbox
rm /etc/apt/source.d/dropbox

If this doesn't work, try;
sudo apt-get remove --purge nautilus-dropbox

Source: Link
ps. Afterwards you could try the installation again?


text:
Q: Php POST - get boundary value So I want to upload a file using curl, but the problem is: the post request contains a boundary variable that is checked upon by the website. I know this because I get errors when modifying this variable in Tamper Data.
Http headers (important part):
Content-Type: multipart/form-data; boundary=----pluploadboundaryp18mu3sf5fus08pd11c3kvq163514

Post request:
------pluploadboundaryp18mu3sf5fus08pd11c3kvq163514\r\n
Content-Disposition: form-data; name="name"\r\n
\r\n
1.jpg\r\n
------pluploadboundaryp18mu3sf5fus08pd11c3kvq163514\r\n
Content-Disposition: form-data; name="imageData"; filename="1.jpg"\r\n
Content-Type: image/jpeg\r\n
\r\n
{Filecontent}

So my question is: How can I bypass or duplicate this boundary?
Edit: if you want to test yourself the form upload is located at:https://www.marktplaats.nl/syi/239/1399/plaatsAdvertentie.html

A: So i got the answer on my question. Also thanks to Ruslan Bes for helping.
The problem was i sended my post request as http_build_query($post) instead of $post.
Small mistakes can cause a lot of problems :D


text:
Q: Jwt authentication, authorization any request I cloned this github project: https://github.com/cornflourblue/dotnet-5-jwt-authentication-api
So I have followed function to validate the jtw token and on a successful jwt validation it attach user to context:
private void attachUserToContext(HttpContext context, string token)
{
   try
   {
      //...
      var jwtToken = (JwtSecurityToken)validatedToken;
      var userId = jwtToken.Claims.First(x => x.Type == "username").Value;

      // attach user to context on successful jwt validation
      context.Items["User"] = userId;
   }
   catch
   {
      // do nothing if jwt validation fails
      // user is not attached to context so request won't have access to secure routes
   }
}

So the AuthorizeAttribute:
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class AuthorizeAttribute : Attribute, IAuthorizationFilter
{
    public void OnAuthorization(AuthorizationFilterContext context)
    {
        var username = context.HttpContext.Items["User"];
        if (username == null)
        {
            // not logged in
            context.Result = new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized };
        }
    }
}

But for some reason it allows all requests, even requests without header information. If u need more information then just ask!

A: I dont know why the Custom AuthorizeAttribute dont work but I set the same
query to test that HttpContext.Items["User"] is not null and now it work...:
[Authorize]
[HttpGet("Select")]
public IActionResult Select()
{
   try
   {
      if (HttpContext.Items["User"] == null)
      {
         return Conflict(new JsonResult(new { message = "Unauthorized" }) { StatusCode = StatusCodes.Status401Unauthorized });
      }
      return Ok(TestService.Select());
   }
   catch (Exception ex)
   {
      return Conflict(ex);
   }
}


text:
Q: How avoid code replication in the following example? C++ / Cuda EDIT: This code is working, but it looks there are many code replication parts and i cant find a way arround this.
In the MatrixDevice class i want to call the kernel functions in kerne.cu.
I reduce the MatrixDevice class to only showing this concept how i do it actually.
From MatricDevice i have some functionens to add MatrixDevice with other MatrixDevice or number, this should work for different types, in this example with float and double, this should be no problem with templates, but i have to declare the overloading functions MatrixCudaOperations extern because i cannot include a .cu file into a .h/.cpp file.
matrixdevice.h
extern void MatrixCudaOperations(const float* a, const float* b, float* result, size_t rows, size_t cols, EOperation operation);
extern void MatrixCudaOperations(const float* a, float b, float* result, size_t rows, size_t cols, EOperation operation);
extern void MatrixCudaOperations(const double* a, const double* b, double* result, size_t rows, size_t cols, EOperation operation);
extern void MatrixCudaOperations(const double* a, double b, double* result, size_t rows, size_t cols, EOperation operation);

template<class T>
class MatrixDevice{

    T* data;
    size_t rows;
    size_t cols;

    MatrixDevice& Add(const MatrixDevice &other);
    MatrixDevice& Add(T &other);
};

//Operations with MatrixDevice
//Add MatrixDevice to this
template<class T>
MatrixDevice& MatrixDevice::Add(const MatrixDevice &other){
    MatrixCudaOperations(data, other.data, data, rows, cols, EOperation::ADD);
    return *this;
}

//Add two MatrixDevice and return the result as new MatrixDevice
template<class T>
MatrixDevice Add(const MatrixDevice &a, const MatrixDevice &b){
    MatrixDevice result(a);
    result.Add(b);
    return result;
}

//Add two MatrixDevice to result MatrixDevice
template<class T>
void Add(const MatrixDevice &a, const MatrixDevice &b, MatrixDevice &result){
    MatrixCudaOperations(a.data, b.data, result.data, a.rows, a.cols, EOperation::ADD);
}

//Operations with Number

//Add T number to this
template<class T>
MatrixDevice& MatrixDevice::Add(T &other){
    MatrixCudaOperations(data, other, data, rows, cols, EOperation::ADD);
    return *this;
}

//Add T number to MatrixDevice and return the result as new MatrixDevice
template<class T>
MatrixDevice Add(const MatrixDevice &a, T &b){
    MatrixDevice result(a);
    result.Add(b);
    return result;
}

//Add T number with MatrixDevice to result MatrixDevice
template<class T>
void Add(const MatrixDevice &a, T &b, MatrixDevice &result){
    MatrixCudaOperations(a.data, b, result.data, a.rows, a.cols, EOperation::ADD);
}

In the kernel i declare the overloading functions for MatrixCudaOpertions and the code in any function is the same.
I trying this out with templates, but it didnt work if i need a extern declaretion in MatrixDevice class.
kernel.cu
template<class T> __global__
void d_Add(const T* a, const T* b, T* result){
    //code
}

template<class T> __global__
void d_Add(const T* a, T b, T* result){
    //code
}

void MatrixCudaOperations(const float* a, const float* b, float* result, size_t rows, size_t cols, EOperation operation){
    dim3 blocksize(rows, cols);

    switch(operation){
        case ADD:
            d_Add<<<1,blocksize>>>(a, b, result);
            break;
        //other cases, subtract, multiply...
    }
}

void MatrixCudaOperations(const float* a, float b, float* result, size_t rows, size_t cols, EOperation operation){
    dim3 blocksize(rows, cols);

    switch(operation){
        case ADD:
            d_Add<<<1,blocksize>>>(a, b, result);
            break;
        //other cases, subtract, multiply...
    }
}

void MatrixCudaOperations(const double* a, const double* b, double* result, size_t rows, size_t cols, EOperation operation){
    dim3 blocksize(rows, cols);

    switch(operation){
        case ADD:
            d_Add<<<1,blocksize>>>(a, b, result);
            break;
        //other cases, subtract, multiply...
    }
}

void MatrixCudaOperations(const double* a, double b, double* result, size_t rows, size_t cols, EOperation operation){
    dim3 blocksize(rows, cols);

    switch(operation){
        case ADD:
            d_Add<<<1,blocksize>>>(a, b, result);
            break;
        //other cases, subtract, multiply...
    }
}

A: Starting from the top.
template<class T>
class MatrixDevice;

template<class T>
static T const& to_matrix_data( T const& t ) { return t; }
template<class T>
static T const* to_matrix_data( MatrixDevice<T> const& m ) { return m.data; }

template<class T, class Rhs>
void AddInto(MatrixDevice<T>& target, MatrixDevice<T> const& src, Rhs const& rhs) {
  MatrixCudaOperations(src.data, to_matrix_data<T>(rhs), target.data, EOperation::ADD );
}

template<class T>
class MatrixDevice{
  T* data;
  size_t rows;
  size_t cols;

  template<class Rhs>
  MatrixDevice& +=(const Rhs &other)& {
    AddInto( *this, *this, other );
    return *this;
  }

  template<class Rhs>
  friend MatrixDevice operator+(MatrixDevice lhs, Rhs const& rhs) {
    lhs += rhs;
    return lhs;
  }
};

Using the word Add for 3 distinct operations is bad.  One is increment by, the other is add, the last is add into.
So I wrote a free template function AddInto.  Then based increment and add on it.
My add costs at most an additional move over yours, and based off the internal structure of your matrix, a move is free.


text:
Q: How to connect the input to the output directly using single fully connected layer in PyTorch? I am new to deep learning and cnn and trying to get familiar with that field using CIFAR10 tutorial code from PyTorch website. So, in that code I was playing with removing/adding layers to better understand the effect of them and I tried to connect the input(which is the initial data with the batch of 4 images) to the output directly with using only single fully connected layer. I know that does not make much sense, but I do it only for the sake of experiment. So, when I tried to do it, I faced with some errors, which are as follows:
First, here is the code snippet:
########################################################################
# 2. Define a Convolution Neural Network
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Copy the neural network from the Neural Networks section before and modify it to
# take 3-channel images (instead of 1-channel images as it was defined).

import torch.nn as nn
import torch.nn.functional as F

class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        #self.conv1 = nn.Conv2d(3, 6, 5)
        #self.pool = nn.MaxPool2d(2, 2)
        #self.conv2 = nn.Conv2d(6, 16, 5)
        #self.fc1 = nn.Linear(16 * 5 * 5, 120)
        #self.fc2 = nn.Linear(120, 84)
        self.fc3 = nn.Linear(768 * 4 * 4, 10)

    def forward(self, x):
        #x = self.pool(F.relu(self.conv1(x)))
        #x = self.pool(F.relu(self.conv2(x)))
        x = x.view(-1, 768 * 4 * 4)
        #x = F.relu(self.fc1(x))
        #x = F.relu(self.fc2(x))
        x = self.fc3(x)
        return x

net = Net()

#######################################################################
# 3. Define a Loss function and optimizer
# ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
# Let's use a Classification Cross-Entropy loss and SGD with momentum.

import torch.optim as optim

criterion = nn.CrossEntropyLoss()
optimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)

########################################################################
# 4. Train the network
# ^^^^^^^^^^^^^^^^^^^^
#
# This is when things start to get interesting.
# We simply have to loop over our data iterator, and feed the inputs to the
# network and optimize.

for epoch in range(4):  # loop over the dataset multiple times

    running_loss = 0.0
    for i, data in enumerate(trainloader, 0):
        # get the inputs
        inputs, labels = data

        # zero the parameter gradients
        optimizer.zero_grad()

        # forward + backward + optimize
        outputs = net(inputs)
        print(len(outputs))
        print(len(labels))
        loss = criterion(outputs, labels)
        loss.backward()
        optimizer.step()

        # print statistics
        running_loss += loss.item()
        if i % 2000 == 1999:    # print every 2000 mini-batches
            print('[%d, %5d] loss: %.3f' %
                  (epoch + 1, i + 1, running_loss / 2000))
            running_loss = 0.0

print('Finished Training')

So, when I run the code, I get the following error:
Traceback (most recent call last):
      File "C:\Users\Andrey\Desktop\Machine_learning_Danila\Homework 3\cifar10_tutorial1.py", line 180, in <module>
        loss = criterion(outputs, labels)
      File "C:\Program Files\Python36\lib\site-packages\torch\nn\modules\module.py", line 477, in __call__
        result = self.forward(*input, **kwargs)
      File "C:\Program Files\Python36\lib\site-packages\torch\nn\modules\loss.py", line 862, in forward
        ignore_index=self.ignore_index, reduction=self.reduction)
      File "C:\Program Files\Python36\lib\site-packages\torch\nn\functional.py", line 1550, in cross_entropy
        return nll_loss(log_softmax(input, 1), target, weight, None, ignore_index, None, reduction)
      File "C:\Program Files\Python36\lib\site-packages\torch\nn\functional.py", line 1405, in nll_loss
        .format(input.size(0), target.size(0)))
    ValueError: Expected input batch_size (1) to match target batch_size (4).

I was trying to check the length of x and it turns out, that it is 4 initially but it becomes 1 after the line
x = x.view(-1, 768 * 4 * 4)
I think my numbers are correct, but it seems like I am having only 1 tensor instead of 4 as I supposed to have, and I feel like that is what causes that error.
I am wondering, why is that and what is the best way to fix that?
Also, what would be the best optimal number for output dimension output in  nn.Linear(Fully connected Layer) in this case?

A: There are two obvious errors in your modified code (from the official ones from PyTorch webpage). First,
torch.nn.Linear(in_features, out_features)
is the correct syntax. But, you're passing 768 * 4 * 4 as in_features. This is 4 times the actual number of neurons (pixels) in one CIFAR10 image (32*32*3 = 3072).
The second bug is related to the first one. When you prepare your inputs tensor,
# forward + backward + optimize;
# `inputs` should be a tensor of shape [batch_size, input_shape]
        outputs = net(inputs)

you should pass it as a tensor of shape [batch_size, input_size], which according to your requirement is [4, 3072] since you want to use a batch size of 4. This is where you should provide the batch dimension; Not in nn.Linear which is what you're currently doing and that is causing the error.
Finally, you should also fix the line in forward method. Change the below line
x = x.view(-1, 768 * 4 * 4)

to
x = x.view(-1, 32*32*3)

Fixing these bugs should fix your errors.

Having said that I'm unsure whether this would actually work, in a conceptual sense. Because this is a simple linear transformation (i.e. an affine transformation without any non-linearity). The data points (which correspond to images in CIFAR10) would most probably be not linearly separable, in this 3072 dimensional space (manifold). Hence, the accuracy would be drastically poor. Thus it is advisable to add at least a hidden layer with non-linearity such as ReLU.


text:
Q: Unexpected Indentation of Nested Opening Brackets EDIT: I don't want to put opening curly brackets on a separate line, in general. I simply want to do so in this case where two opening brackets are on the same line. ESLint does it correctly but Beautify does not, but ESLint is only for inline Javascript.
I'm using the Beautify extension in VSCode to try to format this chunk of inline javascript as follows:
    const dogs = [
        {
            name: 'Snickers',
            age: 2,
        },
        {
            name: 'Hugo',
            age: 2,
        },
        {
            name: 'Sunny',
            age: 2,
        },
    ];

Instead, it does this:
    const dogs = [{
            name: 'Snickers',
            age: 2,
        },
        {
            name: 'Hugo',
            age: 2,
        },
        {
            name: 'Sunny',
            age: 2,
        },
    ];

As you can see, it puts the opening square and curly brackets on the same line. Is there a rule (in .jsbeautifyrc) to force the desired behavior or is this a bug in js-beautify?

A: *

*Try paste this rule in your .jsbeautifyrc

    {
        "js": {
            "brace_style": "expand"
        }
    }

Also you can try this extension too: Visual Studio Code Format

A: Prettier is also used for formatting the code in VS code. This extension does not have this problem. You can try installing this extension and try once. I have checked this and did not see this issue.
Extension name: Prettier - Code formatter


text:
Q: IIS Express + Visual Studio 2010 + non-local Project Url I am facing a dilemma related to another question but not exactly the same.
I want to use IIS Express with a custom URL but without modifying the local HOSTS file.
Specifically, for me, dev.example.com resolves to 127.0.0.1 using DNS (our DNS is set up so that *.example.com resolves to 127.0.0.1). This is what I want to use as a project URL. If I add dev.example.com to my HOSTS file, it works, but if I don't, it doesn't. I'm guessing this is because Visual Studio doesn't recognize this as being a local URL.
Is there a way to not modify the HOSTS file but still use a custom URL like dev.example.com as a Project Url in Visual Studio with IIS Express?

A: Yes-sortof. IISExpress configuration is stored in the executing users profile under:
C:\Users\<username>\Documents\IISExpress\config\

You'll need to edit applicationhost.xml
Locate the <sites> section and extend:
        <site name="WebApplication1" id="20">
            <application path="/" applicationPool="Clr4IntegratedAppPool">
                <virtualDirectory path="/" physicalPath="C:\inetpub\WebApplication1" />
            </application>
            <bindings>
                <binding protocol="http" bindingInformation="*:45965:localhost" />
                <binding protocol="http" bindingInformation="*:80:dev.example.com" />
            </bindings>
        </site>

Note that the port 80 must not be occupied by IIS in case it's running on your dev box.
The problem that this solution is facing, that with these settings pressing F5 in VS, or otherwise start the website from VS will ALWAYS want to start on localhost, and will not initialize the other binding. You have to start IISExpress manually with the following:
c:\Program Files (x86)\IIS Express\iisexpress.exe" /site:WebApplication1


text:
Q: ¿Como puedo personalizar mi aplicacion de xamarin forms?
Como puedo eliminar el nombre, de la aplicación de este lugar, muchas gracias por su ayuda...

A: El titulo de la pagina actual se puede cambiar en la propiedad Title , asi como el icono (propiedad Icon) asociado.
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
   xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
   x:Class="Demo.MainPage"
   Title="Titulo de tu Preferencia" Icon="DefaultIcon.png">

De igual forma, recomiendo cambiar el nombre de la aplicación (Application Name), puedes acceder a traves de las propiedades del proyecto.


text:
Q: why doesn't Excluding model properties on update with TryUpdateModel work without ModelState.Remove I am trying to update a model by excluding some properties with below code on my controller Action  :
[HttpPost, ValidateAntiForgeryToken, ActionName("Edit")]
public ActionResult Edit_post(Board board, int id) {

    var model = _boardrepository.GetSingle(id);

    #region _check if exists

    if (model == null)
        return HttpNotFound();

    #endregion

    if (TryUpdateModel<Board>(model, "", null, new string[] { "BoardID", "BoardGUID", "BoardAbbr" })) {

        try {

            _boardrepository.Edit(model);
            _boardrepository.Save();

            return RedirectToAction("details", new { id = id });

        } catch (Exception ex) {

            #region Log the error
            ex.RaiseElmahNotification("Error while trying to update a destination.");
            #endregion

            ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, inform your system administrator.");
        }

    }

    return View(board);
}

When I try to update my model, it redirects me to my edit view and display a error message saying that BoardAbbr field is required which is totally legitimate if I need to update BoardAbbr field. But as you can see I am excluding some fields with below code and BoardAbbr is one of them :
if (TryUpdateModel<Board>(model, "", null, new string[] { "BoardID", "BoardGUID", "BoardAbbr" }))

Then I put the below code before TryUpdateModel method, it works like a charm :
ModelState.Remove("BoardAbbr");

What is bothing me here is that either I am doing something wrong or there is something wrong has been built inside the framework. I bet that first one is the issue here.
why doesn't Excluding model properties on update with TryUpdateModel work without ModelState.Remove?
To be honest, I didn't dig into it so much and straightly come here to shout this question to you guys.

A: Your model Board probably has a property BoardAbbr on it. The message comes from validation of the posted model (Board in this case) and has nothing to do with TryUpdateModel. So if you remove the property on your model the message will go away.
You can see what is happening if you put your if(TryUpdateModel... inside an if like this:
if(!ModelState.IsValid) {
    if (TryUpdateModel<Board>(model, "", null, new string[] { "BoardID", "BoardGUID", "BoardAbbr" })) {
  .....
    }
}

EDIT
As per your comment: excluding the property with a Bind attribute will work:
public ActionResult Edit_post([Bind(Exclude="BoardAbbr")] Board board, int id) {

But you could also make sure that there is no formvalue coming in that can be bound to the property, the binder will not generate message for properties without formvalues.


text:
Q: print three lines after the matching pattern using regular expression in Python Dear python community,
I want to print three lines after matching pattern in python (printing
the matching line is easy, e.g. by using re.match(r'(.)match(.)', pattern)).
How to do it in python? The equivalent operation can be performed using "grep -A3 "pattern" filename".

A: Assuming you are iterating over the lines, I would use something like this
i = 0
for line in lines:
    if re.match(pattern, line):
        i = 4
    if i > 0:
        print line
        i -= 1


text:
Q: How to insert INLINE text box in html Is there a way that i can put text boxes in line as you do withe the radio buttons and etc in html?
I am trying to create boxes in line to store auto generated values inside.

A: You can simply use:
display: inline-block;


text:
Q: Is there any chance that the execution of two queries could interfere with each other Say two users are using a website and an operation within that website inserts a new row, then selects that row (by selecting the most recently inserted row) to be returned to the user. Is there a chance that in the time between one user having a row inserted and having the row selected that the other user could insert a new row, thus making the select query select the other user's row rather than the correct one. If so is there any way to combat this?

A: If by "most recently inserted row" you mean something like:
select id
from table t
order by id desc
limit 1;

Then they can definitely interfere with each other.
If by "most recently inserted row" you mean LAST_INSERTED_ID(), then you are safe.  This is stored on a per-connection basis.  You can read more about it here.


text:
Q: Syntax Error when Inserting New Data Into Table I keep getting a syntax error when I'm trying to insert new entries into the table but I can't seem to figure out why.
For starters here's the .schema:
CREATE TABLE collection (
id int primary key not null,
album text not null,
artist text not null,
year int not null,
cover text
);

And this is the line I've used to add the entry:
sqlite> insert into collection(115,"houses of the holy","led zeppelin", 1973, "junk");

All the values match up: id int, album text, artist text, year int, cover text. But the terminal just spit out the following syntax error:
Error: near "115": syntax error

I've also tested putting the int values within quotation marks but I just end up with:
Error: near ";": syntax error

Can someone please help me figure out what I'm doing wrong?

A: You are missing the VALUES keyword.
INSERT INTO table_name
VALUES (value1,value2,value3,...);

For more info see INSERT DOCS

A: This syntax is incorrect:
insert into collection(115,"houses of the holy","led zeppelin", 1973, "junk")

First of all, use single-quotes instead of double-quotes:
insert into collection (115, 'houses of the holy', 'led zeppelin', 1973, 'junk')

Aside from that, the query parser is expecting those values to be the column names, and they're not valid as column names.  You should be able to simply include the VALUES keyword:
INSERT INTO collection VALUES (115, 'houses of the holy', 'led zeppelin', 1973, 'junk')

Failing that, explicitly specify the column names:
INSERT INTO collection (id, album, artist, year, cover) VALUES (115, 'houses of the holy', 'led zeppelin', 1973, 'junk')


text:
Q: Can I install Ubuntu before Windows? I ordered Lenovo desktop PC M710t, which is freeDOS OS.
Usually Windows is installed first, and Ubuntu after for dual boot.
Can I switch the OS installation order?
Because I haven't purchased Windows 10 OS yet.

A:
Can I switch the OS installation order?

Yes.
You usually install Windows 1st because the last installed OS uses its bootloader to take presedence. And our grub adds Windows. Windows though does not add other operating systems.
But you could always install Windows last and use a tool like boot-repair to install Grub.
Nowadays we use (U)EFI. And there the boot is done by creating a little bit of room on the disk where you install a file that points to an operating system. So the order does not matter anymore: you tell inside the BIOS you want to install an OS and it will add your OS to the EFI.
So yes. Totally possible.


text:
Q: How to autostart a fully trusted sideloaded app? I have finished a .NET 6 sideloaded, fully trusted app to be deployed on a IoT environment. I want it to autostart when Windows starts, but the method of adding a shortcut to the Startup folder doesn't work. "Windows Start -> App Icon -> More >" doesn't show the option to "Open File Location", you can still find it with Task Manager while the app is running, and copy the shortcut to Startup folder, but that brute force approach doesn't work due to lack of permisions I suspect.
Cortana for example can autostart, so, it should be possible, is the correct procedure documented somewhere?, should it be an entry or a flag in the app manifest?


text:
Q: Problem I.5.4(c) in Hartshorne The problem asks to show that if $Y$ is a projective curve in $\mathbb{P}^2$ of degree $d$ and $L$ is a line such that $Y \neq L$, then $\sum_{P \in L \cap Y} (L \cdot Y)_P = d$.
The solution given here http://math.berkeley.edu/~reb/courses/256A/1.5.pdf, assumes that $L$ is given by $y=0$. This is without loss of generality, since we can always arrive there by a linear change of coordinates. Then the solution looks at $Y\ \cap U_z$, i.e. in the affine open chart where $z \neq 0$, and writes the equations that givees $Y \cap U_z$ as $f(x) + y(*)=0$. Then it claims that if $a$ is a root of $f$ of multiplicity $m$, we have that $(L \cdot Y)_{(a,0)}=m$.
Question 1: This claim would be true by $I.5.4(b)$, if the line $y=0$ were not in the tangent cone of $f(x) + y(*)=0$. But why would this be true in general? What is the ``without loss of generality" argument, if any? (Example that i am thinking of is  $Y=Z(x^3z+yz^3+yx^3)$)
Question 2: I totally don't understand the last argument of this solution. Why look at the point $(0:1:0)$ and how do we get this local form of $f$?

A: *

*The claim does not depend on $y=0$ being in the tangent cone or not. I am going to use $\alpha$ for what they call $x$ (the root of $f$). You are computing the length of the quotient of $k[x,y]_{(x-\alpha, y)}$ by the ideal
$$(f(x) + y(*), y).$$
This is the length of the quotient of $k[x]_{(x-\alpha)}$ by $(f(x))$ which does not depend on anything except the multiplicity of the root.

*In the affine patch (i.e. #1) you don't see infinity! The line and the curve might intersect at the point of infinity ($z=0$), and so we must check there too. They should be checking the point $(1 : 0 : 0)$ because we are on the line $L$ given by $y=0$ after all. Now you need to homogenize and then set $x = 1$. Set $f(x) = \sum a_ix^i$. The equation for the curve $Y$ is
$$\sum_{i=0}^n a_ix^iz^{d-i} + y(*) = 0 \overset{x=1}{\Longrightarrow} \sum_{i=0}^n a_i z^{d-i} + y(*) = 0.$$
Note that in each place I use $(*)$ it is different. Now using the same computation as in 1 above, we see that the multiplicity at $[1 : 0 : 0]$ is just the multiplicity (in the elementary sense - count the roots) of $\sum_{i=0}^n a_iz^{d-i}$ at $z=0$. This is $d-n$.


text:
Q: Write Table in R with a Set number of Decimal Places without changing to character data type I want to use write.table to produce an output with 18 decimal places, in numeric format (for those columns that are Numeric) containing no NA values...
For Example, in the table below - The Value Column would be classed as Numeric data type and would have 18 decimal places.
Country,   Category,   Volume
Germany, Food, 123456.123456789123456789
Poland, Drink, 654321.987654321987654321
Latvia, Food
The Code Below would produce an output file... and in this file it seems that R decides how many decimal places are saved (not Enough for my purposes).
 write.table(myDF,file = "TEST", row.names = FALSE, dec = ".",col.names =
 TRUE, na = "", sep = "|", quote = FALSE)

The Code Below does produce an output file with 18 decimal places - but the problem with using the format function is that the value column would now be character data type. This also produces NA strings (Latvia in the example above was originally blank is now a NA but in character format - which write.table cannot remove from the final file.
 write.table(format(myDF,digits=18,scientific = FALSE),file =
 "TEST", row.names = FALSE, dec = ".", col.names =
 TRUE, na = "", sep = "|", quote = FALSE)

Please advise on how to proceed? Many thanks!


text:
Q: How to know the adress of call in main, and what do this values mean? GDB so i am doing some basic assembly exercises since i'm not very experienced with it and i can't find an answer to this questions.
First one asks for the address of the call instruction that calls the function "calc" on main. It tells me that "calc" has 5 bytes. I only have the assembly code for the function calc itself. The adress of "calc" is 0x08048424 and the last one is
8048470: c3    ret

Ret has nothing in front of it. How do i know the address of call based on this or am i missing something?
The second one, i have this line of code in the middle of "calc":
804845f: 7e **??**        jle 8048454

It asks me to replace the ?? with the right byte value, and justify why. What does those values mean? I can't find that anywhere. And what would be the answer?
Thanks guys

A: The ?? (second byte) represent the relative offset of the JMP instruction.
I found more information here:
http://thestarman.pcministry.com/asm/2bytejumps.htm
Hope it helps someone


text:
Q: Tableau Service Management vs Tableau Server I am a beginner of Tableau.
I have gone through the Trusted Authentication on Tableau online help.
But I found that to add the web server IP address to https://tsm-computer-name:8850.
And I found that Tableau Server domain and Ip address are also required.
So I just want to know the following questions.
Are Tableau Server and Tableau Service Management on different computers?
If so, where should TSM be installed and how?
How do I create a TSM credential (admin)?

A: They way I differentiate two, is TSM (Tableau Services Manager) is the backend admin account and is used for configuring and licensing Tableau Server.
The Tableau Server Administrator account is used to administer the content published to Tableau Server, user/ groups and permissions.
TSM is automatically installed when installing Tableau Server, and the account used to log into TSM is typically the account being used to remote into the machine hosting Tableau Server. I found a decent guide using their online help.
https://onlinehelp.tableau.com/current/server/en-us/sign_in_tsm.htm
Also, a good way to verify which user can/is being used for TSM is to try running a TSM command from CLI. For example, running ' TSM Status -v ' should prompt you for a password for X user, this is what you would log into the TSM UI with.

A: Tableau Services Manager (TSM) replaces multiple tools from previous versions of Tableau Server: Tableau Server Configuration, tabadmin command line, Tableau Server
Monitor, and Manage License Keys.
Online guide gives more details.
https://www.tableau.com/sites/default/files/whitepapers/tsm_slideshare.pdf


text:
Q: Folder attributes lost on copy or move in Windows 10 1607 (Anniversary Update) Windows 10 1511

*

*Make copy of folder with attributes +R/+S on same partition - Copy has same attributes set

*Make copy of folder with attributes +R/+S on different partition - Copy has same attributes set

*Move folder with attributes +R/+S on same partition - Folder still has same attributes set

*Move folder with attributes +R/+S to different partition - Folder still has same attributes set

Windows 10 1607

*

*Make copy of folder with attributes +R/+S on same partition - Copy loses attributes

*Make copy of folder with attributes +R/+S on different partition - Copy loses attributes

*Move folder with attributes +R/+S on same partition - Folder still has same attributes set

*Move folder with attributes +R/+S to different partition - Folder loses attributes

*

*Does this affect everyone? (Update: Seems to be the case. Given the comments below though, for anyone testing this behavior I repeat, please check for folder and not file attributes.)

*Is it a bug or a deliberate change by Microsoft? (And if the latter, was it announced anywhere?)

*Regardless of the answer to #2, is there any way to make 1607 behave the same as 1511?

A: Microsoft has acknowledged and fixed this Windows 10 BUG in Insider Preview build 15019. You can use llandyw's right-click solution till such time the fix is released to the general public.


text: Q: Dynamic Templates using Angular JS I'm following this Blog post < http://onehungrymind.com/angularjs-dynamic-templates/> to understand the loading of dynamic templates using Angular JS in the same view. Now my requirement is slightly different where the dynamic template needs to be loaded in the button click and not in the container div as suggested in the Blog Post. I am  stuck to figure out as to how to do this. Can somebody help ? Pl read through the blog post or leave your comment in case you need more clarity


text:
Q: How to prevent http.ListenAndServe altering style attributes in static output? In a very rudimentary handwritten web page (no js, stylesheets, etc) I have some static html with a section that looks like this.

    Reload HMI

I'm using Go's http.ListenAndServe to serve the page. What's coming out looks like this:

    Reload HMI

Note the altered style attribute.
The server implementation is also rudimentary. It's launched as a goroutine:
// systemControlService provides pages on localhost:8003 that
// allow reboots, shutdowns and restoring configurations.
func systemControlService() {
    info("Launching system control service")
    http.HandleFunc("/", controlPage)
    log.Fatal(http.ListenAndServe(":8003", nil))
}

// loadPage serves the page named by title
func loadPage(title string) ([]byte, error) {
    filename := "__html__/" + title + ".html"
    info(filename + " requested")
    content, err := ioutil.ReadFile(filename)
    if err != nil {
        info(fmt.Sprintf("error reading file: %v", err))
        return nil, err
    }
    info(string(content))
    return content, nil
}

// controlPage serves controlpage.html
func controlPage(w http.ResponseWriter, r *http.Request) {
    p, _ := loadPage("controlpage")
    fmt.Fprintf(w, string(p))
}

In func loadPage() above, info is a logging call. For debug, I'm calling it just before returning the content of controlpage.html. The log entry shows it's not mangled at that point, so the problem pretty much has to be within ListenAndServe.
I'm not finding anything in the Go docs for http that seems applicable. I have no idea what's going on here. Any help appreciated.

A: There are several problems with your code (including the fact that it exists at all when you could use http.FileServer to serve static content, and the fact that you read the whole response into a []byte before sending it back instead of streaming it) but the main one is this:
fmt.Fprintf(w, string(p))

Fprintf's first argument is a format string. Replacing things in the format string that start with % is what it does. To write a []byte to a writer you don't need the fmt package, because you don't want to format anything. w.Write() is good enough. fmt.Fprint is also available but completely unnecessary; it will do extra work that amounts to nothing and then call w.Write.

A: The problem is that fmt.Fprintf is interpreting the response body as a format string with % substitutions. One way to fix this is to supply a format string:
fmt.Fprintf(w, "%s", p)

There's no need to convert p to a string with this approach.
The goal here is to write bytes to the response writer. The idiomatic and most efficient way to write bytes to a response writer (or any other io.Writer) is:
w.Write(p)

The fmt package is not appropriate to use here because no formatting is required.

A: Can you try this, note Fprint rather than Fprintf
func controlPage(w http.ResponseWriter, r *http.Request) {
    p, _ := loadPage("controlpage")
    fmt.Fprint(w, string(p))
}


text:
Q: Postgresql - Select Count of 'votes' but only including the latest I've been staring at this for 20 minutes and can't wrap my head around it.  I've done it before, I just don't remember in which project ( so i can reference code ).
I have a table as such:
votes [table]
  id - serial , primary
  useraccount_id - id
  object_id - id
  vote - int
  timestamp_vote - timestamp

I need to be able to select the current total of votes for any one object.
However - this table acts as a 'timeline' view as well. note that i'm using a sequence as an id column.  there may be multiple records for useraccount_id + object_id
Unfortunately, this is not what i need:
SELECT
   vote , count(vote)
FROM
   votes
WHERE
   object_id = 161
GROUP BY
   vote ;

i know need to use a subquery and distinct, and an 'order by timestamp desc' , to limit to the latest vote by a given user.  i just can't remember how to string that SELECT together.
-- adding sample data --
Sample Data
 id | object_id  | useraccount_id |     timestamp_created      | vote
----+------------+----------------+----------------------------+------------
  2 |        153 |             57 | 2012-12-11 18:37:20.421013 |    1
  3 |        153 |             57 | 2012-12-11 18:48:39.963748 |    2
  4 |        153 |             57 | 2012-12-11 18:48:42.869945 |    3
  5 |        153 |             57 | 2012-12-11 18:48:48.991617 |    1
  6 |        153 |             57 | 2012-12-11 19:34:26.701351 |    2
  7 |        153 |             57 | 2012-12-11 19:35:52.449031 |    3
  8 |        153 |             57 | 2012-12-11 19:35:52.986822 |    1
  9 |        153 |             57 | 2012-12-11 19:35:53.850291 |    2
 10 |        153 |             58 | 2012-12-11 19:35:55.884202 |    3
 12 |        153 |             58 | 2012-12-11 19:35:56.803337 |    1
 13 |        153 |             59 | 2012-12-11 19:37:04.563519 |    3
 15 |        153 |             60 | 2012-12-11 19:37:40.618324 |    3
 16 |        153 |             61 | 2012-12-11 19:37:40.618324 |    3
 17 |        153 |             62 | 2012-12-11 19:37:40.618324 |    3
 18 |        153 |             63 | 2012-12-11 19:37:40.618324 |    2

The expected output is:
vote | count
-----+------
1    | 1        # user 58 cast a vote of `3` , then `1`.  only the latest vote of `1` counted.
2    | 2        # user 57 switched votes many times. only their last vote of `2` counted. user 63 cast a vote of `2` as well.
3    | 4        # users 59,60,61,62 all voted `3`

A: select vote,
       count(vote) as cnt
from (
   select vote,
          row_number() over (partition by vote order by timestamp_created desc) as rn
   from votes
)
where rn = 1
group by vote;

A: You can try something like that:
SELECT DISTINCT ON (useraccount_id, object_id)
       vote,
       timestamp_vote,
       useraccount_id,
       object_id
FROM votes
WHERE object_id = 161 -- your filter here
ORDER BY useraccount_id, object_id, timestamp_vote DESC

It will give you the last vote for every (useraccount_id, object_id).
Then:
SELECT SUM (CASE WHEN vote THEN 1 ELSE 0 END) as true_vote_sum,
       SUM (CASE WHEN vote THEN 0 ELSE 1 END) as false_vote_sum
FROM (SELECT DISTINCT ON (useraccount_id, object_id)
             vote
      FROM votes
      WHERE object_id = 161 -- your filter here
      ORDER BY useraccount_id, object_id, timestamp_vote DESC)

To get the count of the votes.
Details: DISTINCT ON, CASE WHEN


text:
Q: SYMFONY Serializer - Malformed UTF-8 characters, possibly incorrectly encoded I'm trying to setup my Symfony 4.3 project in local machine (MAC OS - MAMP 4 - php 7.2 - mysql 5.6) but I have an error on serialization. This error does not exist in the production site.
Data is inserted with doctrine fixtures.
Here some details:
Serializer exception
The cause of the exception (The ? symbol)
Doctrine configuration
Mysql table configuration
Hope you can help me

A: The problem was coming from the strtolower function. The result is "Hélène" wihout strtolower and b"hã©lã¨ne" with the strtolower.
use mb-strtolower instead php.net/manual/en/function.mb-strtolower.php

A: As the OP pointed out the problem was happening when using the strtolower function.
Quoting from the documentation:

strtolower ( string $string ) : string
Returns string with all alphabetic characters converted to lowercase.
Note that 'alphabetic' is determined by the current locale. This means that e.g. in the default "C" locale, characters such as umlaut-A (Ä) will not be converted.

To fix this, you could:

*

*Option 1: Set the "correct" locale for your use case.

*Option 2: Use mb_strtolower

About mb_strtolower:

By contrast to strtolower(), 'alphabetic' is determined by the Unicode character properties. Thus the behaviour of this function is not affected by locale settings and it can convert any characters that have 'alphabetic' property, such as A-umlaut (Ä).

Depending on your usecase/setup, the second way might not be the best way for you to use, since:

*

*You need to install/enable Multibyte String

*It's MUCH slower, than the strtolower function


text:
Q: How to get object key from the api call dynamically and change the payload structure format? How can I store the following current array of objects into the object key and value pairs by using the key dynamically? I have another api that uses the same api call, but instead of using the keys Desc and DSTR_NR, it has different keys:
{
  list: [
    [
      {
        Desc: {
          value: '7777 - Florida Hurricane'
        },
        DSTR_NR: {
          value: '7777'
        }
      },
      {
        Desc: {
          value: '7172 - Virginia Severe Storm(s)'
        },
        DSTR_NR: {
          value: '7172'
        }
      }
    ]
  ]
}

I tried to do the following but it didn't help:
const data = list.map((item) => {
  return {
    name: Object.values(item),
    value: Object.values(item)
  }
})

Desired format I want am looking for is this:
{
  list: [
    {
      name: '7777',
      value: '7777 - Florida Hurricane'
    },
    {
      name: '7172',
      value: '7172 - Virginia Severe Storm(s)'
    }
  ]
}

A: Object.values gives an array of all the values of that object.
Also your list is an array of array so you have to flatten it first or if it just has one value use list[0]
An Example solution can be as below

const data = {
  "list": [
    [{
      "Desc": {
        "value": "7777 - Florida Hurricane"
      },
      "DSTR_NR": {
        "value": "7777"
      }
    }, {
      "Desc": {
        "value": "7172 - Virginia Severe Storm(s)"
      },
      "DSTR_NR": {
        "value": "7172"
      }
    }]
  ]
};

const newList = data.list.flat().map(item => ({
  name: item.DSTR_NR.value,
  value: item.Desc.value
}));

console.log({
  list: newList
})


text:
Q: How to exit C# application gracefully when application is killed through task manager or system restart I have a C# Windows application that marks the user as logged in in a database when he logs in to application and marks him as logged out when he exits the application.
My problem is that my application does not mark the user as logged out in the database when the user kills the application through the task manager or when the system is restarted without logging out of the application.
Is there any way to mark the user as logged out in these two situations?

A: You can't solve your initial problem (mark the user as logged out in the database) this way. Consider another solution, e.g. some datetime column in database table, which will updated periodically by every logged user, telling to your application that user is alive.


text:
Q: Don't show "add / show 1 more comment" when there are 6 comments Problem
When there are 6 comments, 1 is hidden:

This doesn't make sense.  The amount of space is roughly equal to that of 1 comment.  We should just show the comment instead, and save me the click.
Proposal
If there are this many comments     Show this many     Hide this many

    5                                   5                  0

    6                                   6                  0

    7                                   5                  2

This has really been annoying me lately.  Facebook does it too, and it doesn't make any sense there.
(When searching for dupes, I noticed an unanswered similar feature request from > 2 years ago here - not sure if that really counts as a dupe since it was never addressed or answered.)

A: The problem is that if this change is made, someone down the road will post a feature request that says "Don't show add/show 1 more comment when there are 7 comments", with this table:
Proposal
If there are this many comments     Show this many     Hide this many

    6                                   6                  0

    7                                   7                  0

    8                                   6                  2

There has to be a line drawn at some point, and where it is now seems just as good as anywhere else. There's no benefit to be had from making this change, IMO, other than saving the occasional single mouse click.
There's an additional issue here, too. The suggested change makes the assumption that the comment not shown is a single-line comment.

The amount of space is roughly equal to that of 1 comment

If it's more than a single line comment, it indeed requires additional space on the page to display, which can be considerable if the comment uses most of the available characters.


text:
Q: Overriding generic varargs function with a specific one I'm trying to write a library function(f) that uses another weight function(w) in it's implementation.
I want to have a default weight function(dw) in use but also to allow users of the library function(f) to provide their own weight function(w).
I made an interface for weight functions that has a calculate function. However, because I don't know what parameters such function would require, I defined it like this:
public interface WeightFunction {
    double calculate(Object ... arguments);
}

However, when I override it with my default function(dw), I did this ugly thing:
 @Override
    public double calculate(Object ... arguments) {
        return calculate((Pixel)arguments[0], (Pixel)arguments[1]);
    }

    public double calculate(Pixel u, Pixel v){
        //logic here
        return 0;
    }

Is there a more elegant way to do this? Is this considered good form?

A: You might like to use Generics?
public interface WeightFunction<T> {
    double calculate(T ... arguments);
}

class A implements WeightFunction<Pixel> {

    @Override
    public double calculate(Pixel... arguments) {
        return calculate(arguments[0], arguments[1]);
    }

    public double calculate(Pixel u, Pixel v){
        //logic here
        return 0;
    }
}

You could also just use a single argument and allow the caller to wrap all his arguments in a class. This might be better in case you have arguments of multiple different types.
public interface WeightFunction<T> {
    double calculate(T argument);
}

@Override
public double calculate(SeededPixels arg) {
    return calculate(arg.u, arg.v); // * arg.seed
}

class SeededPixels {
    public final Pixel u;
    public final Pixel v;
    public final long seed;

    SeededPixels(Pixel u, Pixel v, long seed) {
        this.u = u;
        this.v = v;
        this.seed = seed;
    }
}

A: Generics is the way to go. But interpreting this in your question:

However, because I don't know what parameters such function would require, I defined it like this:

and your first comment to answer from Gregor Koukkoullis I think that your problem is that you just need to (and should) declare every method that takes different amount of parameters. There just is no other way around but it is anyway more clear this way.
So you should have something like this:
public interface WeightFunction<T> {
    double calculate(T... arguments);
    double calculate(Long seed, T... arguments);
    double calculate(Long seed, Integer somethingElse, T... arguments);
}

Why varags parameters have to be the last? See this. The accepted answer propably is not the clearest one but few others will clarify the problem.
Now, when you implemented your calculate in your example somehow you knew what are the parameters?
@Override
public double calculate(Object ... arguments) {
    // you know here that the 2 first are pixels, dont you?
    return calculate((Pixel)arguments[0], (Pixel)arguments[1]);
}

So with the same knowledge you could just create a declaration of needed atributes in your interface. Maybe even:
double calculate(Long seed, T t1, T t2);

if there is more likely only two Ts.
And the answer to your question:

Is this considered good form?

IMO it is never a good habit to make functions that take an array of Objects and then you implement a method that interprets the params as it wants and does what it wants. I think it is strongly against the whole idea of interface.
It is always a better idea to declare methods that "tell" what they are doing and then just add a new method declaration or refactor your interface and already implemented methods when there is a need for that.
If you choose to pass "a list of objects" anytime you need some flexibility, you are soon a knee-deep in it.
Now this may raise a question that do I have to implement all the methods n this interface? Yes, but if you do not want to you can either define separate interfaces and make your class implement 1 or more of them or/and use extends to make interface hierarchy.


text:
Q: Base price, discounted price and percentage discount in the summary checkout I need to have the discounted, base, and percentage off prices in the summary checkout.
I found the file that prints and it is this checkout/summary/item/price/row_excl_tax.html but I can't retrieve the base price or even calculate the discount percentage on the item

A: In Magento 2, you can add the base price, discounted price, and percentage discount to the summary checkout by modifying the template files and creating a new block class. Here is an example of how you can do this:

*

*Override the "checkout_cart_item_renderers.xml" layout file in your custom module. You can create a new directory called "Magento_Checkout" in the "view/frontend" directory of your custom module and create a new file called "layout/checkout_cart_item_renderers.xml" within it.

*In the "checkout_cart_item_renderers.xml" file, add the following code to add a new block to the summary checkout template:
Here is the code:-
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">

        <referenceBlock name="checkout.cart.item.renderers">
            <block class="YourVendor\YourModule\Block\Checkout\Discount" name="checkout.cart.item.renderers.discount" template="YourVendor_YourModule::checkout/discount.phtml" after="checkout.cart.item.renderers.name"/>
        </referenceBlock>

</page>

*Create a new block class called "Discount.php" in the "Block/Checkout" directory of your custom module.

*In the "Discount.php" file, add the following code to define your new block class and retrieve the base price, discounted price, and percentage discount:
Here is the code:-
<?php

namespace YourVendor\YourModule\Block\Checkout;

use Magento\Framework\View\Element\Template;

class Discount extends Template
{
    public function getDiscount()
    {
        $item = $this->getItem();
        $basePrice = $item->getPrice();
        $discountedPrice = $item->getDiscountAmount();
        $discountPercent = 0;
        if ($basePrice > 0) {
            $discountPercent = ($discountedPrice / $basePrice) * 100;
        }
        return [
            'base_price' => $basePrice,
            'discounted_price' => $discountedPrice,
            'discount_percent' => $discountPercent
        ];
    }
}

*Create a new template file called "discount.phtml" in the "view/frontend/templates/checkout" directory of your custom module.

*In the "discount.phtml" file, add the following code to display the base price, discounted price, and percentage discount in the summary checkout:
Here is the code:-
<?php
$discount = $block->getDiscount();
$basePrice = $discount['base_price'];
$discountedPrice = $discount['discounted_price'];
$discountPercent = $discount['discount_percent'];
?>

    Base Price: <?php echo $basePrice ?>
    Discounted Price: <?php echo $discountedPrice ?>
    Discount Percent: <?php echo $discountPercent ?>

Let me know if any query.
THANKS.


text:
Q: How to change properties of point tracker without re-initializing tracking? I am working on point tracker, I know I can set the properties of tracker initilay by using :
tracker = vision.PointTracker('NumPyramidLevels',3,'MaxBidirectionalError', 2, 'MaxIterations',30,'BlockSize',[5 5]);
initialize(tracker, points.Location, objectFrame);

and then by using step method the tracking is working fine.
my question how to make these properties dynamic during the tracker is working, I used same method inside the while statment as following:
while ~isDone(videoFileReader)
    frame = step(videoFileReader);
    [points, validity,scores] = step(tracker, frame);
tracker = vision.PointTracker('NumPyramidLevels',3,'MaxBidirectionalError', 2, 'MaxIterations',30,'BlockSize',[5 5]);
initialize(tracker, points, objectFrame);
end

but the problem here that the tracker is initialized again! but I need to continue on the prevouis fram state without initialize the tracking again.

A: Unfortunately, the short answer is "no".
vision.PointTracker is a System Object, which is a special kind of MATLAB class. In a System Object, properties may be tunable or non-tunable. Non-tunable properties can only be changed before you call the step method of the object for the first time. Currently, all properties of vision.PointTracker are non-tunable, which means you cannot change their values inside the loop.


text:
Q: How to append table with match of other table multiple column data I have two table. one with 50 records in table A and other with 100 in table B.
Both table have customer id and date on it.
Both table have duplication but there are less number of unique customer in table with 50.
Now i wish to put date of customer in table B in front of customer in table A. a customer can appear more than 2 time in table B.
So number of time it appear, number of column appended with date in front of the customer.
Id    Date
1   1/01/2016
2   2/01/2016
2   3/01/2016
3   1/01/2016
4   4/01/2016
5   5/01/2016
6   1/01/2016
7   3/01/2016
8   4/01/2016
9   1/01/2016
1   6/01/2016
10  1/01/2016
For eg. this is table A
and Table B is
Id     Date
1   1/01/2016
2   2/01/2016
2   3/01/2016
3   1/01/2016
4   4/01/2016
5   5/01/2016
6   1/01/2016
7   3/01/2016
8   4/01/2016
9   1/01/2016
1   6/01/2016
10  1/01/2016
1   15/01/2016
2   16/01/2016
2   17/01/2016
3   18/01/2016
4   19/01/2016
5   20/01/2016
6   21/01/2016
7   16/01/2016
8   20/01/2016
9   21/01/2016
1   16/01/2016
10  18/01/2016
1   19/01/2016
2   2/02/2016
2   30/01/2016
3   16/01/2016
4   31/01/2016
5   21/01/2016
6   18/01/2016
7   19/01/2016
8   16/01/2016
9   2/02/2016
1   18/01/2016
10  19/01/2016

I wish to have output given under

Id   Date    Date1   Date2
  1   1/01/2016   15/01/2016  19/01/2016
  2   2/01/2016   16/01/2016  2/02/2016
  2   3/01/2016   17/01/2016  30/01/2016
  3   1/01/2016   18/01/2016  16/01/2016
  4   4/01/2016   19/01/2016  31/01/2016
  5   5/01/2016   20/01/2016  21/01/2016
  6   1/01/2016   21/01/2016  18/01/2016
  7   3/01/2016   16/01/2016  19/01/2016
  8   4/01/2016   20/01/2016  16/01/2016
  9   1/01/2016   21/01/2016  2/02/2016
  1   6/01/2016   16/01/2016  18/01/2016
  10  1/01/2016   18/01/2016  19/01/2016

Any help is much much appreciable. Thanks

A: This should explain how to use joins. Once you learn about that you can write SQL yourself.
http://www.w3schools.com/sql/sql_join.asp
try understanding LEFT and Inner Joins

A: try this (not easy)
with tmp1 as (
select row_number() over(order by (select null) ) - 1 newid , (row_number() over(order by (select null)) - 1) %12 rg1 ,  f1.*
from table2 f1
),
tableranked as (
select DENSE_RANK() over(partition by rg1 order by newid) rg2, f2.*
from tmp1 f2
)
select  f1.id, f1.date, f4.date1, f4.date2
from tableranked f1 inner join (select f2.id, f2.date as date1, f3.date as date2 , f2.rg1
                                from tableranked f2
                                inner join tableranked f3 on f2.id=f3.id and f2.rg2+1=f3.rg2 and f2.rg1=f3.rg1
                                where f2.newid>=12 and f3.newid>=12
                                ) f4 on f1.id=f4.id and f1.rg1=f4.rg1
where f1.newid<12


text:
Q: how can I make logo background fill header? I am wondering how to accomplish this logo background found here
if you notice the logo floated to the left and how the white "D" is on a red color background that fills the entire height of the header. I know how to float it and everything, I just need to know how to make a background color with a certain width to fill the entire height of the header like so. And by the way I am assuming  that there is no set height already for the header.
Thanks in advance!

A: Whatever id or class your floated div is for the logo, simply apply a background color to that in CSS.
If you're looking for some sort of dynamic height application; set the html, body, and enclosing div elements to all have 'height:100%'.
Posting a sample of your code would help.

A: You may want to try something like this (fiddle here):
HTML:

CSS:
#Header {
    width: 600px;
    height: 60px;
    background: #333333;
}

#Logo {
    width: 60px;
    height: 60px;
    float: left;
    background: #666666;
}

As you can see, the image already has transparency, so any background color set to this block would render behind the actual image. Either that or put your img inside another container with a specified background color.


text:
Q: A fact about Hermitian matrices. We know that if $A$ is a hermitian matrix then $X^{*}AX$ is real for all $X$ in $\Bbb{C^{n}}$.Now my question is, is it true that if $X^*AX$ is real for all $X$ in $\Bbb{C^{n}}$ then $A$ has to be hermitian?
My try:
Taking $X$ as $e_{i}$ we are getting $a_{ii}$ to be real.Then taking $X$ to be $e_{i}+e_{j}$ we have $a_{ii}+a_{ij}+a_{ji}+a_{jj}$ to be real.So $a_{ij}+a_{ji}$ has to be real for all i,j.So if $a_{ij}$ is of the form $b+ic$ then,then $a_{ji}$  has to be in the form $p-ic$.But i can't say b=p.That's where i got stuck.
Any help will be appreciated.And i would like to know if there is any conceptual way to do this without these computations.Thanks in advance.

A: The condition reduces to $ X^{*}(A-A^{*})X = 0 $ for all $ X \in \mathbb{C}^{n} $.
$ (A-A^{*}) $ is normal, so by spectral theorem there is a unitary matrix $ P $ such that $ P^{-1} (A - A^{*}) P $ is diagonal. But our condition forces this diagonal matrix to be $ 0 $, i.e $ (A-A^{*}) = 0 $, as needed.

A: You know that $\langle X,AX\rangle=\langle X,A^*X\rangle$ (because these are real numbers) so that $\langle X,TX\rangle=0$ with $T=A-A^*$.
Let $\varphi(X)=X^*TX$ (so here, $\varphi$ is actually $0$). Then, you know that
$$\langle X,TY\rangle=
X^*TY={\frac 12}\bigl (\varphi (X+Y)-\varphi (X)-\varphi (Y)\bigr)+{\frac{\rm {i}}2}\bigl(\varphi (X+{{\rm {i}}}Y)-\varphi (X)-\varphi (Y)\bigr )$$
(this is the polarization identity).
By replacing $\varphi$ by $0$ you get that $\langle X,TY\rangle=0$ for all $X,Y$, so that $T=0$, hence $A$ is self-adjoint.


text:
Q: How to connect to database which in VM at the same machine without network cable? I have a VM at my Laptop and I installed Oracle database on it.. I need to access this database from the main windows (host) without connect a network cable..
I am using Oracle VM software.
I am using bridge option in VM network setting.. I cant access to VM database if the network cable not connected.
how I can do it?
thanks

A: If you want your host and VM to communicate without a physical network, you'll need to create a host-only network and set up your VM to use that.
This guide walks through it in detail, but the basic steps are:

*

*In VirtualBox Manager, go to Tools > Network, and create (or use existing) virtual host-only network, with DHCP server enabled.

*Turn your VM off. Go to Settings > Network and create a new host-only adapter, choosing the network from step 1.

*Turn your VM on, and find its IP address.

*Connect to the VM from the host


text:
Q: Android XML Parser Exception Caught Could someone please check on codes. My XMLParser has caught an exception. I'm trying to use tabs fragments with listview using XML Parser to parse results from remote database.
MainActivity.java
public class MainActivity extends SherlockFragmentActivity implements TabListener {
    private Fragment mFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.main);

        ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        actionBar.setDisplayShowTitleEnabled(true);

        //mFragment = new AppleFragment();

        Tab tab = actionBar.newTab()
                .setText("Apple")
                .setTabListener(this)
                .setIcon(R.drawable.apple);

        actionBar.addTab(tab);

    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
         if (mFragment == null) {
                mFragment = new AppleFragment();
                ft.add(android.R.id.content, mFragment);
            } else {
                ft.attach(mFragment);
            }
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
        ft.detach(mFragment);
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }
}

AppleFragment.java
public class AppleFragment extends SherlockListFragment{

        static final String URL = "http://api.androidhive.info/pizza/?format=xml";
        // XML node keys
        static final String KEY_ITEM = "item"; // parent node
        static final String KEY_ID = "id";
        static final String KEY_NAME = "name";
        static final String KEY_COST = "cost";
        static final String KEY_DESC = "description";

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){

        return super.onCreateView(inflater, container, savedInstanceState);

        }

        public void onActivityCreated(Bundle savedInstanceState) {

            ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();

            XMLParser parser = new XMLParser();
            String xml = parser.getXmlFromUrl(URL); // getting XML
            Document doc = parser.getDomElement(xml); // getting DOM element

            NodeList nl = doc.getElementsByTagName(KEY_ITEM);
            // looping through all item nodes <item>
            for (int i = 0; i < nl.getLength(); i++) {
                // creating new HashMap
                HashMap<String, String> map = new HashMap<String, String>();
                Element e = (Element) nl.item(i);
                // adding each child node to HashMap key => value
                map.put(KEY_ID, parser.getValue(e, KEY_ID));
                map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
                map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
                map.put(KEY_DESC, parser.getValue(e, KEY_DESC));

                // adding HashList to ArrayList
                menuItems.add(map);
            }

            ListAdapter adapter = new SimpleAdapter(getActivity(), menuItems,
                    R.layout.list_item,
                    new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
                            R.id.name, R.id.desciption, R.id.cost });

            setListAdapter(adapter);

        }
}

XMLParser.java
public class XMLParser {

    // constructor
    public XMLParser() {

    }

    /**
     * Getting XML from URL making HTTP request
     * @param url string
     * */
    public String getXmlFromUrl(String url) {
        String xml = null;

        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity);

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }

    /**
     * Getting XML DOM element
     * @param XML string
     * */
    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {

            DocumentBuilder db = dbf.newDocumentBuilder();

            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is);

            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }

            return doc;
    }

    /** Getting node value
      * @param elem element
      */
     public final String getElementValue( Node elem ) {
         Node child;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                     if( child.getNodeType() == Node.TEXT_NODE  ){
                         return child.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }

     /**
      * Getting node value
      * @param Element node
      * @param key string
      * */
     public String getValue(Element item, String str) {
            NodeList n = item.getElementsByTagName(str);
            return this.getElementValue(n.item(0));
        }
}

LOGCAT :
10-05 16:36:50.453: E/AndroidRuntime(20162): FATAL EXCEPTION: main
10-05 16:36:50.453: E/AndroidRuntime(20162): java.lang.RuntimeException: Unable to start activity ComponentInfo{in.wptrafficanalyzer.actionbarsherlocknavtab/in.wptrafficanalyzer.actionbarsherlocknavtab.MainActivity}: android.os.NetworkOnMainThreadException
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.app.ActivityThread.access$600(ActivityThread.java:127)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.os.Handler.dispatchMessage(Handler.java:99)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.os.Looper.loop(Looper.java:137)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.app.ActivityThread.main(ActivityThread.java:4512)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at java.lang.reflect.Method.invokeNative(Native Method)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at java.lang.reflect.Method.invoke(Method.java:511)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:982)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:749)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at dalvik.system.NativeStart.main(Native Method)
10-05 16:36:50.453: E/AndroidRuntime(20162): Caused by: android.os.NetworkOnMainThreadException
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at java.net.InetAddress.getAllByName(InetAddress.java:220)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at in.wptrafficanalyzer.actionbarsherlocknavtab.XMLParser.getXmlFromUrl(XMLParser.java:45)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at in.wptrafficanalyzer.actionbarsherlocknavtab.AppleFragment.onCreateView(AppleFragment.java:38)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:870)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1080)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:622)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1416)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:505)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1136)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.app.Activity.performStart(Activity.java:4475)
10-05 16:36:50.453: E/AndroidRuntime(20162):    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1943)
10-05 16:36:50.453: E/AndroidRuntime(20162):    ... 11 more

A: You're running a network operation on main thread. Use async task to run network operations in background thread (do your xml parsing in a background thread). That's why you are getting android.os.NetworkOnMainThreadException.
parse it in an async task like this:
class XMLParsingTask extends AsyncTask<String, Void, RSSFeed> {

    protected void onPreExecute() {
    //show a progress dialog to the user or something
    }

    protected void doInBackground(String... urls) {
        //Parse your XML here
    }

    protected void onPostExecute() {
        //do something with your parsed xml here and dismiss the progress dialog
    }
 }

 new RXMLParsingTask().execute(null);

Here are some tutorials for you if you don't know how to use async tasks:
http://mobileorchard.com/android-app-developmentthreading-part-2-async-tasks/
http://www.vogella.com/articles/AndroidPerformance/article.html
here are the official docs: https://developer.android.com/reference/android/os/AsyncTask.html

A: Move your network logic from main thread to separate thread, From Android 3.0, we need to execute all network related code on separate thread.


text:
Q: Calling methods in a win32 service with elevated privileges from an application I have developed a Win32 C/C++ application that creates dynamic WFP IP filters, however it must be run as admin to do so (due to the Windows security policy). I want to place the code that requires admin privileges in a service running with admin privileges and then call it from the application running as a normal user.
First is this the correct approach? And second, although I know how to create a service I cannot find any reference illustrating how to call methods in/send requests to a service.
Although I can probably cheat and play with the manifest, I don't mind extra work to do it correctly especially as the functionality will be reusable across applications.
Does anybody have any experience or pointers?

A: It is certainly the right approach to have a separate executable that has the privilege to perform the action you require, so that the main application can run in a restricted user account.  As for sending requests to the service, there is nothing special about the fact it is running as a service. Just consider it to be a process that runs with the credentials of an admin user.  So communicate with it in the same way you would in any other process-to-process situation, eg named pipes, network sockets, etc.