text:
Q: XmlBeans versus Axis for Web Service client stubs Has anyone had any personal experience on why XmlBeans might be preferred over Axis for invoking Web Services?

A: I don't think you can use XmlBeans to invoke WebServices. XmlBeans will create a bunch of Java classes representing data types encountered in a XML schema (XSD). Technically you could use those classes to invoke WebServices, but you will have to deal yourself with the SOAP protocol itself.
AXIS on the other hand, will create a bunch of Java classes from WSDL, and will also create STUB for connecting to the remote service through the SOAP protocol.
So, if what you are intending to do is make a WebService call, go for Axis or any other WebService client technology such as the one included by default with new SUN (should I say Oracle?) SDKs so you won't have to deal with external dependencies other than the JVM itself. Here is a nice tutorial on how to do JAX-WS with Java 6.
I used to use Axis a lot, now I switched almost exclusively to JAX-WS.


text:
Q: How to install PHP SOAP on REDHAT 5 How can I install SOAP php extension on REDHAT 5 server which runs PHP 4.4.5
I was not able to use yum since the os is not registered(and I have no rights to register)
I havent find any compatible versions of SOAP for PHP 4.4.5
Please help.

A: The native SOAP extension is only available since PHP 5.0.1. Because your server is running PHP4, you'll have to use a third party SOAP framework, such as NuSOAP.
NuSOAP doesn't require any installation or configuration at the server level. It's just a collection of PHP scripts that you need to include.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Google Speech recognition API stops recording after a few seconds This is the code to recognize speech, it stops recording in a few seconds. The mic icon from the Title Bar vanishes.
var streaming = new webkitSpeechRecognition();
streaming.lang = 'en-IN';
streaming.continuous = true;
streaming.interimResults = true;

streaming.onresult = function(event) {
  l_pos = event.results.length - 1 ;
  console.log(event.results[l_pos][0].transcript);
}

streaming.onend = function(event) {
  console.log("1")
  streaming.start();
  console.log("2")
}

streaming.start();

How do I make it record continuously?

A: if you want  to record continuously then you can do  one thing. There is an onstop or onend event. in that event you can start it again..


text:
Q: Can not get params from URL - why is my cgi.FieldStorage() empty? I cant get parameters from URL. After reading numerous posts on the web but nothing seems to answer my question...
I have a simple HTML file:

    <form action="test.py" method="get">
        Name: <input id="person_name" type="text" name="person_name" >
        <input id="submit_button" type="submit" value="Submit" >
    </form>

and my python script looks like this:
import cgi, cgitb

form = cgi.FieldStorage()
name = str( form.getvalue('person_name') )

print ("Content-type:text/html\n\n")
print ("")
print ("")
print ("")
print ("")
print ("Hello " + name )
print("
")
print ("all params: " + str(form)  )
print ("")
print ("")

However, when I execute the HTML file and type "Mike" as a name, my python script prints:
Hello None
all params: FieldStorage(None, None, [])

the cgi.FieldStorage() is empty.
How can I fix it?

A: It's hard to say.
<form action="test.py" method="get"> Error?
It should be <form action="cgi-bin/test.py" method="get">
If "cgi-bin" is not a part of the url sgi scripts are not executed. It's even surprising that you get some kind of response.

A:
I get "500 Internal server error"

It's better now. It looks like it is starting working. The problem is that your python script has no declaration. It starts with import cgi, cgitb when it should start with #!/usr/bin/python or #!/usr/bin/env python. Apache doesn't know what kind of script it is.

A: the 500 internal server error is a problem with your apache script configuration file especially the pythonhandler and addhandlers area something to do with mod-python


text:
Q: how to find last occurrence of a parent in a given below string I have a below pattern string.
'GP0|#92ca7467-4c0d-461a-aac4-2bc8fd9ee16a;L0|#092ca7467-4c0d-461a-aac4-2bc8fd9ee16a|Analysts;GTSet|#7fa22453-62b1-4bec-b73d-01ccf115d558;GPP|#fd613617-ba9d-43e5-9990-95f96f94af2a;GPP|#ba395283-6169-4c6d-84d5-1cecb3c2a73b;GP0|#a547b95c-0dfa-4f42-b540-e55872fb2e81;L0|#0a547b95c-0dfa-4f42-b540-e55872fb2e81|Awards;GP0|#c4363ae8-8608-4309-92f0-5079c69b47e4;L0|#0c4363ae8-8608-4309-92f0-5079c69b47e4|Digital Workplace;GP0|#1976b988-a993-4f13-a1e8-d847138eebc6;L0|#01976b988-a993-4f13-a1e8-d847138eebc6|Intranet;GP0|#a68218df-b9e8-4f07-bfff-22cab83bbc0d;L0|#0a68218df-b9e8-4f07-bfff-22cab83bbc0d|Microsoft;GP0|#57737444-1a1b-4c87-a479-1548b58e44e3;L0|#057737444-1a1b-4c87-a479-1548b58e44e3|Research;'

I want to get last occurrence of the pattern which starts with GPP and ends with ;
expected output: GPP|#ba395283-6169-4c6d-84d5-1cecb3c2a73b;

I tried this regex /GPP\|.+?;/i but it gives the first occurrence i.e. GPP|#fd613617-ba9d-43e5-9990-95f96f94af2a;

A: As they come after each other, you can match the pattern and assert that there is no following occurrence starting with the same pattern:
As the match ends on a single character, you can match any character except ; instead using a negated character class.
\bGPP\|[^;]+;(?!GPP\|[^;]+;)

Regex demo


text:
Q: Find the border patch where randomly moved particle hit I have a randomly blue drawn border and a ball which is placed inside border and should randomly move inside, when it hits a wall it should turn in opposite direction and continue. For that I`ve wrote a code
breed [ balls ball ]
ask balls
  [
    ifelse (pcolor = blue or [pcolor] of patch-at dx dy = blue)
    [
     rt 180
    ]
    [
      jump 0.4
    ]
  ]

This code seems to work, but now there is a need to create a flash when the ball hits a wall. I`ve tried the following code - with no success
breed [ flashes flash ]
flashes-own [ birthday ]

to apply-flash-visualization
  set size 2.5
  if (ticks - birthday > 0.4)  [ die ]
end

to go
  ask flashes [ apply-flash-visualization ]
  ask balls
  [
    ifelse (pcolor = blue or [pcolor] of patch-at dx dy = blue)
    [
     rt 180
      if (pcolor = blue)
      [
        let bounce-patch patch-here
        let new-px [ pxcor ] of bounce-patch
        let new-py [ pycor ] of bounce-patch
        ask patch new-px new-py [
          sprout 1 [
            set breed flashes
            set color gray - 2
            set birthday ticks
          ]
        ]
      ]
    ]
    [
      jump 0.4
    ]
  ]

How should the issue be solved?
Thanks

A: I think it's the if (pcolor = blue) line that's causing the problem. Your ball agents are never actually on a blue patch, since you have them turn around once they assess the patch ahead of them (using your patch-at dx dy line). So, if (pcolor = blue) never evaluates to true, so no flashes are ever made. This would be a good place for a print command for debugging- if you put something like:
...
     if (pcolor = blue)
      [
        print "making flash"
...

you'll see that that code is never actually evaluated. So to fix this, you have to re-evaluate when the flashes should actually occur- one simple example that might work for you:
breed [ flashes flash ]
breed [ balls ball ]

flashes-own [ birthday ]

to setup
  ca
  ask patches with [
    member? pxcor list max-pxcor min-pxcor or
    member? pycor list max-pycor min-pycor
  ] [
    set pcolor blue
  ]

  create-balls 10

  reset-ticks
end

to apply-flash-visualization
  set size size + 1
  if ticks - birthday > 2  [ die ]
end

to go
  ask flashes [ apply-flash-visualization ]
  ask balls [
    let next patch-ahead 1
    ifelse [pcolor] of next = blue [
      ask next [
        sprout-flashes 1 [
          set shape "square"
          set color white
          set birthday ticks
        ]
      ]
      rt 180
    ] [
      fd 1
    ]
  ]
  tick
end

Also, you may want to look at the "Bounce Example" model in the Models Library that shows how to make angled bouncing work.


text:
Q: Solve $\frac{11}{x(x-5)}+\frac6{x(x+4)}-\frac3{(x-4)(x-5)}=0$ How to solve this equation? I've tried adding it by taking LCM. I dont know what I'm doing wrong.
$$\frac{11}{x(x-5)}+\frac6{x(x+4)}-\frac3{(x-4)(x-5)}=0$$

A: First, whenever you solve an equation, you should find the domain.
$$x\neq0,5,4,-4$$
Taking LCM,
$$11(x+4)(x-4)+6(x-5)(x-4)-3x(x+4)=0$$
$$14x^2-66x-56=0$$
So the solutions are
$$x = \frac{33}{14} - \frac{\sqrt{1873}}{14}\approx5.448440715$$
$$x = \frac{33}{14} + \frac{\sqrt{1873}}{14}\approx-0.7341550012$$


text:
Q: Difference between «so that» and «such that» Are these the same?

The image will be sheared such that the x-axis goes through (1,1).
The image will be sheared so that the x-axis goes through (1,1).

I think I have usually seen the former, I didn't even know that "so that" is allowed in English until I once saw it in a text from a (as I assume) native English speaker.
Simon

A: The sentences, while very similar, do have a subtle difference of meaning.
"Such that" is a description of HOW something is to be done:

The image will be sheared such that the x-axis goes through (1,1). -> The image will be sheared in such a way that the x-axis goes through (1,1).

"So that" is a description of WHY something is to be done:

The image will be sheared so that the x-axis goes through (1,1) -> The image will be sheared in order for the x-axis to go through (1,1).  (Or, more obviously: Because the x-axis needs to pass through (1,1), the image will be sheared appropriately.)

A: I think that 'such that' should refer to a subject noun or pronoun. It is often stretched these days like in example 1, where it is lost upon the reader that it is the image that is such that... at least a comma after 'sheared' could help.
Still, it would be good style to avoid 'such that' without clear subject, just like 'so that' would not be appropriate without a verb.

A: I would say " The image will be sheared such that the x-axis goes through (1,1)" but, as indicated by Hellion, would keep the other construct to express some higher-level aim: " The image will be sheared so that it is clearer".

A: "Such that" is idiomatic mathematical jargon most often used in the definition of mathematical objects.  The usage in your example is a bit atypical.  The phrase is difficult to directly gloss, but one possible rendering for the phrase as it is used in definitions is "...for which it is true that..."
For example, if we define a rational number as "any p/q such that p and q are integers and q≠0," we've established that iff there are two integers that can be divided by one another to produce a given number, then that number is rational.
Your example is a bit different, because it isn't directly defining a mathematical object, but rather describing a transformation on a mathematical object. (Some branches of mathematics would allow you to define transformations as objects, but that isn't what's being done here.)
By contrast, the phrase "so that" is not mathematical jargon; it's a common-use phrase that indicates the intent or result of some action or condition. Consider the following examples:

*

*"I drank coffee so that I could stay awake."

*"I drank coffee such that I could stay awake."

These sentences are very different! The former sentence is saying that your reason for drinking coffee was to stay awake -- in order to stay awake, you drank coffee.  The latter sentence is describing the coffee, not your action of drinking the coffee, saying that it's coffee that you drank before a period of time when you were able stay awake, and suggesting that the coffee had something in it that kept you awake.
Note also that the meaning of the sentence changes yet again when a comma is added as follows:

*

*"I drank coffee, such that I could stay awake."

In this case, the phrase "such that" modifies the entire clause in a similar manner to "so that", except it describes the result of your action of drinking the coffee rather than your reason for drinking the coffee. For one reason or another, you drank coffee, and because you drank that coffee, you were able to stay awake. If you ever see the phrase "such that" used outside of mathematics, it will probably be used like this: following a clause, separated from that clause by a comma, and describing the result of whatever is happening in that clause.  Your example seems to be using the phrase in this sense, such that the sentence should probably have a comma between "sheared" and "such that".
In particular, this usage often connotes extent, i.e., that the preceding clause is true to an extent that results in whatever's going on in the following clause -- you drank enough coffee to stay awake. This connotation is especially strong if the preceding clause uses some word or phrase that itself describes extent, as in "I drank lots of coffee, such that I could stay awake."

A: This distinction criterion is very simple and always works: 'such that' expresses consequence, 'so that' purpose.


text:
Q: Accessing the value of a particular key in firebase using swift I have the following firebase structure.Firebase Structure
"Users" is the root, with the keys as "Uid". How do i access a particular value of a key for a given "Uid"?
Example: I want to retrieve "mobileno" of a particular user with "Uid" as M5j80aAlmCS3Jcbh0aA3T4Tfzxv1.

A: To get a user's profile information, use the properties of an instance of FIRUser. For example :
let user = Auth.auth().currentUser
if let user = user {
  // The user's ID, unique to the Firebase project.
  // Do NOT use this value to authenticate with your backend server,
  // if you have one. Use getTokenWithCompletion:completion: instead.
  let uid = user.uid
  let email = user.email
  let photoURL = user.photoURL
  // ...
}

Refer to the Firebase Documentation for more info on this.

A: If it is your uid (or the user's):
if let userUID = Auth.auth().currentUser?.uid{
    %firebaseReferenceVariable%.child("Users/\(userUID)").observeSingleEvent(of: .value, with: { snapshot in
        if snapshot.value is NSNull{
             //handles errors
             return
        }
        else{
             if let selectedUser = snapshot.value as? NSDictionary //OR [Stirng: Any]{
                 let mobileno = selectedUser["mobileno"] as! String
                 //Do something with mobileno
             }
        }

   })
}

You can replace the variable userUID with any string value in the firebase reference call and it will get that user - I would recommend (if you are trying to access these users from your app) to populate a tableView or collectionView (some type of list) with all the users. You can also get all the users and loop through ones you want (let's saying if you had a boolean variable to display this user).

A: Have a look at below code I had used Observe Block as I required to get data each time it was updated in a chat App . so you can make use of observe single event to get data and at end remove observer too.
   Database.database().reference().child("users").child(your Key value).observe(.value, with: { (snapshot) in

         if snapshot.exists(){

            print(snapshot)

            if let snapDict = snapshot.value as? [String:AnyObject] {

                //here you can get data as string , int or anyway you want
                self. mobilenoLabel.text = snapDict["mobileno"] as? String

            }

        }

    })


text:
Q: Inheritance and Generic Types i have a problem to create my code structure i don't now how to make it work
the problem in PlayListInfo<VerseTrack> ProgresList = new PlayListInfo<VerseTrack1>();
where it connot be converted
here is the code sample
public class PlayListInfo<_VerseTrack> : IPlayListInfo
    where _VerseTrack : VerseTrack
{
     public List<_VerseTrack> Tracks;
}

public class VerseTrack1: VerseTrack
{

}

public class VerseTrack2: VerseTrack
{

}

public class player
{
    PlayListInfo<VerseTrack> ProgresList;
}

public class player1:player
{
   PlayListInfo<VerseTrack> ProgresList = new PlayListInfo<VerseTrack1>();
}
public class player2:player
{
}

A: Generic types aren't inherited based on their type parameters. A PlayListInfo<QuranVerseTrack> is not a PlayListInfo<VerseTrack>
You could do:
PlayListInfo<VerseTrack1> ProgresList = new PlayListInfo<VerseTrack1>();

and then treat all of the items like a VerseTrack, but it's unclear if that's what you should do.
or you could do:
PlayListInfo<VerseTrack> ProgresList = new PlayListInfo<VerseTrack>();

and then add VerseTrack1 (or VerseTrack2) items to it (assuming it's a collection of some sort).
Side note:  player1.ProgresList is hiding the base property, not overriding it.

A: If you are using .NET 4.0 or higher, here's another workaround. I introduce you covariance and contravariance
Assuming A is convertible(implicit reference conversion is available) to B,
X is covariant if X<A> is convertible to X<B>

Since covariance and contravariance only work with interface, you need to modify IPlayListInfo like this:
public interface IPlayListInfo<out _VerseTrack>
  where _VerseTrack : VerseTrack
{
  // blah blah ...
}

And this might work!
public class player1:player
{
  // PlayListInfo<VerseTrack> ProgresList = new PlayListInfo<VerseTrack1>(); // old one
  IPlayListInfo<VerseTrack> ProgressList = new PlayListInfo<VerseTrack1>() as IPlayListInfo<VerseTrack1>;
}


text:
Q: Overwriting rails URL helper (form_for) I am trying to override a url helper that is being called from a form_for.
My controllers and models are all namespaced in the "Admin" module, and are resting in an admin folder. (So models/admin/foo.rb, controllers/admin/foo_controller.rb)
My routes are correct (I believe)
scope module: "admin" do
    resources :foos do
      resources :foo_details
    end
end

Here is some code to demonstrate what I am attempting to do and where I get the error:
<%= form_for(@foo) do |f| %>

I am getting an error on the form for line, with this: "undefined method `admin_foos_path' for #<#:0x007f08fd7ffb90>.
When I run 'rake routes', I have a route for foos, but not admin_foos.  I assume the form_for is trying to access admin_foos_path because of how the application was scaffolded.
Is there a way for me to override admin_foos_path to be foos_path or redirect it?  I have tried searching for this issue and haven't been able to come up with much.
Thanks in advance.

A: Use the namespace directive
namespace :admin do
  resources :foos do
    resources :foo_details
  end
end

Using scope just gives you foos_path, while namespace gives admin_foos_path which is needed for the @foo to work.

A:
undefined method `admin_foos_path' for

To explain the error, @foo is a model instance of Admin::Foo not Foo, so form_for by default look for its resourceful route which in your case it is admin_foos. And because it can't find it, so is the error.

Is there a way for me to override admin_foos_path to be foos_path or
  redirect it?

You can overwrite the URL of a form to your desired URL like below
<%= form_for(@foo, url: foos_path) do |f| %>

But I believe you need namespace instead of scope. I recommend to read about when to use scope and namespace in controller-namespaces-and-routing


text:
Q: Using magento2 Soap api in .NET I am trying to consume magento2 soap api in .NET C#, and can find that to consume sales api's we need to be authorize, i have the authorization token , but can anybody help me how we can add this in .net as service reference,
http://magento2url/soap/default?wsdl&services=salesOrderRepositoryV1
I am getting "consumer not authorize" as error.


text:
Q: Servlet jar not loaded Tomcat Issue I restarted tomcat today and the webapp is offline.
And when I referred catalina.out file I saw the following error.
Dec 27, 2012 6:38:21 AM org.apache.catalina.loader.WebappClassLoader validateJarFile
INFO: validateJarFile(/dun/stud01/webapps/WEB-INF/lib/servlet.jar) - jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

All this time before today the appliacation was working fine.
Its a Unix IBM-AIX server envirnment.
I dont know what went wrong all this time it was working fine.
Can anyone suggest how to bring back the website online.

A: Have you looked at the relevant chapter of the servlet spec? It says:

It must not allow the WAR to override J2SE or Java servlet API
  classes.

In other words, you should not be providing servlet.jar in your webapp as it is already shipped with Tomcat. Remove it from your .war and restart Tomcat.


text:
Q: Reading from a buffer word by word in c I have a Buffer received as a result of recvfrom(). lets say,

char buffer[12] = "Hello 1";

I want to separate Hello and 1 and store them in different buffers so that one buffer has "Hello" in it and other buffer or an int variable has "1" stored in it.
In other words I want to separate contents of a buffer on the basis of spaces. How can this be done?
I tried:
int number;
char buff[7];
sscanf (buffer,"%s %d",buff,number);

Will this approach work?

A: If there are only 2 words your idea will work. But there is a small error in your code.
Change the sscanf this way
sscanf (buffer,"%s %d",buff,&number);

A: This approach works but you need to change to change your sscanf to:
sscanf (buffer,"%s %d",buff,&number);

The %d expects an int* and you are sending an int.

A: Looks like you want strtok, it can do exactly that. But make sure your string is NULL-terminated, recv and other socket functions don't do that for you and the standard C string functions do expect NULL-termination.


text:
Q: JSF Primefaces form errors after failed validation I am new to JSF/Java in general but have been trying to solve this for a few days now.
I have a form which gets stuck on validation.  When all the entries are valid, it all works well.  The minute I break validation (such as don't provide a required value), then the form gets stuck.  One thing that happens is I cant correct the invalid entry it seems and repost.  Also, where I had a cascading ajax call of a selectOneMenu, that suddenly starts failing...even though this is not the invalidated part of the form.
I notice that the cascading drop down seems to be throwing null pointer exceptions in its overridden equals method.
I am at a loss.
<html xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://java.sun.com/jsf/html"
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:p="http://primefaces.org/ui"
    xmlns:ui="http://java.sun.com/jsf/facelets">
<ui:composition template="/templates/layout.xhtml">
    <ui:define name="content">
        <p:ajaxStatus onstart="statusDialog.show();" onsuccess="statusDialog.hide();"/>

        <p:dialog modal="true" widgetVar="statusDialog" header="Status"
                draggable="false" closable="false">
        <p:graphicImage value="/resources/images/ajaxloadingbar.gif" />
</p:dialog>
        <h:form id="form">
            <p:panel id="panel"
                header="Please ensure your personal details are accurate"
                style="margin-bottom:10px;">
                <p:messages id="msgs" />
                <h:outputText
                    value="Please ensure your personal details are up to date and accurate within the Admin Direct system. Please note that this application only supports GMD customers, so unless you are within GMD, or are a user of the GMD Admin Direct service, please do not enter your details or attempt to use the application for administrative support." />
                <h:panelGrid columns="3" cellpadding="5" id="grid">

                    <h:outputText value="First Name:" style="font-weight:bold" />
                    <p:inputText id="firstName"
                        value="#{personalDetailsBean.user.firstName}"
                        requiredMessage="First name is required..." style="width:250px" />
                    <p:message id="firstNameMessage" for="firstName" />

                    <h:outputText value="Last Name:" style="font-weight:bold" />
                    <p:inputText id="lastName"
                        value="#{personalDetailsBean.user.lastName}"
                        requiredMessage="Last name is required..." style="width:250px" />
                    <p:message id="lastNameMessage" for="lastName" />

                    <h:outputText value="Select Function:" style="font-weight:bold" />
                    <p:selectOneMenu id="functions"
                        value="#{personalDetailsBean.user.function}"
                        style="width:250px">
                        <f:selectItem itemLabel="Select Function" itemValue="" />
                        <f:selectItems value="#{personalDetailsBean.functions}" var="func"
                            itemLabel="#{func.functionName}" itemValue="#{func}" />
                        <f:converter converterId="functionConverter" />
                    </p:selectOneMenu>
                    <p:message id="functionMessage" for="functions" />

                    <h:outputText value="Select Site" style="font-weight:bold" />
                    <p:selectOneMenu id="sites"
                        value="#{personalDetailsBean.user.site}"
                        style="width:250px">
                        <f:selectItem itemLabel="Select Site" itemValue="" />
                        <f:selectItems value="#{personalDetailsBean.sites}" var="sit"
                            itemLabel="#{sit.siteName}" itemValue="#{sit}" />
                        <f:converter converterId="siteConverter" />
                        <p:ajax update="region" event="change" process="@this"/>
                    </p:selectOneMenu>
                    <p:message id="siteMessage" for="sites" />

                    <h:outputText value="Region" style="font-weight:bold" />
                    <h:outputText id="region"
                        value="#{personalDetailsBean.user.site.region.regionName}" />
                    <p:message id="regionMessage" for="region" />

                    <h:outputText value="Email" style="font-weight:bold" />
                    <p:inputText id="email" value="#{personalDetailsBean.user.email}"
                        required="true"
                        validatorMessage="Invalid email address format"
                        style="width:250px">
                    <f:validateRegex
                       pattern="[\w\.-]*[a-zA-Z0-9_]@[\w\.-]*[a-zA-Z0-9]\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]" />
                        <f:validateLength minimum="2" />
                    </p:inputText>
                    <p:message id="emailMessage" for="email" />
                </h:panelGrid>
                <p:separator />
                <p:commandButton value="Save" id="btnSubmit" actionListener="#{personalDetailsBean.saveUser}" process="@all" update="panel" />
            </p:panel>
        </h:form>
    </ui:define>
</ui:composition>
</html>

any advice greatly appreciated.
Regards
SM


text:
Q: Authentication between client-server and web applications I have two applications, one is a desktop client and the other is a web application which is optionally embedded into the desktop client. Both talk to separate servers with separate databases and separate user authentication mechanisms. The servers may communicate with each other.
I need to be able to log in to the desktop application and use the embedded web application without having to enter the web client's username/password.
The web app is developed at our side so major changes are possible (within reason). Architecture is .NET on Windows (IIS and SQL Server).
The desktop app is developed elsewhere so changes should be minimal; making http-requests and passing a token around is ok but creating a new authentication mechanism isn't. Architecture unknown, solution should be platform independent.
Can I use some sort of trust between the two servers to create a one time authentication token which the desktop client can pass to the web client to create a session?
Are there any existing implementations of this or another similar use case I could slot in? Note that internet connectivity must not be required, only access to the two servers is guaranteed.
If there aren't any easy/quick/free solutions, I was thinking something like this (D is desktop application, W is web application):

*

*User logs in to Client D and wants to open Client W

*Server D asks Server W for a token for a specific user

*Server W creates a new token, maps it internally to the requested username and returns the token

*Client D logs in to Client W using username and token

*Server W creates a new session and forgets the token so it cannot be used again

Traffic between servers would be over SSL/TLS, IP whitelisted, authenticated using a preconfigured passcode and includes a unique counter and timestamp to prevent replay attacks.
The desktop client would communicate to the web application by making a request to the server via the embedded browser. For authentication it would HTTPS POST the username and token to a login page.
Communication between clients and their representative servers is assumed to be secure.
Is there something I'm still missing?
Thanks.

A: I think the solution that is the least obtrusive will be best. I like the idea of modularized authentication that you can drop in new authentication methods easily. You simply have two active authentication modules.
Let's take a look at server D:

*

*User Name/Password authentication. You take user name and password and validate it (or hopefully its hash) against what's in the database and return a token. Requests with the returned token will be successful until the token expires.

*Peer authentication. You take the given session token from the request and submit it to Server W for validation. If Server W doesn't return 200 you should forbid access. This would also be a good opportunity to share session data.

It seems like you're already thinking down this path, but I would recommend that you don't have the servers ask each other for tokens. Instead have the servers ask each other for session data using the token that is valid for that server. If you log in with user/pass on Server D, have Server D give you a session token that is valid with Server D. Then when communicating with Server W, have Server W ask Server D if the given session token is valid. Server D can simply return yes/no or return all the public session data for the given token.
This solution has at least two benefits over the one you propose:

*

*You don't have to keep two tokens. You just store whichever token the last server you authenticated with user/pass gave you. This also enables you to deal with servers as if they used the same authentication which allows you more flexability in the future if you wish to change the auth method.

*Token expiration is more straightforward. You won't have mismatching expiration to deal with. Whenever your single token has expired you are no longer authenticated with either server.

What do you think? Make sense?
Btw, I think SSL protects against replay attacks.


text:
Q: Adding external dependencies to ant project (IDEA Android project) In the documentation to socket.io-java by nkzawa is mentioned that to add ant dependency should be used next snippet:

<dependency org="com.github.nkzawa" name="socket.io-client" rev="0.1.1-SNAPSHOT">
  <artifact name="socket.io-client" type="jar" />
</dependency>

In which file and how I should include it? How I should compile my application after that?

A: In order to manage dependency with ant you'll need to use Ivy
But I agree with Bart Kiers - switch to Gradle, especially as you're already using IDEA.

A: The socket.io-client documentation is misleading. ANT has an extension called ivy for performing dependency management, but it is not bundled by default.
Once setup you can list your project's dependencies in an ivy.xml file or within your build.xml using the cachepath task:
<ivy:cachepath pathid="compile.path">
   <dependency org="com.github.nkzawa" name="socket.io-client" rev="0.1.1" />
</ivy:cachepath>

I have included a more complete example below. It details how to configure your ANT build to automatically setup ivy.
I am not an android programmer, so not able to recommend the best build tool. What I can say is that adding dependency management to your build process is a very good idea. ANT pre-dates more modern tools like Maven and Gradle that have this feature baked in.
Example
build.xml
<project name="demo" default="build" xmlns:ivy="antlib:org.apache.ivy.ant">

    <!--
    ================
    Build properties
    ================
    -->
    <available classname="org.apache.ivy.Main" property="ivy.installed"/>

    <!--
    ===========
    Build setup
    ===========
    -->
    <target name="install-ivy" description="Install ivy" unless="ivy.installed">
        <mkdir dir="${user.home}/.ant/lib"/>
        <get dest="${user.home}/.ant/lib/ivy.jar" src="http://search.maven.org/remotecontent?filepath=org/apache/ivy/ivy/2.3.0/ivy-2.3.0.jar"/>
        <fail message="Ivy has been installed. Run the build again"/>
    </target>

    <target name="resolve" depends="install-ivy" description="Use ivy to resolve classpaths">
        <ivy:cachepath pathid="compile.path">
           <dependency org="com.github.nkzawa" name="socket.io-client" rev="0.1.1" />
        </ivy:cachepath>
    </target>

    <!--
    ===============
    Compile targets
    ===============
    -->
    <target name="build" depends="resolve" description="Project build logic goes here">
       <javac .... classpathref="compile.path">
       </javac>

       ...
    </target>

    <!--
    ===============
    Clean-up targets
    ===============
    -->
    <target name="clean" description="Cleanup build files">
        <delete dir="build"/>
    </target>

    <target name="clean-all" depends="clean" description="Additionally purge ivy cache">
        <ivy:cleancache/>
    </target>

</project>


text:
Q: Implement MATLAB listener which notifies that there is enough data in a matrix I am trying to implement a listener in my MATLAB DAQ program, which notifies, if enough data are available in my acquired data matrix (and then saves a backup etc).
I know that there is something similar existing in the Data Acquisition Toolbox with the event 'DataAvailable' and NotifyWhenDataAvailableExceeds (frequency, when the event is fired). Unfortunately my device is not supported by the toolbox and I set up a DAQ program by myself by using a timer and querying the instrument values with fprintf and fscanf (Instrument Control Toolbox).
For a first approach to implement this, I read the documentation (i.a. Events and Listeners Syntax) and tried to implement an example, where an empty matrix is expanded by a for loop and a listener is notifying, when there are e.g. 100 data points available. However, I failed completely, because I couldn't figure out, how to implement, how the listener "notifies" this. Is it even possible to create "own" events or can MATLAB only listen to already existing events given in the documentation?
I am not sure if I got the concept right and would be glad if someone would give me a quick overview, if and how it is possible, what I am trying to do.
Below you find a Code example. I am totally aware, that it can't work like this yet, but I hope it makes clear what I am trying to do:
%% Class definition

classdef DAQClass < handle
   properties
  DataMatrix %Does this make sense to put the matrix as property?

                %Maybe better as event data?
   end
   events
      EnoughData
   end
   methods %Does it make sense to put the condition when to notify, in a    method??
    %how can I access it for my listener
      function IfEnoughDataAvailable(obj,DataMatrix)
         if (length(DataMatrix)>100)
            notify(obj,'EnoughData');
         end
      end
   end
end

%% Add listener, run code to fill data matrix

DAQObject=DAQClass;
DAQObject.DataMatrix=[];
lh = addlistener(DAQObject,'EnoughData',@reactToEvent);

for k=1:1000
    DAQObject.DataMatrix(k)=k;

end

A: I'd implement it like this, using a property listener rather than a listener (notice that I've put DataMatrix to be SetObservable):
classdef DAQClass < handle
    properties (SetObservable)
        DataMatrix = []
    end
    properties (Access = private)
        DataMatrixListener
    end
    methods
        function obj = DAQClass
            obj.DataMatrixListener =...
                addlistener(obj, 'DataMatrix', 'PostSet', @obj.reactToEvent);
        end
        function reactToEvent(obj, ~, ~)
            if length(obj.DataMatrix)>100
                disp('Enough data available') % Do actual thing here
            end
        end
    end
end

Then you can run:
>> d = DAQClass
d =
  DAQClass with properties:

    DataMatrix: []
>> for i = 95:105
disp(i)
d.DataMatrix = 1:i;
end
    95
    96
    97
    98
    99
   100
   101
Enough data available
   102
Enough data available
   103
Enough data available
   104
Enough data available
   105
Enough data available

Note that the reactToEvent method does the length-checking itself, and reactToEvent is called whenever DataMatrix changes. So you might want to put some logic in there so that it's only called once, when DataMatrix increases beyond 100, rather than every time it's beyond 100 (e.g. it could process the content of DataMatrix and then reset DataMatrix to [], treating it like a buffer.


text:
Q: How can I add a comment for each flag, on separate lines, in a bash script? I want to write bash scripts that are as self-documentary as possible.
I had an idea that when I execute software with lots of flags, I wanted to split the command into multiple lines, and add a comment at the end of each line, telling what the flag does (info from a man page), like so:
bwa aln \
-n $n \ # -n max #diff (integer) or missing prob under 0.02 err rate (float) [0.04]
-o $o \ # -o maximum number or fraction of gap opens [1]
-e $e \ # -e maximum number of gap extensions, -1 for disabling long gaps [-1]
-i $i \ # -i do not put an indel within integer bp towards the ends [5]
-d $d \ # -d maximum occurrences for extending a long deletion [10]
-l $l \ # -l seed length [32]
-k $k \ # -k maximum differences in the seed [2]
-m $m \ # -m maximum entries in the queue [2000000]
-t $t \ # -t number of threads [1]
-M $M \ # -M mismatch penalty [3]
-O $O \ # -O gap open penalty [11]
-E $E \ # -E gap extension penalty [4]
-R $R \ # -R stop searching when there are >integer equally best hits [30]
-q $q \ # -q quality threshold for read trimming down to 35bp [0]
-f $f \ # -f file to write output to instead of stdout
-B $B \ # -B length of barcode
-L $L \ # -L log-scaled gap penalty for long deletions
-N $N \ # -N non-iterative mode: search for all n-difference hits (slooow)
-I $I \ # -I the input is in the Illumina 1.3+ FASTQ-like format
-b $b \ # -b the input read file is in the BAM format
-0 $0 \ # -0 use single-end reads only (effective with -b)
-1 $1 \ # -1 use the 1st read in a pair (effective with -b)
-2 $2 \ # -2 use the 2nd read in a pair (effective with -b)
-Y $Y \ # -Y filter Casava-filtered sequences
-prefix $prefix \ # -prefix Prefix
-inputfile $inputfile \ # -inputfile Input file (FastQ format)

The problem is that I can not have anything after the \ character (that tells bash that the command continues on next line), and neither can I have the "\" at the end of the line, because then it is treated as part of the comment.
Anybody knows a way to do this, or something similar?

A: I suggest using multiple lines to comment the code before the command. like
 # this command uses multiple parameters
 # it requires 4 parameters and none are optional with no defaults
 # parameters used :
 # -q              name of the file
 # -b              size to truncate
 # -n              new location
 # -r              recursive

A: You can evaluate comments before the slash, simply generating empty strings for comments which won't affect your script:
bwa aln \
-n $n `# -n max #diff (integer) or missing prob under 0.02 err rate (float) [0.04]` \
-o $o `# -o maximum number or fraction of gap opens [1]` \
....

A: One option is to construct your command in pieces so you don't have to worry about line continuation:
cmd='date'                # run the date program
cmd=${cmd}' -d 20130905'  #  for this date
cmd=${cmd}' +%s'          #  with output in this format
echo $cmd                 # review the command
eval $cmd                 # run the command

A: For me something like this works good enough.
Solution focused on building string by concatenation.
(Compare release build vs debug build)
#############################################################################
#### GRPC ########################################################## GRPC ###
#############################################################################
# GRPC - depends on protobuf (above)
#
# gRPC_BUILD_CODEGEN=ON - needed to build grpc_cpp_plugin
# ABSL_ENABLE_INSTALL=ON - needed to install Abseil
#
TYPE=RelWithDebInfo
INSTALL=${BUILD_DIR}/install-${TYPE}
BUILD=build-grpc-${TYPE}
echo "Building: $BUILD <-------------------------------------------------------"
(cd ${BUILD_DIR} && rm -rf $BUILD && mkdir -p $BUILD) || exit 1
(cd ${BUILD_DIR}/$BUILD && cmake ${DIR}/../grpc \
    -DgRPC_BUILD_TESTS=OFF \
    -DgRPC_BUILD_CODEGEN=ON \
    -DgRPC_BUILD_CSHARP_EXT=OFF \
    -DgRPC_INSTALL=ON \
    -DgRPC_PROTOBUF_PROVIDER=package \
    -DgRPC_SSL_PROVIDER=package \
    -DgRPC_ZLIB_PROVIDER=package \
    -DgRPC_BUILD_GRPC_CPP_PLUGIN=ON \
    -DgRPC_BUILD_GRPC_PYTHON_PLUGIN=ON \
    -DgRPC_BUILD_GRPC_CSHARP_PLUGIN=OFF \
    -DgRPC_BUILD_GRPC_NODE_PLUGIN=OFF \
    -DgRPC_BUILD_GRPC_OBJECTIVE_C_PLUGIN=OFF \
    -DgRPC_BUILD_GRPC_PHP_PLUGIN=OFF \
    -DgRPC_BUILD_GRPC_PHP_PLUGIN=OFF \
    -DgRPC_BUILD_GRPC_RUBY_PLUGIN=OFF \
    -DABSL_ENABLE_INSTALL=ON \
    -DBUILD_SHARED_LIBS=OFF \
    -DCMAKE_BUILD_TYPE=${TYPE} \
    -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_C_COMPILER=clang \
    -DCMAKE_INSTALL_PREFIX=${INSTALL}) || exit 1
(cd ${BUILD_DIR}/$BUILD && cmake --build . --target install -j $THREADS) || exit 1
(cd ${BUILD_DIR} && rm -rf $BUILD) # Cleanup
#############################################################################

#############################################################################
TYPE=Debug
INSTALL=${BUILD_DIR}/install-${TYPE}
BUILD=build-grpc-${TYPE}
echo "Building: $BUILD <-------------------------------------------------------"
(cd ${BUILD_DIR} && rm -rf $BUILD && mkdir -p $BUILD) || exit 1

GRPC_BUILD_FLAGS="                    -DgRPC_BUILD_TESTS=OFF"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_BUILD_CODEGEN=ON"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_BUILD_CSHARP_EXT=OFF"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_BUILD_CSHARP_EXT=OFF"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_INSTALL=ON"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DABSL_ENABLE_INSTALL=ON"                 # needed to install Abseil
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_PROTOBUF_PROVIDER=package"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_SSL_PROVIDER=package"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_ZLIB_PROVIDER=package"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_BUILD_GRPC_CPP_PLUGIN=ON"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_BUILD_GRPC_PYTHON_PLUGIN=ON"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_BUILD_GRPC_CSHARP_PLUGIN=OFF"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_BUILD_GRPC_NODE_PLUGIN=OFF"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_BUILD_GRPC_OBJECTIVE_C_PLUGIN=OFF"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_BUILD_GRPC_PHP_PLUGIN=OFF"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_BUILD_GRPC_PHP_PLUGIN=OFF"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DgRPC_BUILD_GRPC_RUBY_PLUGIN=OFF"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DBUILD_SHARED_LIBS=ON"
GRPC_BUILD_FLAGS="${GRPC_BUILD_FLAGS} -DCMAKE_BUILD_TYPE=${TYPE}"

(cd ${BUILD_DIR}/$BUILD && cmake ${DIR}/../grpc \
    ${GRPC_BUILD_FLAGS} \
    -DCMAKE_CXX_COMPILER=clang++ -DCMAKE_C_COMPILER=clang \
    -DCMAKE_INSTALL_PREFIX=${INSTALL}) || exit 1
(cd ${BUILD_DIR}/$BUILD && cmake --build . --target install -j $THREADS) || exit 1
(cd ${BUILD_DIR} && rm -rf $BUILD) # Cleanup
#############################################################################


text:
Q: "SyntaxError: Can't build lexer" plyplus I am doing a High Level Language, and I cannot understand why I get this error when trying to generate a lexer for it.
This is my code:
start : codigo;

codigo : funcion* home;

funcion : DEF ID PL (ID (',' ID)*)* PR LLL expresion LLR;

home : HOME PL PR LLL expresion+ graph LLR;

@expresionuno:
    variable
    | numero
    | expuno
    | expdos
    | funcioncall
    | parexpdos     ;

@expresiondos:
    condicional
    | parexp    ;

@expresion:
    expresionuno
    | expresiondos  ;

expresionlogica:
    expresionuno (EQ | NE | LT | LE | GT | GE) expresionuno
    | TRUE
    | FALSE     ;

condicional:
    IF PL expresionlogica PR LLL expresion LLR (ELSE LLL expresion LLR)?;

variable:
    ID;

numero:
    '(\+|-)?[0-9]+(\.[0-9]+)?';

parexp:
    PL expresion PR;

parexpdos:
    (ADD | SUB)? PL expresionuno PR;

expuno:
    expresionuno (ADD | SUB) expresionuno;

expdos:
    expresionuno (MUL | DIV | MOD | POW) expresionuno;

funcioncall:
    ID PL (expresion (',' expresion)*)* PR;

graph : ID PL funcioncall numero numero PR;

/**  * Lexer rules  *  * Here we define the tokens identified by the
lexer.  */

// COMENTARIOS ABRIR_COMENTARIO : '/\*'; CERRAR_COMENTARIO : '\*/';
COMENTARIO : ABRIR_COMENTARIO '.*?' CERRAR_COMENTARIO (%ignore);

// SIMBOLOS ARITMETICOS ADD     : '\+'; SUB     : '-'; MUL     : '\*';
DIV     : '/'; MOD     : '%'; POW     : '^';

// SIMBOLOS LOGICOS EQ      : '=='; NE      : '!='; LT      : '<'; LE
: '<='; GT      : '>'; GE      : '>=';

// TIPOS DE PARENTESIS PL      : '\('; PR      : '\)'; LLL     : '{';
LLR     : '}';

// NOMBRES ID ID: '[a-z]+'
    (%unless
        DEF: 'func';
        HOME    : 'home';
        IF      : 'if';
        ELSE    : 'else';
        TRUE    : 'true';
        FALSE   : 'false';
    );

WS : '[ \t\r\n]+' (%ignore);

And this is the output:
ERROR: Regular expression for rule 't_POW' matches empty string
Traceback (most recent call last):
  File ".\CompilatorMain.py", line 19, in <module>
    arbol = Grammar(gramatica, auto_filter_tokens=False).parse(inputCode)
  File "C:\ProgramData\Anaconda3\lib\site-packages\plyplus\plyplus.py", line 560, in __init__
    self._grammar = self._create_grammar(grammar, source, tab_filename, options)
  File "C:\ProgramData\Anaconda3\lib\site-packages\plyplus\plyplus.py", line 569, in _create_grammar
    return _Grammar(grammar_tree, source, tab_filename, options)
  File "C:\ProgramData\Anaconda3\lib\site-packages\plyplus\plyplus.py", line 674, in __init__
    self.engine.build_lexer()
  File "C:\ProgramData\Anaconda3\lib\site-packages\plyplus\engine_ply.py", line 94, in build_lexer
    self.lexer = lex.lex(module=self.callback, reflags=re.UNICODE)
  File "C:\ProgramData\Anaconda3\lib\site-packages\ply\lex.py", line 909, in lex
    raise SyntaxError("Can't build lexer")
SyntaxError: Can't build lexer


text:
Q: Button Not Displayed in Kivy I am learning Kivy, the button is not displayed in the Kivy Screen. I am unable to find the issue. My Python version is 3.5.3
from kivy.app import App
from kivy.uix.widget import Widget

class MainWidget(Widget):
    pass

class TheLabApp(App):
    pass

TheLabApp().run()

MainWidget:

<MainWidget>:
    Button:
        text: "Hello"
        size: "40dp", "40dp"
        pos: "100dp", "200dp"

A: *

*Make sure your .kv file starts with the prefix 'TheLab', from the Pong Game Tutorial:

COMMON ERROR: The name of the kv file, e.g. pong.kv, must match the name of the app, e.g. PongApp (the part before the App ending)

*Add the build method to your App class:
 class TheLabApp(App):
     def build(self):
         return MainWidget()

Edit: A full working example:
*main.py
    from kivy.app import App
    from kivy.uix.widget import Widget

    class MainWidget(Widget):
        pass

    class TheLabApp(App):
        def build(self):
            return MainWidget()

    TheLabApp().run()

*TheLab.kv
    <MainWidget>:
        Button:
            text: "Hello"
            size: "40dp", "40dp"
            pos: "100dp", "200dp"

A: Try to Put in FloatLayout:
from kivy.app import App
from kivy.uix.floatlayout import FloatLayout

class MainWidget(FloatLayout):
    pass

class TheLabApp(App):
    pass

TheLabApp().run()

A: for linux users the .kv file has to be in lowercase
if you name the class as
class TheLabApp(App):
then the .kv file has to be
thelab.kv
Atleast this worked for me


text:
Q: Call a python class from command line I have no python experience. I am trying to figure out how to trigger this part of some code from the command line. The issue I'm finding is that it looks like "UserAccount()" is an object and I'm not sure how to trigger that from the command line. So a) what is UserAccount? b) how do I call that from the command line with arguments?
        # Create a random use account
        randomInt = random.randint(1, 4294967295)
        accountId = "random_id+" + str(randomInt) + "@acme.com"
        randomInt = random.randint(1, 4294967295)
        password = "Random_password1_" + str(randomInt)
        primaryEmail = accountId

        userAccount = UserAccount()
        userAccount.accountId = accountId
        userAccount.password = password
        userAccount.primaryEmail = primaryEmail
        userAccount.firstName = "Random"
        userAccount.lastName = "User"
        userAccount.birthdayMonth = 5
        userAccount.birthdayDay = 31

        #userAccount.firstNamePhonetic = ""
        #userAccount.firstNameRomagi = ""
        #userAccount.middleName = ""
        #userAccount.middleNamePhonetic = ""
        #userAccount.middleNameRomagi = ""
        #userAccount.lastName = ""
        #userAccount.lastNamePhonetic = ""
        #userAccount.lastNameRomagi = ""
        #userAccount.companyName = ""
        #userAccount.securityQuestion = ""
        #userAccount.securityAnswer = ""
        #userAccount.locale = ""
        #userAccount.timeZone = ""
        #userAccount.allowUpdateNotification = False
        #userAccount.allowThirdPartyNotification = False

        # Assume for now that we're just creating a user account, not also requesting activate/deactivate
        # permissions by providing a pre-created OAuth client ID.
        oauthClientId = "";

        print("  Test creating an account: " + userAccount.accountId + ", password: " + userAccount.password + ", email: " + userAccount.primaryEmail)
        accessToken = client.createAccount(userAccount, oauthClientId)
        print("    Account created!")
        if accessToken:
            print("      Access token for account: " + accessToken)
        print()

A: A: UserAccount is probably a class. UserAccount() is calling the constructor of it. Note that the construction is made by calling it, not by a new Operator.
B: As @OMGtechy already stated, take a look at argparse. Here an example which might work for you:
import argparse
parser = argparse.ArgumentParser(description='UserAccount creator')

parser.add_argument('--id', '-i', required=True, help='Required. User Account Id')
parser.add_argument('--password', '-p', required=True, help="Required. User Account's Password.")
parser.add_argument('--email', '-e', required=True, help='Required. User Account E-Mail')
parser.add_argument('--firstname', '-f', required=True, help="Required. User Account's first name")
parser.add_argument('--lastname', '-l', required=True, help="Required. User Account's last name")
parser.add_argument('--birthdaymonth', '-m', required=True, help="Required. User Account's Birthday month")
parser.add_argument('--birthdayday', '-d', required=True, help="Required. User Account's Birthday day")

args = parser.parse_args()
userAccount = UserAccount()
userAccount.accountId = args.id
userAccount.password = args.password
userAccount.primaryEmail = args.email
userAccount.firstName = args.firstname
userAccount.lastName = args.lastname
userAccount.birthdayMonth = args.birthdaymonth
userAccount.birthdayDay = args.birthdayday

# Now rest, like normal

oauthClientId = "";

print("  Test creating an account: " + userAccount.accountId + ", password: " + userAccount.password + ", email: " + userAccount.primaryEmail)
accessToken = client.createAccount(userAccount, oauthClientId)
print("    Account created!")
if accessToken:
    print("      Access token for account: " + accessToken)
print()


text:
Q: automation login to a website does not lead to the same page without automation (selenium) I want to do some automation for a website using selenium and there is a login password to enter and when I automate the login it goes to one page, and when im not automating it goes to another(the right one)...the login info are identical and there is no explanation in the landing pages that will explain the behaviour...does anyone know if this means that the website added some security features that will detect automation?... I dont know even if its possible..will love to get help
this is what im doing:
driver.get("https://somewebsite")

val userNameTextFieldLocator: WebElement = driver.findElement(By.id("username"))
userNameTextFieldLocator.sendKeys("vvv")

val passwordTextFieldLocator: WebElement = driver.findElement(By.id("password"))
passwordTextFieldLocator.sendKeys("vvvv")

val pinNumLocator = driver.findElement(By.id("pinnumber"))
pinNumLocator.sendKeys("vvvv")

val logginButton: WebElement = driver.findElement(By.className("login_button"))
logginButton.click()

Then I see this security popup:

then to continue I go:
val alert: Alert = wait.until(ExpectedConditions.alertIsPresent())
    alert.accept()

A: before initialize the driver try to:
DesiredCapabilities cap = DesiredCapabilities.chrome();
cap.setCapability("chrome.switches", Arrays.asList("--ignore-certificate-errors"));

driver = new ChromeDriver(cap);

A: Get the header Text from the Window Popup or the New page.
Next have a if-else case , if you get the above mentioned error--
Refer to these
Handle Securtiy Warning pop-up in FireFox with Selenium IDE
How to Click a option in Security Warning dialog box using Selenium?
If not, do as usual.


text:
Q: Get variable from class to another class I'm having trouble getting the variable of class main to another class class members ... Ive tried using getter-setter but it only return me a null value, how can i fix it? here are my codes:
Main.java
public class Main extends JFrame{

 JTextField txt = new JTextField(10);
 String value;

    Main(){

        getContentPane().add(txt);

        this.value = txt.getText();

        setLayout(new FlowLayout());
        setSize(300,200);
        setVisible(true);

    }//constructor of main

    public String getValue(){

        return this.value;

    }//getValue

    public static void main(String args[]){
        new Main();
    }//psvm

}//class main

Members.java
public class Members extends JFrame{

    JLabel lbl = new JLabel("");

    Main main = new Main();

    Members(){

        getContentPane().add(lbl);

        main.setVisible(false);

        lbl.setText(main.getValue());

        setLayout(new FlowLayout());
        setSize(300,200);
        setVisible(true);

    }//constructor of main

    public static void main(String args[]){
        new Members();
    }//psvm

}//class members

A: In your scenario, you will get null value because value is being set in constructor
this.value = txt.getText();

Make sure that, you update the this.value whenever you update the textfield
JTextField txt = new JTextField(10);

Better way to addListener to txt
txt.getDocument().addDocumentListener(new DocumentListener() {
     public void changedUpdate(DocumentEvent e) {
    //update value
   }});

A: In the code of your Members-class there are two members named main which are one Main-class object and a main()-method.
According to the principle of OOP a class cannot have more than one member with a single name except in method overloading.
Change the name of the Main-class object from main to main1 or something else. Hope this will solve your problem.
Use the following code snippet-
public class Members extends JFrame{

    JLabel lbl = new JLabel("");

    Main main1 = new Main();

    Members(){

        getContentPane().add(lbl);

        main1.setVisible(false);

        lbl.setText(main1.getValue());

        setLayout(new FlowLayout());
        setSize(300,200);
        setVisible(true);

    }//constructor of main

    public static void main(String args[]){
        new Members();
    }//psvm

}//class members


text:
Q: Compare two videos using Image processing Hi i am new to image processing.I want to compare two videos using image processing.First type of video has effect(blur) in video.And second type is normal video. Using edge detection i want to compare two videos.So i want to use canny edge detection.Is there any guide to help to do this project.I want to extract some information in edge video.i thought using canny edge detection identify edge and extract information from it.

A: Adi has given good point, apart from that I would suggest you to see Canny Edge detector threshold values gives different result for better edge detection without bothering small differences in lighting and contrast, otherwise your result may differ.
For matching edges, see ECR.
Apart from that I would suggest you to add multiple methods for video matching to avoid high processing and false-positive. e.g. if you compare histogram(it is quite simple easy and fast) and if difference is very high, no need to compare edges(comparatively process intensive).

A: Edge detection is generally not invariant to blurring.
If you still want to use edge detection, then you might blur your un-blurred video, and then do the comparison. If the blur is strong, you should consider sub-sampling the frames (e.g. keep every 2nd row/col pixel) and do the edge-detection and comparison on the reduce frames. This will be faster and also give the edge-detection stronger edge to detect.


text:
Q: Spring OAuth2.0 : Spring Authorization Server 1.0 and Resource server in the same boot application I'm struggling to use the very same Spring Boot 3.0 application as both authentication server and resource server, but until now, I've not been able to make the whole thing working.
First, I defined a very simple RestController:
@RestController
@RequestMapping("api")
public class PublicAPI {

    @GetMapping("/apitest")
    public String test(Principal principal) {
        return " This is a test ==>";
    }
}

Then, essentially following the code found in a Sample project of Spring, I managed to setup my boot app as Spring Authorization Server. I'm able to use Postman to get the authentication token using Oauth2 flow: I'm redirected to Spring's standard login page, I log in with credentials, and I get the Token.
Problem is, if I try to GET http://localhost:9000/api/apitest` using provided token, I get a 401 response from Spring boot.
This is my Security Configuration:
@Bean
    @Order(1)
    public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http, CorsConfiguration configCors) throws Exception {
        OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
        http.getConfigurer(OAuth2AuthorizationServerConfigurer.class).oidc(Customizer.withDefaults());
        http
            .exceptionHandling((exceptions) -> exceptions
                .authenticationEntryPoint(
                    new LoginUrlAuthenticationEntryPoint("/login"))
            );
        http.cors().configurationSource(request -> configCors);
        return http.build();
    }

    @Bean
    @Order(2)
    SecurityFilterChain apiFilter(HttpSecurity http) throws Exception {
        http
            .securityMatcher("/api/**")
                .authorizeHttpRequests()
                    .requestMatchers("/api/**").authenticated()
                    .and()
            .oauth2ResourceServer()
                .jwt();
        return http.build();
    }

    @Bean
    @Order(3)
    public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http, CorsConfiguration configCors) throws Exception {
        http
            .securityMatcher("/oauth2/**", "/login")
            .authorizeHttpRequests()
                .requestMatchers("/login", "/oauth2/**")
                .authenticated()
                .and()
            .formLogin(Customizer.withDefaults());
        http.cors().configurationSource(request -> configCors);
        return http.build();
    }

    @Bean
    public CorsConfiguration corsConfiguration() throws Exception {
        CorsConfiguration configuration = new CorsConfiguration();
        configuration.setAllowCredentials(true);
        configuration.setAllowedOriginPatterns(List.of("*"));
        configuration.setAllowedMethods(List.of("*"));
        configuration.setAllowedHeaders(List.of("*"));
        return configuration;
    }

If I try to access another Spring API in a different Spring Boot application which uses the first one as Authentication Server I get no errors.
Pretty sure that there's something wrong my configuration... any hint will be greatly appreciated !

A: At the very end, it turned out that another filter has been configured:
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class LoopbackIpRedirectFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        if (request.getServerName().equals("localhost") && request.getHeader("host") != null) {
            UriComponents uri = UriComponentsBuilder.fromHttpRequest(new ServletServerHttpRequest(request))
                    .host("127.0.0.1").build();
            response.sendRedirect(uri.toUriString());
            return;
        }
        filterChain.doFilter(request, response);
    }

}

Removing the LoopbackIpRedirectFilter problem was fixed


text:
Q: ASP.NET MVC add-migration "project failed to build" I am trying to add a new model and its Data Annotations, when i tried to add the migration using Package Manager Console it show me

"The project ** project name** failed to build"

This is my model :
{
    public class Genre
    {
        [Required]
        [StringLength(255)]
        public string Name { get; set; }
    }
}```


text:
Q: Endomorphism ring of an abelian variety and its reduction mod $\mathfrak{p}$ Let $A$ be an abelian variety defined over a number field $K$. Let $\mathfrak{p}$ be a prime of $K$ for which $A$ has good reduction and let $k=\mathcal{O}_{K,\mathfrak{p}}/\mathfrak{p}$. Let $\mathcal{A}$ be a Neron model for $A$ over $\mathcal{O}_{K,\mathfrak{p}}$. Then I have seen it mentioned that the following composition is an injection:
$$\operatorname{End}_K(A)= \operatorname{End}_{\mathcal{O}_{K,\mathfrak{p}}} (A)\to \operatorname{End}_k(\mathcal{A}\otimes k).$$
I cannot however seem to prove this. It seems like it should be easy though. Any help or direction is appreciated.

A: One may assume that $A$ is simple over $K$. Then $\mathrm{End}_K(A)$ is a division ring. Since the morphism into $\mathrm{End}_k(A\otimes k)$ is not zero, the kernel is $0$.


text:
Q: Validate amp client id I want  to validate the amp-client-id I get from amp-pages, but I can't find a definition of its structure except of what is written here:
https://developers.google.com/analytics/devguides/collection/amp-analytics/client-id -
"If a Client ID is generated by an AMP page, the Client ID follows the AMP format (amp- followed by a randomly generated string)."
Does the client id has a length limitations?
What is the exact regex for it?
Thanks

A: There's no information about the length of the Client ID and the exact regex. Based from the documentation of Google Analytics, the unique identifier is a randomly generated string.

Fiel Name: clientId Value Type:text Default
  Value: Randomly Generated
Example value: 35009a79-1a05-49d7-b876-2b884d0f825b


text:
Q: APIs: Many minimal ones or a few bigger I'm currently working on a project/product which consists of ~60 REST APIs and one client (Web app)
I find many downsides on this design, and not so many benefits, and I'd like to know if this is clearly a bad practice from an architectural standpoint or just bad execution. (And if it can be improved without changing the design)
Pros:

*

*Deploy

*

*Deploying is very easy.

*If something fails, it might not be critical.

*Relation with data

*

*Each API is closely related with its "data model"

Cons:

*

*Memory.

*

*Each API serves its own http server, averaging at ~75mb idle.

*Most APIs also have at least 2 "workers" (RabbitMQ emitters/handlers) to interact with other systems.

*Expensive development

*

*Most APIs interact with each other, and even load client side code.

*Errors are hard to find, and easy to introduce.

*Some modules are used in every API, changing these might mean changing ~60 repos too.

*Lots of "boilerplate" repeated in most projects.

A: It sounds like bad execution. The memory/hardware con is not really a big deal, so I'm going to concentrate on the "Expensive Development" part.
Most APIs interact with each other, and even load client side code.
This seems like a red flag. Why are the APIs interacting with each other? Ideally they should be logically discrete. If there's a lot of cross-dependency, then it sounds like things have not been logically grouped correctly. Loading client side code is another red flag.
Errors are hard to find, and easy to introduce.
Do your services not have their own logging?
Some modules are used in every API, changing these might mean changing ~60 repos too.
You can introduce module versioning to solve this.
Lots of "boilerplate" repeated in most projects.
See if you can break them out into libraries


text:
Q: Serving a request from gunicorn Trying to setup a server on Rackspace.com.
Have done the following things:

*

*Installed Centos 6.3

*Installed Python 2.7

*Installed gunicorn using the "Quick Start" on their home page: gunicorn.org/
In the quick start, a "hello world" application seems to be initialized:
Create file "myapp.py":

(tutorial) $ vi myapp.py
(tutorial) $ cat myapp.py

Contents of "myapp.py"
def app(environ, start_response):
   data = "Hello, World!\n"
   start_response("200 OK", [
       ("Content-Type", "text/plain"),
       ("Content-Length", str(len(data)))
   ])
   return iter([data])

Since I know very little about servers, I do not know what to do next. I tried typing the server's IP address into the browser, but that seemed to result in a timeout.
I'm not sure if there is:

*

*something else that needs to be installed. Nginx is mentioned under "deploy" on the gunicorn website. Looks like Nginx is a proxy server which is confusing to me because I thought gunicorn was a server. Not sure why I need two servers?

*something that needs to be configured in gunicorn

*something that needs to be configured on the server itself

*something that else entirely that needs to be done in order to actually serve a request

What are the next steps?
Thanks so much!

A: Looks like you do not have a web application developed so far. So, I assume that your goal for now is to set up a development environment. For the time being, develop your web application using the development web server included in most frameworks, e.g. Flask.
Whatever framework you are using, make the development web server listen on 0.0.0.0 so that the service is listening on all configured network interfaces and make sure that the port is open to the outside (check the Rackspace settings).
When you are done developing your application or are looking into an existing one, you have to deploy it in a solid way. Then, gunicorn behind nginx is an option.
I will roughly go through your questions. It looks you have to read a bit more :-)

*

*
Nginx is mentioned under "deploy" on the gunicorn website. Looks like Nginx is a proxy server which is confusing to me because I thought gunicorn was a server. Not sure why I need two servers?
Nginx is a full-featured web server. It is appreciated for its performance and stability. People use it to serve static files (to not burden a dynamic web application with this task), to forward requests to web applications whenever necessary, for SSL-termination, and for load-balancing. Note that this is an incomplete picture.
gunicorn is a server for serving WSGI apps. Mainly, it manages worker processes that actually execute the web application.

*

*something that needs to be configured in gunicorn.
something that needs to be configured on the server itself.
something that else entirely that needs to be done in order to actually serve a request.
Actually, you can optimize your linux box in endless ways (for performance, e.g. increase the file descriptor limit and for security). Within gunicorn, you can configure the number of worker processes and a lot more. If you have nginx as frontend or even another load balancer, this one has its own configuration. You see, your setup might become very complex for actual deployment in a real-world scenario. This is not trivial.
However, for playing around with a WSGI application, just set up your development framework properly, which is very simple in most cases, and make sure that there are no firewall issues. That's all.

A: since gunicorn is a Web server on your case Nginx will act as a back proxy passing the an HTTP request from Nginx to gunicorn.
So, I will put here the steps to take for a simple Nginx and Gunicorn configuration running on the same machine.

*

*Starting with nginx configuration
Go to your /etc/nginx/nginx.conf and under the http{} make sure you have: include /etc/nginx/site-enabled/*;
http{
    # other configurations (...)
    include /etc/nginx/sites-enabled/*;
}

now, include a file on /etc/nginx/sites-enabled/mysite.conf where you will proxy your requests to your gunicorn app.
server {
    listen 80 default; # this means nginx will be
                       # listening requests on port 80 and
                       # this will be the default nginx server
    server_name localhost;

    # declare proxy params and values to forward to your gunicorn webserver
    proxy_pass_request_headers on;
    proxy_pass_request_body on;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_read_timeout 120s;

    location / {
        # here is where you declare that every request to /
        # should be proxy to 127.0.0.1:8000 (which is where
        # your gunicorn will be running on)
        proxy_pass_header Server;
        proxy_set_header Host $http_host;
        proxy_redirect off;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Scheme $scheme;
        proxy_connect_timeout 10;
        proxy_read_timeout 10;

        proxy_pass http://127.0.0.1:8000/; # the actual nginx directive to
                                           # forward the request
    }
}

Ok, at this point all you have is an Nginx acting as a proxy where all the requests going to  127.0.0.1:80 will be passed to 127.0.0.1:8000.

*

*Now is time to configure your Gunicorn webserver:

Usually the way I do I use a configuration file, Gunicorn config file can be an ordinary python file. So now, create a file at any location you like, I will assume this file will be /etc/gunicorn/mysite.py
workers = 3              # number of workers Gunicorn will spawn

bind = '127.0.0.1:8000'  # this is where you declare on which address your
                         # gunicorn app is running.
                         # Basically where Nginx will forward the request to

pidfile = '/var/run/gunicorn/mysite.pid' # create a simple pid file for gunicorn.

user = 'user'          # the user gunicorn will run on

daemon = True          # this is only to tell gunicorn to deamonize the server process

errorlog = '/var/log/gunicorn/error-mysite.log'    # error log

accesslog = '/var/log/gunicorn/access-mysite.log'  # access log

proc_name = 'gunicorn-mysite'            # the gunicorn process name

Ok, all set in configuration. Now all you have to do its to start the servers.
Starting the gunicorn and telling it which app to use and which config file.
from the command line and the folder where your myapp.py file is located run:
gunicorn -c /etc/gunicorn/mysite.py mysite:app

Now, only start nginx.
/etc/init.d/nginx start

or
service nginx start

Hope this helps.

A: looking at the quickstart guide, you probably should have run
(tutorial) $ ../bin/gunicorn -w 4 myapp:app

which should have produced a line that looks a bit like:
Listening at: http://127.0.0.1:8000

Among others.  see if you can access your site at that address.
Also Note that 127.0.0.1 is the loopback address; accessible only from that host itself.  To get gunicorn to bind to a different option, pass it --bind 0.0.0.0:80, as Jan-Philip suggests.
Since you mention rackspace, its possible that you may need to adjust the firewall settings to allow incoming connections to the desired ports.


text:
Q: How to dynamically change styling of a dynamic piece in react (using functional components)? TLDR- I want to change the backgroundColor of 1 square onClick. I am not sure how to differentiate this 1 square from the other 63 since they are created dynamically
I am dynamically creating a Board composed of 64 squares and I want a square's background color to change if selected under the proper conditions (preferably under the selectPiece function) and then revert back after a move is made or the piece on the square is unselected. My problem is identifying the dynamically created square to change its state.
Board.js
    let [squareStyle] = useState('squares ');

    function Row(i){
        const newRow = [];
        let count = i * 8;
        let squareImp;
        for (let j = 0; j<8; j++){
            if ((i + j) % 2 === 1){
                squareImp = squareStyle + "g";
            }else {
                squareImp = squareStyle + "y";
            }
                newRow.push(

                     { (props.data[count].name != null) &&

                    }

)
            count++;

        }
        return
{newRow}
;
    }

If I was using class based Components, then I could use this.setState to change the individual square, using something like -
this.setState({className: "squares b"})

but with Function Components, the setState is unique to each property. So while I can use the id (currently not used for CSS) to grab the selected square, I can't create a [state, setState] variable for each square. Is it possible to dynamically create a variable? aka something like
function setBackground(int id){
    let StateChange = id + ""
    setStateChange({backgroundColor:"blue"})

It doesn't seem to be.
So after I have spent quite a bit of time reading the multitudes of posts on here about how to dynamically change the CSS in React I tried following the only article that I thought might apply to me here- How to add a CSS class to an element on click - React and set the className with a function like so -
Board.js
    function Row(i){
        const newRow = [];
        let count = i * 8;
        for (let j = 0; j<8; j++){
                newRow.push(

                     { (props.data[count].name != null) &&

                    }

)
            count++;

        }
        return
{newRow}
;
    }
    //function getClassName(e, i, j){ //can't read e
    function getClassName(i, j){
        console.log(i, j)
        //console.log(e.currentTarget)
        let base = "squares ";
        if (clicked){
        // if (clicked && e.currentTarget.id == i * 10 + j){ //this is what I want but I can't figure out how to grab the target to compared the id to
                 return base + "b";
        } else {
             if ((i + j) % 2 === 1){
                 return base + "g";
             }else {
                 return base + "y";
             }
        }
    }

but as you can probably tell from the commented out text, I can't figure out how to grab the event and thus use the id to compare so that I am only changing the background color of the selected square rather than the whole board.
I don't understand the nuances of event handling but I am guessing that because I am calling the function from within the className attribute of the div element rather than from the element itself, that the event just isn't available. I am not sure how to get around it.
Any help would be appreciated

A: So this would be how I would do it. I abstracted Square to be its own component and it is being create via your for loop. Each of these Squares can manage their own local state so when they are clicked they can update their own state and you dont need to have messy centralized code.
FYI you seem to be using useState incorrectly as it does have its own function to update its local state. The below code is not 100% correct as Im not sure what you are doing, but it should give you a general outline.
I would also review the React docs: https://reactjs.org/docs/hooks-state.html
Just so you can get clear about the useState hook and how it can be utilized.

const { useState } from 'react'

const Square = (i, j, data, count, isMove, selectMove) => {
    const [ squareStyle, setSquareStyle ] = useState('square') // then use setSquareStyle('STYLING) to update local state
    const selectedPiece = data[count].name
    return (

        { (selectedPiece.name != null) &&

        }

    )
}

function Row(i){
    const newRow = [];
    let count = i * 8;
    for (let j = 0; j<8; j++){
            newRow.push(
                <Square
                    i={i}
                    j={j}
                    count={count}
                    isMove={isMove}
                    selectMove={selectMove}
                />
            )
        count++;

    }
    return
{newRow}
;
}
//function getClassName(e, i, j){ //can't read e
function getClassName(i, j){
    console.log(i, j)
    //console.log(e.currentTarget)
    let base = "squares ";
    if (clicked){
    // if (clicked && e.currentTarget.id == i * 10 + j){ //this is what I want but I can't figure out how to grab the target to compared the id to
             return base + "b";
    } else {
         if ((i + j) % 2 === 1){
             return base + "g";
         }else {
             return base + "y";
         }
    }
}


text:
Q: Network File Share access across multiple domains under the same forest My knowledge of Active Directory and network setup is limited. In the environment of this example, there are multiple domains under one forest. It has come up that users of Domain A have access to network file shares on Domain B, Domain C, etc.
What causes this cross domain access? I initially thought it was due to the 'Everyone' AD group being assigned access rights to various network shares, but there are instances of access where the 'Everyone' group is not present.
Ultimately, how would you go about securing file access so that Domain A does not have access to the network file shares of another Domain under the Forest? Any insight into what is causing this event or how to better secure access so that cross Domain file access is not possible would be highly appreciated.
Thanks.

A: It sounds like you are writing about domain trusts. With a Windows Active Directory Forest, Domain Trusts can be one way (Domain B trusts Domain A) or two way (Domain A and Domain B trust one another). The result of a one way trust is that accounts from the trusted domain can authenticate against the trusting domain's Domain Controller. You should check the NTFS permissions on the folder in question and see in which domain the user or group in the Access Control List exists.
This blog has some good information which you might find helpful.
https://blogs.msmvps.com/acefekay/2016/11/02/active-directory-trusts/
Here is Microsoft's documentation on trusts. https://docs.microsoft.com/en-us/previous-versions/windows/it-pro/windows-server-2008-R2-and-2008/cc731335(v=ws.11)


text:
Q: Is is possible to increase the maximum upload size on wordpress? Basicaly I'd like to find a way to increase the maximum upload size, I'm only talking about wordpress because it happens to be the platform Im working on but what I need is to find a way to go around php setting on the server as wordpress seems to use those setting as default.
Note that I'm only looking at uploading pictures, no other sort of files.
I have found several pages on google explaining either how to edit wordpress setting (in my case this is not something that would work), or changing the php setting on the server side, and I simply cannot do that.
I have thought of a few ways to reach this goal but don't know where to start as I'm not that good in picture processing. I was thinking about evaluating the picture size and dividing it into several files (is it something do-able in js ?), then upload them onto the server and assemble them from there in php (that I can do).
Can you tell me what you think about it ? I'm not asking anybody to do the work, i'm just looking for a hint or just for somebody to tell me where to start from in js or whatever other language I need to use on the front end.
Thanks a lot.

A: The restriction is at the server level.
You MUST adjust your server configuration in order to trickle down to WordPress.
If you set WordPress configuration to a max of 40MB, and Apache (or other web server software) still has a 2MB limit, you won't ever be able to post more than 2MB.
One option would be to use a Flash-based upload tool which can perform some pre-processing to downsize the image before uploading.
If you really want to get fancy, you could develop your own Flash-based upload tool to chunk uploads into 2MB parts (or whatever your server's maximum post size is) and some server-side script to re-assemble the pieces, just like the internet does with packets.

A: Yes, it is certainly possible to split a file via JS into chunks and to senk these ones individually.

*

*Declare a file input field:
<input type="file" id="input">

*Access the first file (there could be more if using the multiple attribute):
var selected_file = document.getElementById('input').files[0];

*You now have a File object which also inherits the Blob interface. You can therefore call Blob.slice in order to split the data into chunks.

*Upload those chunks via AJAX

*Combine the chunks again on the server side
Further readings:
https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications
https://developer.mozilla.org/en-US/docs/Web/API/File
https://developer.mozilla.org/en-US/docs/Web/API/Blob


text:
Q: Using awk, how to average numbers in column between two strings in a text file A text file containing multiple tabular delimited columns between strings with an example below.
Code 1 (3)
5     10      7      1      1
6     10      9      1      1
7     10     10      1      1
Code 2 (2)
9     11      3      1      3
10     8      5      2      1
Code 3 (1)
12    10      2      1      1
Code 4 (2)
14     8      1      1      3
15     8      7      5      1

I would like to average the numbers in the third column for each code block. The example below is what the output should look like.
8.67
4
2
4

Attempt 1
awk '$3~/^[[:digit:]]/ {i++; sum+=$3; print $3} $3!~/[[:digit:]]/ {print sum/i; sum=0;i=0}' in.txt

Returned fatal: division by zero attempted.
Attempt 2
awk -v OFS='\t' '/^Code/ { if (NR > 1) {i++; sum+=$3;} {print sum/i;}}' in.txt

Returned another division by zero error.
Attempt 3
awk -v OFS='\t' '/^Code/ { if (NR > 1) { print s/i; s=0; i=0; } else { s += $3; i += 1; }}' in.txt

Returned 1 value: 0.
Attempt 4
awk -v OFS='\t' '/^Code/ {
   if (NR > 1)
      i++
      print sum += $3/i
}
END {
   i++
   print sum += $3/i
}'

Returned:
0
0
0
0.3

I am not sure where that last number is coming from, but this has been the closest solution so far. I am getting a number for each block, but not the average.

A: Could you please try following.
awk '
/^Code/{
  if(value!=0 && value){
    print sum/value
  }
  sum=value=""
  next
}
{
  sum+=$NF;
  value++
}
END{
  if(value!=0 && value){
    print sum/value
  }
}
' Input_file


text:
Q: What is wrong with this JOIN statement in SQL? I am working on this tutorial about SQL. In Step 2 of 2, it is asked to use the JOIN command to link 2 people from the persons list using information from the friends list. I edited the provided code and obtained the code included below: the relevant part starts with select persons.fullname, persons2.fullname. However, the last paragraph of the code ('relevant code') does not yield any result nor error message. Am I doing something wrong?
Code
CREATE TABLE persons (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    fullname TEXT,
    age INTEGER);

INSERT INTO persons (fullname, age) VALUES ("Bobby McBobbyFace", "12");
INSERT INTO persons (fullname, age) VALUES ("Lucy BoBucie", "25");
INSERT INTO persons (fullname, age) VALUES ("Banana FoFanna", "14");
INSERT INTO persons (fullname, age) VALUES ("Shish Kabob", "20");
INSERT INTO persons (fullname, age) VALUES ("Fluffy Sparkles", "8");

CREATE table hobbies (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    person_id INTEGER,
    name TEXT);

INSERT INTO hobbies (person_id, name) VALUES (1, "drawing");
INSERT INTO hobbies (person_id, name) VALUES (1, "coding");
INSERT INTO hobbies (person_id, name) VALUES (2, "dancing");
INSERT INTO hobbies (person_id, name) VALUES (2, "coding");
INSERT INTO hobbies (person_id, name) VALUES (3, "skating");
INSERT INTO hobbies (person_id, name) VALUES (3, "rowing");
INSERT INTO hobbies (person_id, name) VALUES (3, "drawing");
INSERT INTO hobbies (person_id, name) VALUES (4, "coding");
INSERT INTO hobbies (person_id, name) VALUES (4, "dilly-dallying");
INSERT INTO hobbies (person_id, name) VALUES (4, "meowing");

CREATE table friends (
    id INTEGER PRIMARY KEY AUTOINCREMENT,
    person1_id INTEGER,
    person2_id INTEGER);

INSERT INTO friends (person1_id, person2_id)
    VALUES (1, 4);
INSERT INTO friends (person1_id, person2_id)
    VALUES (2, 3);

/* personal contribution starts here

select persons.fullname,hobbies.name
    from persons
    join hobbies
    on hobbies.person_id=persons.id;

/* select persons.fullname, persons2.fullname
    from persons
    join persons persons2
    join friends
    on persons.fullname=friends.person1_id and persons2.fullname=friends.person2_id; */

/* relevant code: */
select persons.fullname, persons2.fullname
    from persons
    join friends
    on persons.fullname=friends.person1_id
    join persons persons2
    on persons2.fullname=friends.person2_id;

[tutorial (c) khanacademy.org]

A: join friends
on persons.fullname=friends.person1_id

You're only including friends whose person1_id equals a person's fullname. Since person1_id is an integer and fullname is text, those will never be equal. You probably want:
select persons.fullname, persons2.fullname
from persons
join friends
on persons.id=friends.person1_id
join persons persons2
on persons2.id=friends.person2_id;


text:
Q: Windows Server 2008 R2 Hyper-V guest (sometimes) does not get enough dynamic memory I have a Windows Server 2008 R2 Hyper-V guest (the host is Windows Server 2016) which sometimes (for example, right now) fails to get more memory even though

*

*dynamic memory is enabled,

*plenty of memory is available on the host, and

*the guest requires more memory.

Ad 1:

Ad 2:

Ad 3:

As soon as I manually restart the guest, dynamic memory allocation works properly again (until it stops working properly again).
I have found the following similar questions and resources, but they only apply to other operating system versions:

*

*Hyper-V dynamic memory not correctly assigning more memory (applies only to Windows Server 2012/2012R2)

*Hotfix: Hyper-V Dynamic Memory does not work on a Windows Server 2008 Standard Edition or Windows Web Server 2008 virtual machine (VM) (applies only to Windows Server 2008)

Is this a known issue? If yes, what can I do to fix it?
Note: Since the problem only occurs sporadically, I won't be able to give timely feedback on "Try this: ..." answers.


text:
Q: Delete[] is not calling elements destructors I've started to implement a dictionary using a trie. Basically, i have a root node which has a definition (pointer to T that represents de value associated to the key) and childs (pointer to array that contains pointers to 256 nodes, one for each letter). check the definitions out:
template<typename T>
class DiccString {
        public:
                DiccString() : root(NULL);
                DiccString(const DiccString<T>&);
                ~DiccString() {delete root;}

                void define(const string& key, const T& value);
                bool isDefined(const string& key) const;
                const T& getDefinition(const string& key) const;
                T& getDefinition(const string& key);
                void remove(const string& key);
                const Set<string>& keys() const;

        private:

                struct Node{
                    Node** childs;
                    T* definition;
                    Node(){
                        std::cout << "Node has been created " << this << std::endl;
                        childs = new Node*[256];
                        definition = NULL;
                    }
                    ~Node(){
                        std::cout << "Node has been deleted " << this << std::endl;
                        delete definition;
                        delete [] childs;
                    }
                };

                Node* root;
};

So if i want to store "John" with the value 14 (T would be int so), assuming there is no other key, then i would create a root, then at root->childs[(int)'j'] i would create another node "nodeJ", and then nodeJ->childs[(int)'o'], and so on until reaching the last node "nodeN", which will contain the value (nodeN->definition = 14).
The problem is when i do:
int main() {
    DiccString<int> d;
    d.define("john",20);
    d.define("jane",25);

    return 0;
}

Then i expect all nodes created to be destroyed but take a look at the output:
Node created 0x61fc20 // root
Node created 0x620860 // for letter 'j'
Node created 0x621090 // for letter 'o' (child of 'j' 0x620860)
Node created 0x6218c0 // for letter 'h' (child of 'o' 0x621090)
Node created 0x6220f0 // for letter 'n' (child of 'h' 0x6218c0), value: 20
Node created 0x622990 // for letter 'a' (child of 'j' 0x620860)
Node created 0x6231c0 // for letter 'n' (child of 'a' 0x622990)
Node created 0x6239f0 // for letter 'e' (child of 'n' 0x6231c0), value: 25
Node deleted 0x61fc20 // root

Just the root is being deleted. So apparently when it comes to execute delete [] childs in the destructor of Node, it's not deleting all the elements of the array, which i'm sure that exist: for instance, in the case of the call to the destructor of root (which is the only one actually being called), i evaluated childs[(int)'j'] and it's certainly 0x620860, so i know it should call the destructor of this element (at least) when it executes delete [] childs, right?
What i am doing wrong?

A: childs has type Node**, it is a pointer to a pointer. You allocate for it an array of Node* pointers.
delete[] childs deletes this allocation, i.e. only the memory for the pointers, not the objects the pointers point to.
We don't see the code where you actually allocate Nodes, but you must store somewhere somehow which of the 256 allocated Node* actually point to a valid Node object. Maybe you do it via marking the pointers with a NULL pointer? In that case you probably want to do something like:
for(int i=0; i<256; ++i) {
    delete childs[i];
}

I should also note, that you should use a static array if the number of Node pointers is fixed and an std::vector otherwise.

A: The printout only occurs for destruction of Node objects but not Node *.  You can check that the behavior is correct by using a debugger.
Note that instead of lazily allocating in define() it might be clearer if you had symmetry among the constructor/destructor.  Also be sure to handle correctly the case when DiccString is empty when deallocated.


text:
Q: Using the Tensorflow Dataset map function to retrieve multiple sentences for a single image I am trying to implement the Neural Image Caption generator with visual attention proposed in the "Show, Attend and Tell" paper. For validation, I want to compute the Bleu score. For this, I need to get all the captions for a particular image. I thought of approaching the problem as shown below:
data_path = './processed_data'
split_type = 'val'
encoded_captions = np.load(data_path + '/{}/captions_{}.npy'.format(split_type, split_type))
image_paths = json.load(open(data_path + '/{}/img_paths_{}.json'.format(split_type, split_type), 'r'))

encoded_captions, image_paths = shuffle(encoded_captions, image_paths, random_state=0)

dataset = tf.data.Dataset.from_tensor_slices((image_paths, encoded_captions))

dataset = dataset.map(lambda img_path, cap: map_func(img_path, cap, image_paths, encoded_captions))

def map_func(img_path, caption, image_paths, encoded_captions):
    matching_captions = [caption for i, caption in enumerate(encoded_captions) if image_paths[i] == img_path]
    img = tf.io.read_file(img_path)
    img = tf.image.decode_jpeg(img, channels=3)
    img = tf.image.resize(img, (299, 299))
    img = tf.keras.applications.inception_v3.preprocess_input(img)

    return img, caption, matching_captions

When running the above code, I am getting the following error:
OperatorNotAllowedInGraphError: using a tf.Tensor as a Python bool is not allowed in Graph execution. Use Eager execution or decorate this function with @tf.function.
How do I resolve this issue? Alternatively, is there a more efficient way of getting captions that map to a particular image?
Thank you very much!


text:
Q: I need help on awk AWK related help needed in one query
csv having this column
m1|1|0|1
m1|2|1|1
m1|3|1|1
m2|1|0|1
m2|2|0|1
m2|1|1|1
m3|1|0|1
m3|2|1|1

Desire Out put
tag|total_count|no1_repetead_in b column|no2_repeated_in b column |no3_repeated_in b column|count_of_c_column|count_of_d_column
m1|3|1|1|1|2|3
m2|3|2|1|0|1|3
m3|2|1|1|0|1|2

can any one help in awk
awk -F '|' '{c[$1]++;a[$1]+=$3;b[$1]+=$4;d[$1]+=if($2=="1")}END{for(i in a)print i"|"c[i]"|"a[i]"|"b[i]"|"d[i]|"sort"}'  /tmp/csv.txt >> desire_output.txt

A: $ awk 'BEGIN {FS=OFS="|"}
             {k=$1; c[k]++; c2[k,$2]++; c3[k]+=($3==1); c4[k]+=($4==1)}
       END   {for(k in c)
                print k,c[k],c2[k,1]+0,c2[k,2]+0,c2[k,3]+0,c3[k],c4[k]}' file

m1|3|1|1|1|2|3
m2|3|2|1|0|1|3
m3|2|1|1|0|1|2

counts only "1"s in the 3rd and 4th columns

A: Based on your column names and your desired output, you can try this:
awk 'BEGIN{FS=OFS="|"}{c[$1]++;a[$1]+=$3;b[$1]+=$4}$2=="1"{d[$1]++}$2=="2"{e[$1]++}$2=="3"{f[$1]++}END{for(i in a)print i,c[i],d[i]+0,e[i]+0,f[i]+0,a[i]+0,b[i]+0}' csv.txt

Or just for better reading:
awk 'BEGIN{FS=OFS="|"}
{c[$1]++;a[$1]+=$3;b[$1]+=$4}
$2=="1"{d[$1]++}
$2=="2"{e[$1]++}
$2=="3"{f[$1]++}
END{for(i in a)
print i,c[i],d[i]+0,e[i]+0,f[i]+0,a[i]+0,b[i]+0}
' csv.txt

It's based on your own code, fixed the errors.


text:
Q: Javascript - How to get number of characters in textbox and use substring to delete I want to get the number of characters in a textbox and use substring to remove characters if the number of characters is >= 255
I have the following javascript:

What javascript should I use?

A: Try this.
   function CheckMaxLength(Object, MaxLen)
    {
        if (Object.value.length >= MaxLen) { //find textbox and use substring }

        return Object.value.substring(0, 255);
    }

If you want to handle this on keypress, paste, focus etc then try this.
   var MaxLen = 255;
   $('textboxSelector').bind('keypress focus blur paste', function () {
        if (this.value.length > MaxLen) {
            this.value = this.value.substring(0, MaxLen);
            return false;
        }
    });

A: The following script attaches a keyuyp event to an input control and prevents the user from entering data that is great than 255 characters in length. This is, most likely, a better solution in that the user won't see his text magically disappear when he blurs away...
document.getElementbyId('<%= MyControl.ClientID %>').onkeyup(function(){
    if(this.value.length > 255) return false;
});

A: var string = someString.substring(0, 255) will simply return up to 255 characters with no need to actually test the string for length. So why not:

A: Use this code, it will done the job perfectly:

<form name=myform action="YOUR-SCRIPT.CGI">
 ( You may enter up to 1024 characters. )

<textarea name=message wrap=physical cols=28 rows=4 onKeyDown="textCounter(message,remLen,1024);" onKeyUp="textCounter(message,remLen,1024);"></textarea>

<input readonly type=text name=remLen size=3 maxlength=3 value="1024"> characters left
</form>


text:
Q: How To connect Local Database in j2me How can I connect my local database in my application? I have a database which contains a book. I have to display it in my application in J2ME

A: Basically, in JME, an app can create a database which is a file stored in the RMS. Actually, there are several APIs that can help you in creating a Java ME database: Is there any option for local database like Sqlite for j2me - CLDC devices?
Anyway, I think the data in a sqlite database is not easily accessible to a JME app. It is not impossible but it, maybe, is complicated. Honestly, I don't know anyway to do it.

A: You have to create a server application where you access to database. Also your J2ME has to communicate with your server application for getting Data you want to display (Use HttpConnection Class).

A: In Mobile Application, you can not directly make connection with local or remote database. To Make Connection with Database , you need a middle tier called a web service. You can create web service in any platform  like Java-Servlet, .net or in PHP. See this is a very simple example to work with MySql Database.


text:
Q: Cypher IF A AND NOT(B) in match I want to write a cypher clause that says (I know this is not correct syntax, its just an example to show the general idea):
IF (S1)-->(B1{attr:TRUE})-->(G) AND NOT((S2)-->(B2{attr:FALSE})-->(G))
THEN stuff

So, if I have only the node B1 with attr=TRUE I want the pattern to match. If I have B1 with attr=TRUE and also B2 with attr=FALSE I want the pattern not to match. In all other cases where at least B1 with attr=TRUE is found, the mattern should match also.
But I cannot figure out how to implement this logic.

A: Here is an example of how to do that:
MATCH (S1)-->(B1{attr:TRUE})-->(G)
WHERE NOT ()-->({attr:FALSE})-->(G)
... stuff ...

Or, if stuff needs to use the B2 nodes:
MATCH (S1)-->(B1{attr:TRUE})-->(G), (B2{attr:FALSE})
WHERE NOT ()-->(B2)-->(G)
... stuff ...

This should give you an idea of how to start. It all depends on what data your stuff needs to use, and how much you want to specify about the S and B nodes.