text:
Q: What is the role of websocket in webRTC? I built the server into Java,The server sends (image)data to the web browser through a web socket.So far it works fine.
and I wand that The web browser  send data from the server to another web browser (client) using webRTC, So I looked for the webrtc...
I noticed that there are occasions when you need to use webSocket with webRTC
What is the role of websocket in webRTC?

A: In order to establish a WebRTC connection between two browsers, these browsers will have to negotiate a connection first. To negotiate a connection they need to be able to talk to each other. But they cannot talk to each other because they have not established a connection yet.
That's where a signalling server comes in. That's a server that both peers are already connected to and which can relay messages between them until they have established a connection. Using a websocket connection for this purpose is the most useful way, since it's a (soft) realtime bi-direction communication channel, exactly what you want when relaying messages as quickly as possible.
It doesn't have to be a websocket though; AJAX and/or long-polling will do too, but they have more overhead and are slower, which means it will take longer to negotiate the WebRTC connection.


text:
Q: How to do programming after jailbreaking my iPhone? I need some private frameworks for my app, so I am planning on jailbreaking my iPhone but, I wonder what are the steps for programming after the jailbreaking process.
Are they the same for jailbroken and normal iPhones?
I know that my app will be rejected by the app store, but that is not my goal now.
This is a research thing.
Thanks.

A: Once you have jailbroken your device, open the Cydia Installer and look on the start page. There will be many infos on how to create programs and on how to use the jailbreak-toolchain.
The programming steps are a bit different for jailbroken phones.

A: Yes, you can use XCode, here are some guidelines as to what you should do.

A: You can use private frameworks without jailbreaking.  However I'd agree that it's much easier to find them in the first place.  :)
Everything is the same for development -- using XCode will work just fine.  It's a good place to get started.
The unofficial SDK would work as well but you'll have to go through a lot more hoops to get it set up so I wouldn't recommend it.  Besides all the books and help really support the official development stack.
The main reason you're probably wanting to jailbreak is so that you can copy your test binary to your personal device for real world testing.

A: You can build using Xcode if you wish, but you don't need to. Infact you can build on your iphone itself. All you need is to remote login to your iphone and work from there directly!
If you want to go the "open" path of iphone development (ie: not SDK), then get yourself a copy of  this book. However you can still use Xcode if you wish.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Liouville's theorem and gravitationally deflected lightpaths It is customary in gravitational lensing problems, to project both the background source and the deflecting mass (e.g. a background quasar, and a foreground galaxy acting as a lens) in a plane.
Then, the lensing problem can be regarded as a mapping between the unlensed source plane, and the lensed image plane. In such transformations, the Jacobian evaluated at a point of the source plane, expresses how an infinitesimal area located around that point increases.
Lens mass and mass distribution, relative positions and distances involved give rise to different scenarios. The special case in which the distortions are too small to be resolved by telescopes, is called microlensing regime. Typically, a dark, unseen object like a floating planet, happens to cross transversally in front of a background star.
The image of the background star suffers amplification and distortions that are unresolved, but a change in brightness is detected, with a very typical light curve shape. The measured light curve of a microlensing event can be related to physical parameters of the problem, because the change in brightness of a lensed image can be modelled simply by dividing the area of the lensed image by that of the unlensed source image. If that can be done, it is because the mean surface flux of the image equals that of the source.
That is, gravitational lensing can make a tiny source appear bigger in the sky but in plain terms, every square inch of the image has the same brightness of every square inch of the source. Here comes my question, because that seems to me rather counter-intuitive and, when I try to find a rigorous justification to it, I find the same arcane sentence in each book, in each review, in each paper I have seen:

'Because of Liouville's theorem, gravitational lensing conserves surface brightness'

(... and therefore the magnification is found by dividing the subtended area of the image by that of the source). Every single author I have read, drops that sentence as if it were something very obvious, and quickly goes into other questions.
I have tried to trace-back the origin of the idea, by consulting the bibliography of every book or document in which that thing is stated. Interestingly, I have recognized sort of a fingerprint of obscure points like this one, a patter that is repeated in many of the documents, as if some authors didn't understand and merely copied from each other, developing and personalizing only the parts they understand in between.
I have rigorously developed and resolved every one of the dark points in that pattern, but this one remains unresolved. Is it perhaps something obvious? How is Liouville's theorem applied to photons along null geodesics? I will accept an appropiate link or paper reference as a good answer.

A: This question is pretty old but I figured other people than OP might be interested in the answer. I had the exact same question, so I asked my advisor and he told me that the answer can be found in two places. First (and unsurprisingly), there's a full derivation in Misner, Thorne and Wheeler, particularly on sections 22.5 and 22.6. There's also an attempt at a more intuitive explanation in Schutz's Gravity from the Ground Up, a very interesting book which attempts to explain GR with only high school math. I'm not actually sure if the explanation given there makes sense, but it has helped me arrive at one that does.
If I had to summarize the whole thing, I'd say that the conservation of surface brightness (or specific intensity, or étendue, or...) is the result of an exchange between position space volume and momentum space volume, or between solid angle and area.

I won't reproduce all the math because it can be found in MTW, but the basic idea is as follows. The first important fact is that you can think of light propagation as a bunch of "classical" photons moving along null geodesics, and the number of photons is conserved.
This photon picture allows you to use kinetic theory, as developed in section 22.6 of MTW, where Liouville's theorem is derived: given a bunch of $N$ particles, the volume $\mathcal{V}$ in phase space occupied by them, given by the product $\mathcal{V} = \mathcal{V}_x \mathcal{V}_p$ of the volume in 3-space and in momentum space as measured by a locally inertial observer, is Lorentz invariant and constant along the world line. Therefore, the number density $\mathcal{N} = N/\mathcal{V}$ is constant as well. I won't go through the proof since it is much easier to just look at the pictures in MTW, but this is the key step which has all the counterintuitive consequences.
The last step is relating the number density to the specific intensity or surface brightness $I_\nu$, the amount of energy per unit time, area of detector, frequency, and solid angle of the photons' momenta. This is a pretty standard derivation, and it makes sense. The result is that $\mathcal{N} = h^{-4} I_\nu/\nu^3$.
The frequency can change in crazy ways along the geodesic, but as long as there's no cosmological redshift between the source and the observer the net change will be zero, so for our purposes $I_\nu$ is constant, which is the result we needed. A given piece of solid angle from the observer's perspective receives the same flux no matter if there's a lens in the way or not.

As you've noticed, this has fairly counterintuitive consequences. From conservation of energy you would (wrongly) expect a bigger image to be dimmer, because a given solid angle of observation covers less of the lensed image than of the unlensed image. But the image also appears closer, so it's also brighter. Or, to put it in more careful terms, given a point on the source, light from a larger solid angle will reach the observer than if there were no lens (hope this sentence makes sense!). Conservation of phase space volume guarantees that these two effects exactly cancel each other out.
If anyone is interested in thinking through this, I have some advice. You must be careful when drawing 2D pictures, because using solid angles is essential: it can happen that images get compressed in one direction and stretched in the other, so in a 2D diagram the image would look smaller while it's actually larger. Also, you have to consider light rays emanating in a given solid angle from a point on the source as well as light rays emanating from an area on the source which converge on a point at the observer with some solid angle. This is the tradeoff between solid angle and area I mentioned earlier.

A: What they're referring to is a property of light from geometrical optics. The conserved property is "entendue" (see wikipedia article), and the constancy of brightness can be demonstrated in a bunch of ways (Hamiltonian optics i.e. Liouville's theorem, second law of thermodynamics as above, etc.).

A: This is just the second law of thermodynamics.
Suppose you have some big source black body and some little target black body. You build a whole bunch of geometric optics to focus light from the source to the target (e.g. mirrors behind the target and lenses in front of it). Eventually an observer standing on the target looks up and sees light from the source at every point in the sky.
All this incoming light heats the target blackbody up until it's radiating light away as fast as it's coming in. That means the target comes up to the same temperature as the source. If you could increase the flux per unit solid angle, the target would get hotter than the source, breaking the second law.
Is this enough, or did you want a technical analysis of the lensing equation?


text:
Q: Query empty XML elements with attributes using apache commons configuration xpath I'm using the apache commons configuration XMLConfiguration object with the XPATH expression engine to query an XML file. I am new to xpath and apache commons and am having trouble with the syntax.
The xml file looks like:
<attrs>
    <attr name="my_name" val="the_val"/>
    <attr name="my_name2" val="the_val2"/>
</attrs>

What I want to do basically is with commons loop through all the attributes and read name and val at each line. The only way I could work out to grab everything is to query the xml again with the value of name. This sort of feels wrong to me, is there a better way to do it?
List<String> names = config.getList("attrs/attr/@name");
for( String name : names )
{
    String val = config.getString("attrs/attr[@name='" +name +"']/@val" );
    System.out.println("name:" +name +"   VAL:" +val);
}

Also the conversion up top to String, I'm not sure the proper way to deal with that.

A: One option is to select the attr elements and iterate those as HierarchicalConfiguration objects:
List<HierarchicalConfiguration> nodes = config.configurationsAt("attrs/attr");
for(HierarchicalConfiguration c : nodes ) {
    ConfigurationNode node = c.getRootNode();
    System.out.println(
        "name:" + ((ConfigurationNode)
                            node.getAttributes("name").get(0)).getValue() +
        " VAL:" + ((ConfigurationNode)
                            node.getAttributes("val").get(0)).getValue());
}

That's not very pretty, but it works.

A: How can get the value of the tag which matches to a given attribute like in this xml sample using commons XML configuration?
<attrs>
    <attr name="my_name"> First Name</attr>
    <attr name="my_name2"> First Name 2 </attr>
</attrs>

Want to get the value First Name for a matching my_name attribute value


text:
Q: Correct wording/spelling for our company's new slogan I work for a small company (located in Italy) which makes websites and sells/repairs computers.
Right now we are in the process of creating a new logo and updating our slogan / corporate design.
My colleagues / boss came up with the following idea for a slogan: (none of us are native english speakers)
[COMPANY NAME]
links the digital world
Now - I'm really not sure if "links the digital world" is correct or does even make sense at all. I think the idea was that we - as a company - link our clients to the digital world, but "linking you to the digital world" was apparently too long and/or clumsy. In my opinion, it should as least be "links the digital world TO something" or "linking the digital world".
I need your assistance as native english speakers: How does this slogan sound to you
Thanks!

A: At first glance, I misunderstood the question and thought the [company name] designation was asking for a suggestion for a new name in addition to the best wording for a "logo".
Moving on to the actual choices for a new "logo" then. I agree that "Linking the digital world" does sound better. But, you could also consider simply adding the preposition "to" to your colleagues' suggestion thus making it "Links to the digital world". Lastly, here is a third suggestion if smaller is better. I will offer the easy phrase - "The digital link"


text:
Q: jQuery send class as POST parameters I want to send class as post ajax parameters.
my class :
  public class PageInput
    {
        public string ActionName { get; set; }
        public string Controller { get; set; }
        public int CountPage { get; set; }
        public int CountRecordInPage { get; set; }
    public KeyValuePair<string, short> No { get; set; }

    }

ajax code :
$.ajax({
        url: '@Url.Action("GetPageNumbers", "MyClasses")',
        data: '@Model.PageInput',
        success: function (data) {
            alert(data);
        }
    });

action :
 public ActionResult GetPageNumbers(PageInput pageInput)
    {
        return PartialView("_PagingNumbers", pageInput);
    }

doesn't working. But why?
When data are received by the actionResult are empty!!But the data are correct before sending.

A: You need to create an object within your JavaScript code and send that across instead:
$.ajax({
    url: '@Url.Action("GetPageNumbers", "MyClasses")',
    data: {
        ActionName: '@Model.ActionName',
        Controller: '@Model.Controller',
        CountPage: @Model.CountPage,
        CountRecordInPage: @Model.CountRecordInPage,
    },
    success: function (data) {
        alert(data);
    }
});

You also need to add the [HttpPost] attribute to your controller action

A: My guess would be that you aren't posting to your url
$.ajax({
    url: '@Url.Action("GetPageNumbers", "MyClasses")',
    data: '@Model.PageInput',
    type: 'POST',
    success: function (data) {
        console.info(data);
    }
});

Now it will post.

A: you should use following pattern:
$.ajax({
    url: '@Url.Action("GetPageNumbers", "MyClasses")',
    data: {"PageInput.CountPage": "@Model.PageInput.CountPage", "PageInput.CountRecordInPage":"@Model.PageInput.CountRecordInPage" },
    success: function (data) {
        alert(data);
    }
});

I think It will work for you. While Ajax post it is necessary that you should use name of the class in AJAX post parameters.


text:
Q: Using generics to cast list of objects i have some structure that's set by an external library.
It's a list of items, where the itemdata is internaly beeing hold as Object.
When using the list, especially when querying it with linq, i always have to cast the objects.
Here some sample-code:
Module Module1

    '========================
    'defined inside the lib
    '========================
    Public Class DataItem
        Public Property P1 As Object
    End Class

    Public Class DataList
        Inherits List(Of DataItem)
    End Class
    '========================

    Public Class D1
        Public Property Val As String
    End Class

    Sub Main()
        Dim I1 As New D1 With {.Val = "test1"}
        Dim I2 As New D1 With {.Val = "test2"}

        Dim dl As New DataList()
        dl.Add(New DataItem With {.P1 = I1})
        dl.Add(New DataItem With {.P1 = I2})

        Dim ql = (From p In dl Where CType(p.P1, D1).Val = "test1" Select p)

        For Each item In ql
            Console.Out.WriteLine(CType(item.P1, D1).Val)
        Next

        Console.ReadKey()
    End Sub

End Module

Is there any way to bypass this casting?
Something like implementing an generic and overloading the DataList and/or DataItem and use my own IEnumerator?
Speed is not an problem, i could touch every object in the list.
Many thanks
rene


text:
Q: How do I pass my authCode variable from my JSP to a Java class to use in an HTTP call? I am trying to use a java class in conjunction with a JSP. When the server is started, the user goes to the JSP which redirects them to an authentication form for a third party. After the authentication flow they can fill out their info, press submit and that info gets sent to the server in an HTTP post. The issue I am having is passing variables from my JSP to my java class. I suspect I may need to use a servlet but I wanted to see if there was a way to do this with just a Java class/bean before moving it all into a servlet. I understand I may have to do a call for the variable but I'm not sure how to do this. Any answers or advice would be very helpful! I am a beginner with coding but really want to get this little app up and running. Thank you!
serverFlow.java
public class serverFlow {

    public StringBuffer getAccessToken(String redirectUri, String clientId, String clientSecret, String authCode)
            throws IOException {

        // Define base URL
        String baseUrl = "https://idfed.constantcontact.com/as/token.oauth2";

        // Build URL
        String fullUrl = baseUrl + "?code=" + authCode + "&redirect_uri=" + redirectUri
                + "&grant_type=authorization_code&scope=contact_data";
        URL authorizeUrl = new URL(fullUrl);

        // Open connection
        HttpURLConnection con = (HttpURLConnection) authorizeUrl.openConnection();

        // Encode Auth Info
        String credentials = clientId + ":" + clientSecret;
        String auth = "Basic " + Base64.getEncoder().encodeToString(credentials.getBytes());

        // Post Method for CTCT request
        con.setRequestMethod("POST");

        // Add Headers
        con.setRequestProperty("Authorization", auth);

        // Open input steam
        BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));

        String inputLine;
        StringBuffer result = new StringBuffer();

        // Append each line
        while ((inputLine = in.readLine()) != null) {
            result.append(inputLine);
        }

        // Close the stream
        in.close();

        return result;
    }

    public static void main(String[] args){

        serverFlow server = new serverFlow();

    // Print string buffered response of access token, refresh token and authentication type
    // Attempted to use a reqeust but unable to utilize 'reqeust.' is there a way to get the authCode in this Java class from my JSP?
        System.out.println(server.getAccessToken("http%3A%2F%2Flocalhost%3A8080%2Fsignup", clientId, clientSecret, authCode));

    }
}

signup.jsp
<jsp:useBean id="auth" class="infoClass" scope="session" />
<jsp:setProperty name="auth" property="authCode" />

    <title>My Jmml</title>

Contact Information

<%

%>

<jsp:getProperty name="auth" property="authCode"/>

<% if(request.getMethod().equals("GET")){

    // This is where the authCode is generated, how do I get this back over to my serverFlow.jsp?
    String authCode = "";
    try {
        authCode = request.getParameter("code");
        request.setAttribute("authCode", authCode);

        // Verifies it in console
        System.out.println("Here is the auth code: " + authCode);
    }catch(Exception a){
        System.out.println("Could not get Auth Code: " + a);
    }

    }%>

<form method='post' action='<% request.getRequestURL(); %>'>

        Email Address

        <input type='text' name='email' size='50' placeholder="Email" required />

        <input class="submitbutton" type='submit' value='Submit'/>

</form>

<% if(request.getMethod().equals("POST")) {

    }%>


text:
Q: First law of thermodynamics (derivation) According to the first law of thermodynamics,
$$dQ=dU+dW$$
The derivation of this formula is as follows:
$dW=Fdx$
where $d$x stands for displacement.
$dW=P(Adx)$
as force = pressure x area and $dW= PdV$.
Finally, $dQ= dU+dW$.
What does $dV$ stand for? And how is $(Adx)=dV$.
Please answer my question in the simplest way possible.

A: $dV$ is the incremental volume. If you have a cylinder with a base of area $A$ and with height $dx$, then the volume will be $dV=A.dx$


text:
Q: PHP PDO SQLSERVER Output Parameters Issue $query = '  Declare @MemCode Varchar(12);
        Declare @ConCounter decimal(28,0);
        Set @MemCode = null;
        Set @ConCounter = null;
        EXECUTE spQMInsEventMember_TMS
        "'.$masterEventCode.'",
        "'.$eventCode.'",
        '.$memberContactTitle.',
        "'.$guestFirstName.'",
        "'.$guestLastName.'",
        '.$address.',
        '.$townDescription.',
        '.$countryCode.',
        '.$postZip.',
        '.$STD.',
        '.$phone.',
        "'.$guestEmail.'",
        '.$isMember.',
        '.$divisionCode.',
        '.$statusCode.',
        '.$subStatusCode.',
        '.$memberTypeCode.',
        '.$memberTitles.',
        '.$memberSubType.',
        '.$classCode.',
        '.$subClassCode.',@MemCode OUTPUT,@ConCounter OUTPUT;
        SELECT @MemCode AS member_code;
        SELECT @ConCounter AS contact_counter;';
        //print_r($query);

        $res = $this->dbh->query($query);
        $result = $res->fetchAll();
        print_r($result);

The Stored Procedure runs fine, if I run it on SQLSERVER, I gets 2 Rows.
But when I run it from the PHP, I do not get the member_code or contact_counter returned in the results array.
What am I doing wrong?

A: Is it possibly because of multiple select statements?  If your query is working in sql but not in PHP, you should try printing out your parameters to see if they are being set properly.


text:
Q: How to restore Ctrl+M,O behaviour in VS2017 In VS2015 and before, Ctrl+M,O would collapse all constructors, methods, properties in a file. It would also collapse all regions.
In VS2017 it no longer collapses the regions.
I really liked the high level view that this keyboard chord produced, with collapsed regions. In VS2017 that chord will actually expand all regions too.
You can invoke Ctrl+M,L twice, but this collapses everything which makes it impossible to see anything.
Is there a way of getting the old behaviour back?

A: Seems like there's a solution for it here
If I understood you right

It seems that this behavior still exists within visual studio 2017 except it is turned off by default. It can be enabled under Tools -> Options -> Text Editor -> C# -> Advanced -> Outlining -> "Collapse #regions when collapsing to definitions"


text:
Q: How does inductor resist the increasing dc current? I understand the point that inductor will have high resistance for ac current.this is because the magnetic field produced during positive half cycle will oppose the negative half cycle since the energy during positive half cycle will be stored in magnetic field. But how would this happen there is an increase in dc current.please explain how would inductor react.

A: You said it in your question: "an increase in DC current". Sometimes people get all bundled up in the term "AC". AC describes a special kind of changing current which is sinusoidal. We know pretty much everything there is to know about sinusoids, so describing the nature of AC is pretty easy.
An increase in DC current is still a changing current just like the current changes in an AC signal. The same magnetic effects apply (per your question) when there is any type of change in current. It just so happens that AC is a special type of changing current.
Having said that, describing the true conditions of the inductor and its related fields under arbitrarily changing currents requires more general use of electrodynamics laws.
If you want some more elaboration, please speak up. We'll talk about frequency and the Fourier representation of signals to go in a little deeper.

A: The inductor will react the same for AC and DC.  The energy stored in an inductor is $$ E_L = {1\over 2} L \cdot i(t)^2 $$ and in a capacitor $$ E_C = {1\over 2} C \cdot v(t)^2.$$  The energy depends on the instantaneous current or voltage, AC or DC.
To change the energy or current, the voltage $$v(t) = L {d i(t) \over dt}$$ is required on the inductor.
For a capacitor the current required is $$i(t) = C {d v(t) \over dt}.$$
The magnetic or electric field takes time to change and the size of \$ L \$ or \$ C \$ is what resists the change.
I the inductor is designed for AC, and then used in DC, it might saturate, causing the inductance to become almost the same as for a free-air winding.
Tell me if I need to simplify this a lot and I will try.

A:
But how would this happen there is an increase in dc current.please explain how would inductor react.

In order for the current through the inductor to increase, the magnetic field in the core has to increase. This means the stored magnetic energy has to increase.
The magnetic energy can only increase as fast as the applied electric power allows. For example, if you want 1 more joule of magnetic energy, you must supply 1 watt for 1 second, or 2 W for 0.5 s...some combination that adds up to 1 J.
The net result of this requirement is the usual relationship that defines an [ideal] inductor
$$\frac{\rm{d}i}{\rm{d}t}=\frac{v}{L}$$

A:
the magnetic field produced during positive half cycle will oppose the negative half cycle since the energy during positive half cycle will be stored in magnetic field.

You are misunderstanding how this works. The inductor doesn't "wait" for the negative cycle before opposing a change.  It's doing it the whole time.  At the beginning of the positive cycle, it is opposing the rise in current as it builds to the peak.  As the positive cycle begins to return to zero, it opposes that, too (it wants to push it, so it doesn't decrease).  The same thing is happening on the negative part of the cycle.  As you pass through zero, the inductor is still trying to push current forward (using the residual field), but as the applied voltage is now going negative, the forward push is still in opposition.  And so on.
In a "dc" circuit, the moment the voltage changes (and the current tries to change), the inductor opposes it.  The inductor doesn't know if this change is the start of an AC cycle, or a change in the DC voltage.  And if I were to clip out this very tiny part of the waveform and show it to you, you couldn't tell, either.


text:
Q: Javaassist source error while instrumenting a method I am trying to instrument a method in one of my entities (com.xxx.entity.Order):
private String getLookupMethodString() {
    return new StringBuilder(
            "public java.lang.String lookupCustomValue(java.lang.String fieldName) throws java.lang.IllegalAccessException, java.lang.reflect.InvocationTargetException, java.beans.IntrospectionException {").append(
            "java.lang.String mappingFieldName =  \"value1\";").append(
            "com.xxx.entity.CustomFieldValue cfv = (com.xxx.entity.CustomFieldValue) new java.beans.PropertyDescriptor(\"customFieldValue\", getClass()).getReadMethod().invoke(this);").append(
            "return (java.lang.String) new java.beans.PropertyDescriptor(mappingFieldName, com.xxx.entity.CustomFieldValue.class).getReadMethod().invoke(cfv);}").toString();
}

public byte[] transform(ClassLoader clazzLoader, String className, Class<?> clazz, ProtectionDomain arg3, byte[] rawBytes) throws IllegalClassFormatException {
    CtClass cl = pool.makeClass(new java.io.ByteArrayInputStream(rawBytes));
    String lookupMethodString = getLookupMethodString();
    CtMethod lookupMethod = CtMethod.make(lookupMethodString, cl); // Error encountered at this line.
    cl.addMethod(lookupMethod);
}

The field customFieldValue has also been instrumented in this class, hence I am using reflection to fetch its value. The error I get on executing this is:
[source error] invoke(com.xxx.entity.CustomFieldValue) not found in java.lang.reflect.Method

Can somebody please help me with this?

A: Got it to work, the issue was with the invocation of invoke method. When tried to call invoke method with second argument as null, it worked. (Not pretty sure why?)
return (java.lang.String) new java.beans.PropertyDescriptor(mappingFieldName, com.xxx.entity.CustomFieldValue.class).getReadMethod().invoke(cfv, null);}").toString();


text:
Q: What to use for financial product model =>Decimal or double I know that the consensus is "money = decimal". I understand all the technical fine point of the argument, and agree with that.
Where I still have issue is that it's seems to assume that all finance applications are simple ledger...
When you start to play with ratio, interpolation (cubic spline for example) or if you move to some Stochastic model, differentiate, integral... it seems that the decimal become meaningless.
So my question is where is the border (mathematical complexity?) when using decimal become more a burden that an advantage?
EDIT: most of complex financial product use statistical model in order to be priced. In the end the price is a $$, and as Flydog57 point out, most (if not all) mathematical library used double as input/output.
So unless I redeveloped all these mathematical functions (that has been develops by people way smarter than me) I need to constantly cast decimal to double and conversely. That's where the problem is.
Is it useful to use decimal "because it's money" if in the end I constantly need to cast it in double to be able to create a price?
That where the argument saying (money = decimal) may be a simplistic view of a real world problem. I know the question seems to be duplicate but all the other answer out there don't deal with this specify case where a price (money) is actually created from a statistical model


text:
Q: jQuery UI, resize the last div responsively How to make the last div always fill the end by pulling it to the left, decreasing its size by pushing it to the right and when changing the size of the first div does not affect the last div only the first and second div?
In the code below, for exceeding the size of the caixa, the div goes to the bottom.
codepen.io e.g.

$(".caixa").resizable({
   handles: "s",
   minHeight: 50,
   maxHeight: 300
});
$(".ta").resizable({
   handles: "e",
});
.caixa {
  background-color: #444;
 /* margin: 100px auto; */
  height: 200px;
  width: 600px;
  overflow: hidden;
  padding-bottom:2px;
}
.ta {
  float: left;
  height: 100%;
  width: 33%;
  padding-right:2px;
}
.ta1 {
  background-color: #000;
}
.ta2 {
  background-color: #ddd;
}
.ta3 {
  background-color: #888;
}
textarea {
  resize:none;
  width: 100%;
  height: 100%;
  padding: 0;
  margin: 0;
}

<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">

<textarea></textarea>

<textarea></textarea>

<textarea></textarea>


text:
Q: ClearML webapp is slow We manage our own ClearML server, on an EC2 instance AWS cloud.
Instance type: t3.xlarge (4 vCPUs, 16 GiB Memory).
Data disk: gp3 (size: 200 GB, IOPS: 3,000, Throughput: 125).
We have 3 ClearML projects, one with 643,000 experiments, another with 151,000 and the small one with 25,000. Total experiments in all projects: 819,000
ClearMLwebapp is very slow. For example, it takes about 30 seconds just to load the main dashboard. Searching a specific experiment by ID is also very slow.
What can we do to improve the performance?
We tried to add more memory, and it improved the performance, but only a little. It is still to slow.

A: Disclaimer: I'm a member of the ClearML team (formerly Trains)
I think your issue is simply caused by the number of serving processes in the server's apiserver component (probably 1 process at the moment).
Assuming you are using the docker-compose deployment of ClearML Server, in order to increase the number of processes add the CLEARML_USE_GUNICORN=1 environment variable to the apiserver service.
This would run the apiserver component with 8 processes by default. To specify a different number of processes, add the CLEARML_GUNICORN_WORKERS=12 environment variable (for 12 processes, for example).
Please note that this mode (and of course, more processes) required more CPU and RAM resources. I believe your current setup should be enough for 8 processes, but I would recommend to monitor the machine's CPU and RAM usage and upgrade as required.


text:
Q: fake http post request - viewstate I am trying to fake a post request to a site programmed with c#.
I used WireShark to sniff the communication between my computer and the server.
I noticed that the client send viewstate data (encoded in Base64) and I would like to know how to fake it in my request.
my post code
 public static void sendPostRequest(string responseUri,CookieCollection responseCookies)
        {
            HttpWebRequest mPostRequest =
                (HttpWebRequest)WebRequest.Create("http://tickets.cinema-city.co.il/webtixsnetglilot/SelectSeatPage2.aspx?dtticks=" + responseUri + "&hideBackButton=1");
            mPostRequest.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.95 Safari/537.36";
            mPostRequest.KeepAlive = false;
            mPostRequest.Method = "Post";
            mPostRequest.ContentType = "application/x-www-form-urlencoded";

            CookieContainer mCookies= new CookieContainer();
            foreach (Cookie cookie in responseCookies)
            {
                mCookies.Add(cookie);
            }
            mPostRequest.CookieContainer = mCookies;
            HttpWebResponse myHttpWebResponse2 = (HttpWebResponse)mPostRequest.GetResponse();
        }

A: If you can "fake" signed/encrypted data you don't really need to deal with fake posts - just steal all SSL traffic :).
View state comes in original response for the page encrypted - so you simply need to parse original response (use Html Agility Pack) and send that view state back in post request.


text:
Q: Overload the constructor of a subclass I'm trying to make a constructor that takes 2 elements of type Punto and assigns it to the instance variables, in my superclass I already have a constructor but I want one more in my subclass so first in my subclass I call the superclass constructor and then I try to add one more with the following error:

constructor in class cannot be applied to given types.

Superclass:
public class Poligono  implements Figura  {

Punto[] vertici;

public Poligono(Punto[] vertici) throws IndexOutOfBoundsException {
    if(vertici == null || vertici.length<3) {
        throw new IndexOutOfBoundsException();
    }
    this.vertici = vertici;
}

Subclass:
package figura;

import punto.Punto;

public class Rettangolo extends Poligono{

   Punto p1;
   Punto p2;

   public Rettangolo(Punto[] vertici) throws IndexOutOfBoundsException {
       super(vertici);
   }

   public Rettangolo(Punto p1, Punto p2) throws NullPointerException{

       if(p1==null || p2==null) throw new NullPointerException();

       this.p1 = p1;
       this.p2 = p2;
   }

in my second constructor i get the error:
constructor Poligono in class Poligono cannot be applied to given types;
required: Punto[]
found: no arguments
reason: actual and formal argument lists differ in length

A: Your public Rettangolo(Punto p1, Punto p2) must call some constructor of the super class Poligono. The compiler complains that the only constructor available - Poligono(Punto[] vertici) - doesn't fit the parameters of the second Rettangolo constructor.
You have to explicitly call the Poligono constructor with the super(..) call.
Assuming that the two points passed to that constructor are two opposite corners of a rectangle, and that the Poligono constructor expects an array of vertices, you need something like this :
public Rettangolo(Punto p1, Punto p2) {

    super (new Punto[]{p1,
                       new Punto (p1.getX(),p2.getY()),
                       p2,
                       new Punto (p2.getX(),p1.getY())});

    this.p1 = p1;
    this.p2 = p2;
}

I may have gotten the order of the points or the method names wrong.

A: Why does this() and super() have to be the first statement in a constructor?
What you can do (besides calling super()) is
public Rettangolo(Punto p1, Punto p2) {
     super(new Punto[] {p1, p2});
}

I'd prefer this solution, because if you use Rettangolo(Punto[]) you do not have any points to work with. So either you read the points out in your first constructor, e.g.,
public Rettangolo(Punto[] vertici) throws IndexOutOfBoundsException {
   super(vertici);
   p1 = vertici[0];
   p2 = vertici[1];
}

or you do not work with single points and only use the array instead.

A: There is no superclass constructor which will be called if you initialize 'Rettangolo' object.
Whenever a object is created the parent class state is initialized before child classes.
The first line of the constructor is either call to the parent constructor or call to the another constructor of the same class, which will call the parent constructor.
Now your case :
public Rettangolo(Punto p1, Punto p2) throws NullPointerException{

   if(p1==null || p2==null) throw new NullPointerException();

   this.p1 = p1;
   this.p2 = p2;

}
Your constructor is trying to call the default constructor but since there is no such constructor defined, error occurred.
Either you define a default constructor to the parent class and initialize Punto p1, p2 but then vertici[] array will be null.
Or you can do
public Rettangolo(Punto p1, Punto p2) throws NullPointerException{
   super(new Punto[] {p1,p2});
   if(p1==null || p2==null) throw new NullPointerException();

   this.p1 = p1;
   this.p2 = p2;
}

But then it depends on your requirements. You just need to remember that parent class constructor will always be called first.


text:
Q: Logged In Windows 7 Active Directory User from SQL Server Simply putting it - I have a Spring-Jersey application (no front-end) deployed into Tomcat, as a service, which is installed in SQL Server 2008.
Users log into their machines (windows 7) and VPN into SQL Server.
After which they can open a KML file in Google Earth.
This will plot coordinates generated by the tomcat application, in real-time.
QUESTION - I want only users who are in a certain group in active directory to be able to use the plotting service.
How can I get the win7-username and win7-group name of the user who logged into his windows 7 machine?
My Java sits in Tomcat/SQL Server, so .getProperty("user.name"); will get me username of the SQL server user, not the windows 7 user who is trying to access my app.
I hope this is clearer.
I appreciate your efforts.


text:
Q: SCP always returns the same error code I have a problem copying files with scp. I use Qt and copy my files with scp using QProcess. And when something bad happens I always get exitCode=1. It always returns 1. I tried copying files with a terminal. The first time I got the error "Permission denied" and the exit code was 1. Then I unplugged my Ethernet cable and got the error "Network is unreachable". And the return code was still 1. It confuses me very much cause in my application I have to distinct these types of errors.
Any help is appreciated. Thank you so much!

A: See this code as a working example:
bool Utility::untarScript(QString filename, QString& statusMessages)
{
  // Untar tar-bzip2 file, only extract script to temp-folder
  QProcess tar;
  QStringList arguments;
  arguments << "-xvjf";
  arguments << filename;
  arguments << "-C";
  arguments << QDir::tempPath();
  arguments << "--strip-components=1";
  arguments << "--wildcards";
  arguments << "*/folder.*";

  // tar -xjf $file -C $tmpDir --strip-components=1 --wildcards

  tar.start("tar", arguments);

  // Wait for tar to finish
  if (tar.waitForFinished(10000) == true)
  {
    if (tar.exitCode() == 0)
    {
      statusMessages.append(tar.readAllStandardError());
      return true;
    }
  }

  statusMessages.append(tar.readAllStandardError());
  statusMessages.append(tar.readAllStandardOutput());
  statusMessages.append(QString("Exitcode = %1\n").arg(tar.exitCode()));
  return false;
}

It gathers all available process output for you to analyse. Especially look at readAllStandardError().


text:
Q: Show variable value in list? <!doctype html>
<html>
<head>
<body>
<script>
  var a=8;
  var b=5;
  var c=8;
  var d=9;
</script>

<select size="5">
    <option value="1">"a" seats remaining</option>
    <option value="2">"b" seats remaining</option>
    <option value="3">"c" seats remaining</option>
    <option value="4">"d" seats remaining</option>
</select>
</body>
</html>

In the list, instead of a,b,c,d, can i show the values of the variables like 8,5,8,9?

A: Give your options an ID for easy access:
<select size="5">
    <option id="a" value="1"></option>
    <option id="b" value="2"></option>
    <option id="c" value="3"></option>
    <option id="d" value="4"></option>
</select>

Then you can simple do something like
var a=8;
var b=5;
var c=8;
var d=9;

document.getElementById("a").innerHTML = a + ' seats remaining';
document.getElementById("b").innerHTML = b + ' seats remaining';
document.getElementById("c").innerHTML = c + ' seats remaining';
document.getElementById("d").innerHTML = d + ' seats remaining';

Demo: http://jsfiddle.net/Ayp28/

A: Try this with using jQuery if you want to replace.
$("select > option").each(function() {
    var array = {"a":"8", "b":"5", "c":"8", "d":"9"};
    for (var val in array)
        this.text = this.text.split('"' + val + '"').join('"' + array[val] + '"');
});


text:
Q: How to check if data already exists in MySQL with PHP This is my php code. How to check if this 3 parameters (user,agwera,vis) exist in MySQL with PHP? And if already exist don't add a second time. + want echo "Already in Exists<br/>";
    <?
sleep(10);
define ('DBHOST', 'yyy');
define ('DBNAME', 'xxxx');
define ('DBUSER', 'xxxx');
define ('DBPASS', 'xxxxx');

mysql_pconnect(DBHOST, DBUSER, DBPASS) or die('DB');
mysql_select_db(DBNAME) or die ('USER');
mysql_query('SET NAMES utf8');

header('Content-Type: text/html; charset=utf-8');
error_reporting (0);
$act = isset($_GET['act']) ? $_GET['act'] : '';
switch($act)
{
case 'send':
$destination = $_POST['adress'];
$signature = $_POST['text'];
$text = "$signature ";

if (empty($_POST["text"])  or strlen($_POST["text"])==0){

@header("location:error5.php");
break;

}

$str = $_POST['text'];
if (strlen($str)>160){
@header("location:error4.php");
break;

}

if (!preg_match('/^[0-9]{9}$/',$destination))
{
@header("location:error1.php");
break;
}

$str2 = $_POST['sender'];
if (strlen($str2)>11){
@header("location:error2.php");
break;
}

if (empty($_POST["sender"])  or strlen($_POST["sender"])==0){

@header("location:error3.php");
break;

}

else
{

    $password = 'zzzzzz';
    $destination = $_POST['adress'];
  $nomeri = "995$destination";
    $nomeri2 = $_POST['sender'];
    $source = $nomeri2;
    $signature = $_POST['text'];
    $text = "$signature ";

    $content =
                'key='.rawurlencode($password).
                '&destination='.rawurlencode($nomeri).
                '&sender='.rawurlencode($source).
                '&content='.rawurlencode($text);

    $a = file_get_contents('http://example.com/api/send.aspx?'.$content);

@header("location:ok.php");

mysql_query("INSERT `gagzavnili` SET
                      `user`        =   '".$source."',
                      `agwera`      =   '".$text."',
                      `vis`     =   '".$destination."',
                      `time_upload` =   '".time()."',
                      `time`        =   '".time()."'") or die(mysql_error());
                       $file_id = mysql_insert_id();

}
}
?>

A: $data = array('user', 'agwera', 'vis');

foreach( $data as $val ) {
$res = mysql_query("SELECT * FROM `table_name` WHERE `column_name` = '$val'");
$count = mysql_num_rows($res);

if( $count > 0 ) {
    echo "<script>alert('Already Exists')</script>";
} else {
    //insert query for $val...
}
}

A: First, it's June 2014, you shouldn't be using the mysql* lib anymore. Switch to mysqli.
Second, there is no truly elegant way to do this without making two queries.
Run a query to select the row with the parameters you specified. Something along the lines of
SELECT COUNT(<some field>) FROM <table name> WHERE field1 = 'value' AND...

If count comes back greater than zero, the entry exists. This doesn't just go for PHP, but for any time you want to see if data exists in a database (in your case MySQL).


text:
Q: Sending google map link through GSM network using Arduino uno Can anyone tell me how I can send the following arduino code, in a single SMS message via GSM network
Serial.print("http://maps.google.com/?q=");
latitude();
Serial.print(',');
longitude();


text:
Q: I want to navigate to Another page after I click Login I use .Net as back-end and now im working with angular for routing part i'm stuck in navagite to another page using authentication I supposed to use
navigate router after subscribe  but I don't know how
export class LoginComponent {

  title = 'webUI.UI';
  user = new User();

  constructor(private authService: AuthService, private router: Router) {}

  login(user: User) {
    this.authService.login(user).subscribe((token: string) => {
      localStorage.setItem('authToken', token);
    });

    if (localStorage.getItem('authToken') != null){
??????

    }
  }
}

my router
const routes: Routes = [

  {
    path: 'login',
    component: LoginComponent
},

{

  path: 'signup',
    component: SignupComponent
},

{
  path: 'home',
  component: EmployeepListComponent
},

A: You can use a Guard, too for this. Read more here. The canActivateguard can protect any component inside your router. So you can check your token or anything and then redirect to login, or the page the user want to navigate.
import { Injectable } from "@angular/core";
import { Router } from "@angular/router";
import {
  CanActivate,
  ActivatedRouteSnapshot,
  RouterStateSnapshot
} from "@angular/router";
import { Observable } from "rxjs";
import { tap } from "rxjs/operators";

import { AuthService } from "./auth.service";

@Injectable()
export class CanActivateGuard implements CanActivate {

  constructor(
    private auth: AuthService,
    private router: Router
  ) {}

  canActivate(
    next: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<boolean> | Promise<boolean> | boolean {
    const token = this.auth.getToken();
    const url = "/token/verify/";

    if (!token) {
      this.router.navigate(["/login"]);
      return false;
    }

    return this.auth.verifyToken().pipe(
      tap(allowed => {
        if (!allowed) this.router.navigate(["/login"]);
      })
    );
  }
}

Here is a Stackblitz example.

A: Do that in the ngOnInit in app component :
ngOnInit(){
  if (localStorage.getItem('authToken') != null){
    this.router.navigete(['login'])
   }
}

or in the login function do that :
login(user: User) {
 this.authService.login(user).subscribe((token: string) => {
    if(token !=null)  {
       localStorage.setItem('authToken', token);
       this.router.navigate(['otherPath'])
     }
  });
}


text:
Q: Pig script doesn't work with MapReduce I'm trying to use Hadoop and Apache Pig. I have a .txt file with some data and a script .pig file with my script :
student = LOAD '/home/srv-hadoop/data.txt' USING PigStorage(',')
   as (id:int, firstname:chararray, lastname:chararray, phone:chararray, city:chararray);

student_order = ORDER student BY firstname ASC;

Dump student_order;

And this is my .txt file :
001,Rajiv,Reddy,21,9848022337,Hyderabad
002,siddarth,Battacharya,22,9848022338,Kolkata
003,Rajesh,Khanna,22,9848022339,Delhi
004,Preethi,Agarwal,21,9848022330,Pune
005,Trupthi,Mohanthy,23,9848022336,Bhuwaneshwar
006,Archana,Mishra,23,9848022335,Chennai
007,Komal,Nayak,24,9848022334,trivendram
008,Bharathi,Nambiayar,24,9848022333,Chennai

But, when I execute : pig -x mapreduce data.pig
17/07/25 17:04:59 INFO pig.ExecTypeProvider: Trying ExecType : LOCAL
17/07/25 17:04:59 INFO pig.ExecTypeProvider: Trying ExecType : MAPREDUCE
17/07/25 17:04:59 INFO pig.ExecTypeProvider: Picked MAPREDUCE as the ExecType
2017-07-25 17:04:59,399 [main] INFO  org.apache.pig.Main - Apache Pig version 0.17.0 (r1797386) compiled Jun 02 2017, 15:41:58
2017-07-25 17:04:59,399 [main] INFO  org.apache.pig.Main - Logging error messages to: /home/srv-hadoop/pig_1500995099397.log
2017-07-25 17:04:59,749 [main] WARN  org.apache.hadoop.util.NativeCodeLoader - Unable to load native-hadoop library for your platform... using builtin-java classes where applicable
2017-07-25 17:04:59,930 [main] INFO  org.apache.pig.impl.util.Utils - Default bootup file /home/srv-hadoop/.pigbootup not found
2017-07-25 17:05:00,062 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - mapred.job.tracker is deprecated. Instead, use mapreduce.jobtracker.address
2017-07-25 17:05:00,066 [main] INFO  org.apache.pig.backend.hadoop.executionengine.HExecutionEngine - Connecting to hadoop file system at: hdfs://localhost:54310
2017-07-25 17:05:00,470 [main] INFO  org.apache.pig.backend.hadoop.executionengine.HExecutionEngine - Connecting to map-reduce job tracker at: localhost:54311
2017-07-25 17:05:00,489 [main] INFO  org.apache.pig.PigServer - Pig Script ID for the session: PIG-data.pig-2bb2e75c-41a7-42bf-926f-05354b881211
2017-07-25 17:05:00,489 [main] WARN  org.apache.pig.PigServer - ATS is disabled since yarn.timeline-service.enabled set to false
2017-07-25 17:05:01,230 [main] INFO  org.apache.pig.tools.pigstats.ScriptState - Pig features used in the script: ORDER_BY
2017-07-25 17:05:01,279 [main] INFO  org.apache.pig.data.SchemaTupleBackend - Key [pig.schematuple] was not set... will not generate code.
2017-07-25 17:05:01,308 [main] INFO  org.apache.pig.newplan.logical.optimizer.LogicalPlanOptimizer - {RULES_ENABLED=[AddForEach, ColumnMapKeyPrune, ConstantCalculator, GroupByConstParallelSetter, LimitOptimizer, LoadTypeCastInserter, MergeFilter, MergeForEach, NestedLimitOptimizer, PartitionFilterOptimizer, PredicatePushdownOptimizer, PushDownForEachFlatten, PushUpFilter, SplitFilter, StreamTypeCastInserter]}
2017-07-25 17:05:01,362 [main] INFO  org.apache.pig.impl.util.SpillableMemoryManager - Selected heap (PS Old Gen) of size 699400192 to monitor. collectionUsageThreshold = 489580128, usageThreshold = 489580128
2017-07-25 17:05:01,411 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MRCompiler - File concatenation threshold: 100 optimistic? false
2017-07-25 17:05:01,452 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.SecondaryKeyOptimizerMR - Using Secondary Key Optimization for MapReduce node scope-23
2017-07-25 17:05:01,462 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MultiQueryOptimizer - MR plan size before optimization: 3
2017-07-25 17:05:01,462 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MultiQueryOptimizer - MR plan size after optimization: 3
2017-07-25 17:05:01,515 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - session.id is deprecated. Instead, use dfs.metrics.session-id
2017-07-25 17:05:01,516 [main] INFO  org.apache.hadoop.metrics.jvm.JvmMetrics - Initializing JVM Metrics with processName=JobTracker, sessionId=
2017-07-25 17:05:01,548 [main] INFO  org.apache.pig.tools.pigstats.mapreduce.MRScriptState - Pig script settings are added to the job
2017-07-25 17:05:01,552 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - mapred.job.reduce.markreset.buffer.percent is deprecated. Instead, use mapreduce.reduce.markreset.buffer.percent
2017-07-25 17:05:01,552 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - mapred.job.reduce.markreset.buffer.percent is not set, set to default 0.3
2017-07-25 17:05:01,555 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - mapred.output.compress is deprecated. Instead, use mapreduce.output.fileoutputformat.compress
2017-07-25 17:05:01,558 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - This job cannot be converted run in-process
2017-07-25 17:05:01,570 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - mapred.submit.replication is deprecated. Instead, use mapreduce.client.submit.file.replication
2017-07-25 17:05:01,891 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Added jar file:/home/srv-hadoop/pig/pig-0.17.0-core-h2.jar to DistributedCache through /tmp/temp1676993497/tmp-1698368733/pig-0.17.0-core-h2.jar
2017-07-25 17:05:01,932 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Added jar file:/home/srv-hadoop/pig/lib/automaton-1.11-8.jar to DistributedCache through /tmp/temp1676993497/tmp885160047/automaton-1.11-8.jar
2017-07-25 17:05:01,975 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Added jar file:/home/srv-hadoop/pig/lib/antlr-runtime-3.4.jar to DistributedCache through /tmp/temp1676993497/tmp-1346471388/antlr-runtime-3.4.jar
2017-07-25 17:05:02,012 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Added jar file:/home/srv-hadoop/pig/lib/joda-time-2.9.3.jar to DistributedCache through /tmp/temp1676993497/tmp32088650/joda-time-2.9.3.jar
2017-07-25 17:05:02,023 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.JobControlCompiler - Setting up single store job
2017-07-25 17:05:02,031 [main] INFO  org.apache.pig.data.SchemaTupleFrontend - Key [pig.schematuple] is false, will not generate code.
2017-07-25 17:05:02,031 [main] INFO  org.apache.pig.data.SchemaTupleFrontend - Starting process to move generated code to distributed cacche
2017-07-25 17:05:02,031 [main] INFO  org.apache.pig.data.SchemaTupleFrontend - Setting key [pig.schematuple.classes] with classes to deserialize []
2017-07-25 17:05:02,093 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - 1 map-reduce job(s) waiting for submission.
2017-07-25 17:05:02,095 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - mapred.job.tracker.http.address is deprecated. Instead, use mapreduce.jobtracker.http.address
2017-07-25 17:05:02,095 [main] INFO  org.apache.hadoop.conf.Configuration.deprecation - mapred.job.tracker is deprecated. Instead, use mapreduce.jobtracker.address
2017-07-25 17:05:02,104 [JobControl] INFO  org.apache.hadoop.metrics.jvm.JvmMetrics - Cannot initialize JVM Metrics with processName=JobTracker, sessionId= - already initialized
2017-07-25 17:05:02,113 [JobControl] INFO  org.apache.hadoop.conf.Configuration.deprecation - mapred.task.id is deprecated. Instead, use mapreduce.task.attempt.id
2017-07-25 17:05:02,178 [JobControl] WARN  org.apache.hadoop.mapreduce.JobResourceUploader - No job jar file set.  User classes may not be found. See Job or Job#setJar(String).
2017-07-25 17:05:02,207 [JobControl] INFO  org.apache.pig.builtin.PigStorage - Using PigTextInputFormat
2017-07-25 17:05:02,213 [JobControl] INFO  org.apache.hadoop.mapreduce.JobSubmitter - Cleaning up the staging area file:/home/srv-hadoop/hadoop-2.6.2/tmp/mapred/staging/srv-hadoop1897657638/.staging/job_local1897657638_0001
2017-07-25 17:05:02,214 [JobControl] INFO  org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob - PigLatin:data.pig got an error while submitting
org.apache.pig.backend.executionengine.ExecException: ERROR 2118: Input path does not exist: hdfs://localhost:54310/home/srv-hadoop/data.txt
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:294)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:302)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:319)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:197)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1297)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1294)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1656)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1294)
    at org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob.submit(ControlledJob.java:335)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.pig.backend.hadoop.PigJobControl.submit(PigJobControl.java:128)
    at org.apache.pig.backend.hadoop.PigJobControl.run(PigJobControl.java:205)
    at java.lang.Thread.run(Thread.java:748)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher$1.run(MapReduceLauncher.java:301)
Caused by: org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://localhost:54310/home/srv-hadoop/data.txt
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:321)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:264)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigTextInputFormat.listStatus(PigTextInputFormat.java:36)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.getSplits(FileInputFormat.java:385)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:280)
    ... 18 more
2017-07-25 17:05:02,597 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - HadoopJobId: job_local1897657638_0001
2017-07-25 17:05:02,597 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - Processing aliases student
2017-07-25 17:05:02,597 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - detailed locations: M: student[1,10],student[-1,-1] C:  R:
2017-07-25 17:05:02,600 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - 0% complete
2017-07-25 17:05:07,608 [main] WARN  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - Ooops! Some job has failed! Specify -stop_on_failure if you want Pig to stop immediately on failure.
2017-07-25 17:05:07,608 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - job job_local1897657638_0001 has failed! Stop running all dependent jobs
2017-07-25 17:05:07,609 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - 100% complete
2017-07-25 17:05:07,619 [main] INFO  org.apache.hadoop.metrics.jvm.JvmMetrics - Cannot initialize JVM Metrics with processName=JobTracker, sessionId= - already initialized
2017-07-25 17:05:07,620 [main] ERROR org.apache.pig.tools.pigstats.PigStats - ERROR 0: java.lang.IllegalStateException: Job in state DEFINE instead of RUNNING
2017-07-25 17:05:07,620 [main] ERROR org.apache.pig.tools.pigstats.mapreduce.MRPigStatsUtil - 1 map reduce job(s) failed!
2017-07-25 17:05:07,622 [main] INFO  org.apache.pig.tools.pigstats.mapreduce.SimplePigStats - Script Statistics:

HadoopVersion   PigVersion  UserId  StartedAt   FinishedAt  Features
2.6.2   0.17.0  srv-hadoop  2017-07-25 17:05:01 2017-07-25 17:05:07 ORDER_BY

Failed!

Failed Jobs:
JobId   Alias   Feature Message Outputs
job_local1897657638_0001    student MAP_ONLY    Message: org.apache.pig.backend.executionengine.ExecException: ERROR 2118: Input path does not exist: hdfs://localhost:54310/home/srv-hadoop/data.txt
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:294)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeNewSplits(JobSubmitter.java:302)
    at org.apache.hadoop.mapreduce.JobSubmitter.writeSplits(JobSubmitter.java:319)
    at org.apache.hadoop.mapreduce.JobSubmitter.submitJobInternal(JobSubmitter.java:197)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1297)
    at org.apache.hadoop.mapreduce.Job$10.run(Job.java:1294)
    at java.security.AccessController.doPrivileged(Native Method)
    at javax.security.auth.Subject.doAs(Subject.java:422)
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1656)
    at org.apache.hadoop.mapreduce.Job.submit(Job.java:1294)
    at org.apache.hadoop.mapreduce.lib.jobcontrol.ControlledJob.submit(ControlledJob.java:335)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.pig.backend.hadoop.PigJobControl.submit(PigJobControl.java:128)
    at org.apache.pig.backend.hadoop.PigJobControl.run(PigJobControl.java:205)
    at java.lang.Thread.run(Thread.java:748)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher$1.run(MapReduceLauncher.java:301)
Caused by: org.apache.hadoop.mapreduce.lib.input.InvalidInputException: Input path does not exist: hdfs://localhost:54310/home/srv-hadoop/data.txt
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:321)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.listStatus(FileInputFormat.java:264)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigTextInputFormat.listStatus(PigTextInputFormat.java:36)
    at org.apache.hadoop.mapreduce.lib.input.FileInputFormat.getSplits(FileInputFormat.java:385)
    at org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.PigInputFormat.getSplits(PigInputFormat.java:280)
    ... 18 more

Input(s):
Failed to read data from "/home/srv-hadoop/data.txt"

Output(s):

Counters:
Total records written : 0
Total bytes written : 0
Spillable Memory Manager spill count : 0
Total bags proactively spilled: 0
Total records proactively spilled: 0

Job DAG:
job_local1897657638_0001    ->  null,
null    ->  null,
null

2017-07-25 17:05:07,622 [main] INFO  org.apache.pig.backend.hadoop.executionengine.mapReduceLayer.MapReduceLauncher - Failed!
2017-07-25 17:05:07,624 [main] ERROR org.apache.pig.tools.grunt.Grunt - ERROR 1066: Unable to open iterator for alias student_order
Details at logfile: /home/srv-hadoop/pig_1500995099397.log
2017-07-25 17:05:07,648 [main] INFO  org.apache.pig.Main - Pig script completed in 8 seconds and 442 milliseconds (8442 ms)

I get :
Input(s):
Failed to read data from "/home/srv-hadoop/data.txt"

Output(s):

Counters:
Total records written : 0
Total bytes written : 0
Spillable Memory Manager spill count : 0
Total bags proactively spilled: 0
Total records proactively spilled: 0

Job DAG:
job_local1897657638_0001    ->  null,
null    ->  null,
null

Bit, if I execute : pig -x local data.pig --> it works fine
I missed something ?

A: Hey It seems that your 'data.txt' is on your local file system. When you run 'pig -x mapreduce' it expect input to be in hdfs.
Since  '/home/srv-hadoop/data.txt' file is on local file system your 'pig -x local ' is working.
make directory on hadoop filesystem:

*

*hadoop fs -mkdir -p /home/srv-hadoop/

copy your data.txt file from local to hadoop

*hadoop fs -put /home/srv-hadoop/data.txt /home/srv-hadoop/

now run you pig in mapreduce mode. It will work fine

A: You have 6 fields in your file and the schema that you have specified has only 5 fields.You have another field after lastname,age perhaps.Modify your load statement like below.
student = LOAD '/home/srv-hadoop/data.txt' USING PigStorage(',')   as (id:int, firstname:chararray, lastname:chararray,age:int, phone:chararray, city:chararray);

A: You can try this: pig -x mapreduce file://data.pig


text:
Q: Pass PHP Variables to Ajax and post them How would I pass a PHP variable to AJAX I've tried using var sStr = "<?php echo $game ?>."; It will print it out ok but i cant get it to POST it to a PHP File. Here is my Code.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<?php
$game=$_GET['id'];
?>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
  $("button").click(function(){
    $.post("php.php",
    {
      game:"<?php echo $game; ?>",
      city:"Duckburg"
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>
</head>
<body>

<button>Add to Favourites</button>

A: Try to call the button by an ID and filter the quotes with addslashes
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<?php
$game = $_GET['id'];
$game = addslashes($game);
?>
<script language="javascript" type="text/javascript">
$(document).ready(function(){
  $("#button").click(function(){
    $.post("php.php",
    {
      game:"<?=$game?>",
      city:"Duckburg"
    },
    function(data,status){
      alert("Data: " + data + "\nStatus: " + status);
    });
  });
});
</script>
</head>
<body>

<button id="button">Add to Favourites</button>


text:
Q: Javascript Factorialize returns incorrect result Just wondering if anyone can tell me why this returns 100 and not 120? It should calculate the total number of the factor.
function factorialize(num) {

  for(var i = 1; i <= num; i++ ) {
    var fact = i+i;
    total = fact * fact;
  }
  return total;
}

factorialize(5);

A: This is not the correct way to calculate the factorial. What is happening in your code is, the last time the line total = fact * fact; is run, fact has a value of 10 (because i is 5), so 10 * 10 becomes 100 and that is what it returns.

A: TLDR is you're overwriting all the values of fact. var is scoped to a function in JS. Eventually you reach i = 5, which eventually sets fact to (5+5) * (5+5) which is 100.

A: If you are trying to calculate the factorial, use this code:
function factorialize(num) {
  var total = 1; // Initialize the total. 0! = 1.
  for(var i = 1; i <= num; i++ ) {

    total = total * i; // Add the current index to the factors by multiplying it by the current total.
  }
  return total;
}


text:
Q: BackgroundUploader for Xamarin.Forms C# I am working on converting my WindowsPhone project to Xamarin.Forms project.
I had a BackgroundUploader task for uploading my video files to server in background. However, I am not able to find a similar class in Xamarin Forms that does the same job.
Below is my BackgroundUploader code for WindowsPhone project.
Any kind suggestions please.
BackgroundUploader bguploader = new BackgroundUploader();
bguploader.SetRequestHeader(RequestHeader, jsonConverter.Serialize(Video));

UploadOperation upload = bguploader.CreateUpload(new Uri(url), videoFile);
Progress<UploadOperation> callback = new Progress<UploadOperation>(UploadProgress);
await upload.StartAsync().AsTask(canceltoken.Token, callback);

A: This is definitely a OS-specific functionality and it has no built-in solution in Xamarin.Forms.
As you mentioned BackgroundUploader is the solution working for UWP and Windows Phone.
For some info on iOS background execution check out the documentation. You will probably use NSURLSessionUploadTask.
On Android you should look into Background Services. See Android documentation.
To implement this in a cross-platform manner, you will have to create a shared interface and then provide platform-specific implementations. See Xamarin.Forms DependencyService for more details.


text:
Q: Mocking RestTemplate.exchange() gives URI is not absolute exception I am trying to mock this service that calls an API using rest template and returns a List.
I am unable to mock the restTemplate.exchange() method. It's giving me a "java.lang.IllegalArgumentException: URI is not absolute" exception.
edit- My stupid self forgot to put http:// before the base url in the test case and that is why I was getting that. Thanks for helping and apologies for wasting your time.
Method to be tested
@Value("${base-url}")
private String baseUrl;

@Override
public List<Currency> getCurrencyList() {
    RestTemplate restTemplate = new RestTemplate();
    String url = baseUrl + "/currency";
    ResponseEntity<List<Currency>> result;
    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
    HttpEntity<String> dataHttpEntity = new HttpEntity<>(headers);
    log.info(url);
    result = restTemplate.exchange(url, HttpMethod.GET,dataHttpEntity, new ParameterizedTypeReference<List<Currency>>() {
    });
    return result.getBody();
}

The Testing code
@Test
public void getCurrencyListTest() {
   ResponseEntity<List<Currency>> result = ResponseEntity.ok(currencyList);

    when(restTemplate.exchange( ArgumentMatchers.anyString(),
            ArgumentMatchers.any(HttpMethod.class),
            ArgumentMatchers.any(),
            ArgumentMatchers.<Class<List<Currency>>>any())).thenReturn(result);
     assertEquals(currencyList,service.getCurrencyList());
}

Exception
java.lang.IllegalArgumentException: URI is not absolute

at java.net.URI.toURL(URI.java:1088)
at org.springframework.http.client.SimpleClientHttpRequestFactory.createRequest(SimpleClientHttpRequestFactory.java:145)
at org.springframework.http.client.support.HttpAccessor.createRequest(HttpAccessor.java:87)
at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:721)
at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:682)
at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:627)
at com.fpts.seller.service.external.impl.DocumentServiceImpl.getCurrencyList(DocumentServiceImpl.java:34)
at com.fpts.seller.service.external.DocumentServiceImplTest.getCurrencyListTest(DocumentServiceImplTest.java:105)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:78)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:84)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:39)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:161)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)

A: Give a protocol name for your baseUrl and try again please, i mean by protocol is : http or https .
For example:
String url = "http://" + baseUrl + "/currency";

A: As per exception URL is not valid due to ArgumentMatcher.anString(). You should provide absolute url.


text:
Q: How to generate .sas in SAS data Integration Studio Since i want to schedule a job in SAS-DIS. i tried the process using sas management console,but an error is popping up saying scheluing server not found. and  scheduling server is an extra package that has to be purchased.
and because of that i need running on crontab on linux.
Do i need to export my job in SAS Data Integration Studio into format .sas or i can execute using .spk file format ?
if yes, i need to generate into .sas format . Please tell me how to generate that format. since i can't convert it ? Thank you.

A: A ´*.pkg ´ file contains much more information than your SAS code. It also contians information on the transformation and option you used as well as the graphical layout of your job.
A simple way to grab your SAS code is to open the properties of your job and select the tab with the code. However, that is not the way you should do it to schedule your job.
What you should do, is to create a "Deployed Job" object from your job. This has the advantage that your successor, or you when you come back to the project in a year, kan find out where you deployed the code today.


text:
Q: Is it possible to have nested striping (besides RAID10) in LVM? I want to put one RAID on top of other RAIDs. This can easily be done with MDADM by using an existing MD device as one of the members for the new MD device. Similar functionality could probably be achieved by "putting" a PV on top of an LV, but LVM seems to discourage this and there seems to be a much more elegant solution with "SubLVs". This is even done with the RAID10 "level", but is seemingly not possible with arbitrary stacked RAID levels.
Ultimately I want to use multiple smaller hard drives with larger hard drives in the same RAID. Previously I did this with a combination of MDADM and LVM by using MD devices as PVs in the top-most LVM RAID, but I'm hoping there's a solution using only LVM.


text:
Q: C# to C++ Translation I am coming towards the end of a project that I created in C#. Unfortunately, the target hardware only comes with compilers for C/C++. My dad is an embedded programmer so he will be making the necessary code to integrate with the hardware, but in the meantime I need to find a way to translate the language. Free translators are a very high preference as I am extremely tight on funds at the moment.
While I am not fluent in C++, with a dirty translation I should be able to figure out most of what is required to make it run.
Edit:
The target platform is mbed Microcontroller

A: There is no 1 to 1 mapping from c# to c++. The programming model and platforms are very different at the lower levels. Take memory management for example.
Your best chance is either to rewrite your application or try to get .NET Compact Framework or .NET Micro Framework to run in the hardware.
Edit:
Note that at least the .NET Micro Framework has a porting kit if your hardware is not supported.

A: Since design is half the battle in application development, your C# prototype should serve you well, but you are unlikely to find a suitable automatic translation tool. If you have not made heavy use of the .NET class library, especially those parts that relate to the underlying OS API, C# should be easily manually translated to C++.  The code body syntax and semantics are very similar; it is the enclosing structural elements such as class definitions that are more different.
The required effort depends on the size of the application code, but much of that is mechanistic.  The biggest difference being that you need to be more careful with memory management in C++ since there is no automatic garbage collection.

A: Learn C or C++. There are no alternatives.
Both languages are radically different from C# and .NET, and automatic conversion is not possible. (and if it were, it certainly wouldn't allow you to "figure out most of what is required to make it run". It would be completely unrecognizable code, that'd be impossible to read or extend.)
In order to write a working C or C++ program, a C or C++ programmer needs to write the code. The good news is that it doesn't have to be that difficult. You don't have to learn every corner of the C++ language. But you do need to learn the basics.
If you're looking for the quick and dirty way to get off the ground, learning C might be a better option, because the language is so much smaller and simpler. But C++ is doable too. Just don't think you can get away with reading a 15-minute online tutorial.

A: Don't. This will not work.
C# has a garbage collector. C and C++ don't. You will have to rethink how you allocate objects and release them in C++.
Chances are, since you already have completed the project, rewriting it in C/C++ will be quite easy. You already understand the problem and have expressed it once before.

A: There are no translators.
The .NET Micro Framework has been ported to a Phycore LPC3180 (NXP) platform that is not to dissimilar to your board so it can be done but you still need to port the .NET framwork to your platform.
It is unlikely that you will be able to use Mono AOT unless you are going to port Meamo to to your mbed board.
Any porting would require you to be able to program C code.
The best and fastest way forward would be for You to learn C++.
The differences between C++ and C# are not to big once you get going with C++ and understand the differences. You also going to have to use the mbed library for your hardware control and communications instead of what is provided by C#.
The C# code was a good prototype to debug your program design but it is not going to help you on the target. Now that you understand the problem it should not be to hard.

A: I'm not sure how you got this far without realising that the target platform couldn't run .NET, but it might be worth seeing if Mono's Ahead-of-Time compiler is able to output to your target platform.
At least then you wouldn't be throwing out (months of?) code.

A: Since you wrote the application in a garbarge-collected language, the fastest way to port this to an mbed platform should be to port the application to a garbage-collected language which runs on mbed.
I haven't tried it, but eLua is supposed to have a preliminary port which runs on the mbed platform, and Lua is fairly simple to learn.
   http://mbed.org/users/jsnyder/notebook/elua-preliminary-port/
If you can get your dad to bring up eLua on the mbed platform, I suspect you could do the conversion fairly easily compared to trying to convert your application to C++.

A: Port the code manually, and as you do, you will learn C++. :D


text:
Q: The figure will be elongated when adjust Axes3D.set_zlim from mpl_toolkits.mplot3d import Axes3D  # noqa: F401 unused import

# setup the figure and axes
bottom=np.zeros_like(xx)
fig = plt.figure(figsize=(15, 8))  # 画布宽长比例
ax1= fig.add_subplot(111, projection='3d')
# ax2= fig.add_subplot(132, projection='3d')
# ax3= fig.add_subplot(133, projection='3d')

ax1.bar3d(xx-0.5, yy+0.5, bottom,0.7 , 0.7, z3, color=C3,shade=True)
# ax1.set_xticks([i+0.15 for i in xx])
ax1.set_xticklabels(labels)
ax1.set_yticklabels(labels)
# the adjust operation is here
# ax1.set_zlim(bottom=0.8,top=1.0)
ax1.set_title("ARI")
plt.savefig("1.png")

before I adjust zlim,the figure is showing as follow,

but!! I uncomment the ax1.set_zlim(bottom=0.8,top=1.0), the figure change as follow,

If I wanna to erase the bottom of image, what should I do?

A: The solution is following
#change the bard3d to this
ax1.bar3d(xx-0.5, yy+0.5, z3,0.7 , 0.7,-(z3-0.9), color=C3,shade=True)

because bar3d(x,y,z,w,h,d),x,y,z deside the coordinates at the bottom of the cylinder ,when z=z3( float list), then we need set to be a negative number.


text:
Q: Which process should I allow in the Windows Firewall to make local network access possible (e.g. \\MyRouter\USBDevice\) Which .exe process is responsible for the Windows Explorer to have access to the local network, i.e. when you go in Explorer, and you browser for example \\Livebox\movies?
I need to whitelist this .exe at the Firewall level (see context below), but I first need to know which .exe it is.
Note:

*

*netsh advfirewall firewall add rule name="local-network-explorer" dir=out action=allow program="C:\Windows\explorer.exe" did not work

Context: I disallow all inbound/outbound connections by default in the Windows Firewall, and when I (rarely) install a new program that I'd like to have access to internet, I just do this in command line:
netsh advfirewall firewall add rule name="Chrome" dir=out action=allow
                  program="C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"

as stated in How to block everything (all incoming and outgoing internet access) except those applications are in firewall white-list?.
I know it is a bit extreme, but it has the advantage that no program that I wouldn't have actively whitelisted can send data outside.
I've done it for Chrome, Firefox, a SFTP program, a few others, and also for core DNS and DHCP:
netsh advfirewall firewall add rule name="Core Networking (DNS-Out)" dir=out action=allow protocol=UDP remoteport=53 program="c:\windows\system32\svchost.exe" service="dnscache"
netsh advfirewall firewall add rule name="Core Networking (DHCP-Out)" dir=out action=allow protocol=UDP localport=68 remoteport=67 program="c:\windows\system32\svchost.exe" service="dhcp"

and so far it has always been successful.

A:
Which .exe process is responsible for the Windows Explorer to have access to the local network, i.e. when you go in Explorer, and you browser for example \\Livebox\movies?

None.
Windows Explorer doesn't explicitly make the network connections – it relies on UNC path support that is made available to all programs. That is, as soon as any process accesses \\foo\bar as a file, the request will be transparently sent through a shared connection maintained by the OS.
Although the "LanmanWorkstation" service is somehow involved in SMB connections, ultimately they're owned by a kernel driver and have no associated userspace process. (Various tools might show them as belonging to PID 4 aka "System", which is the Windows kernel.)
Windows Firewall already comes with a built-in rule "File and Printer Sharing (SMB-Out)" which is already set up for this purpose (the wf.msc GUI shows "System" as the configured program path).

Note that before the connection can happen, the Livebox hostname needs to be resolved to an IP address. If you rely on DNS or LLMNR, both are handled by the "Dnscache" service. NetBIOS name resolution however is also handled through LanmanWorkstation by the kernel SMB driver.


text:
Q: In side the loop if the id is 09 (ex: f132a09) it will skip that student but process all other students I know i need to use continue but just don't know where to start. Any help would be appreciated.
Not looking for an answer, just a clearer understanding
Here's my code so far
prefix=$1

for id in $(grep "^$prefix" /etc/passwd | cut -d: -f1 | sort)
do

 echo -e "$(grep "^${id}:" /etc/passwd | cut -d: -f5 |  sed "s/^\(.*\), \(.*\)$/\2 \1 /g") \c"
    echo -e " has the cisweb id ${id}"
    if who | grep "^${id} "  > /dev/null
    then
    echo -e  "$(grep -w  "^$prefix"  /etc/passwd |  cut -d: -f5 | uniq |  sed 's/^\(.*\), \(.*\)$/\2 \1 /g'            )is currently logged  on"

  fi

done

I've tried several Mods but o luck.


text:
Q: Symlinks from /home subdirs to mount drive break on reboot My Kubuntu workstation has an SSD and an HDD. The SSD contains the Kubuntu installation, while I would like to use the HDD for general storage where drive speed is not a concern.
I have the HDD mounted via /etc/fstab using:
UUID=... /mnt/hdd ext4 defaults 0 2
I created symlinks for some of my /home subdirs to the HDD using:
ln -s /mnt/hdd/Downloads/ ~/Downloads
This creates the desired outcome - e.g. Firefox downloads will downloaded to /mnt/hdd/Downloads on the mounted HDD partition instead of the SSD. This is not the only use-case intended for this. The intention is for directories like Downloads and Documents to be stored on the mounted HDD, while appearing to be in their default /home locations (both to applications and to myself).
However, when I reboot, this symlink breaks with the following result:
$ ls -l ~
...
Downloads -> /mnt/hdd/Downloads/
...

$ ls -l /mnt/hdd/
...
Downloads -> /home/<username>/../../../../../mnt/hdd/Downloads
...

I'm not sure why /mnt/hdd/Downloads would turn into a broken symlink on reboot.
This is a fresh install with no other symlinks set.
Am I doing something wrong here?
Edit: After some experimentation, I've found that this behavior is not consistent. Sometimes a symlink will break, and sometimes it won't. I've had cases where out of 5 symlinks, only 1 or 2 will be broken on reboot.

A: Something very strange is going on at /mnt/hdd/Downloads, if the output you pasted is correct.
Specifically the output
$ ls -l /mnt/hdd/
...
Downloads -> /home/<username>/../../../../../mnt/hdd/Downloads
...

This looks like the path /mnt/hdd/Downloads is a symlink to... um... start at /home/Zach, go back up to /home, got up to root ('/'), go up again, again... again... (which will just stay at the root), then navigate downward to /mnt/hdd/Downloads
So first off, it looks like /mnt/hdd/Downloads must have been created incorrectly, and appears to be a circular link to itself.
What do you get from mount | grep /mnt/hdd? If it shows your drive, then it seems like your /etc/fstab is working fine. If it's blank then your drive isn't mounted.

If the drive is mounted
Your previous Downloads are probably lost, sorry.
The best I can suggest at this point is to unlink /mnt/hdd/Downloads to remove the circular symlink and then re-create a proper Downloads directory with mkdir -p /mnt/hdd/Downloads (the flag -p is likely not necessary for the Downloads directory here, but may be necessary for other directories).

If the drive isn't mounted
Remove any and all files from the path /mnt/hdd/ (if the drive wasn't mounted, then that path is actually on your SSD, not on the HDD) using the commands
sudo mv /mnt/hdd /mnt/hdd.bkup; sudo mkdir -p /mnt/hdd
Then run sudo mount -a and verify whether or not the drive is mounted now. If it's not, then you'll need to fix /etc/fstab.
Assuming things went well, you can then mkdir -p /mnt/hdd/Downloads as above.

The real problem
I have to do some inferring here, but the fact that you have a link of the form /mnt/hdd/Downloads -> /home/<username>/../../../../../mnt/hdd/Downloads looks very wrong.
You mentioned that you created symlinks by running ln -s /mnt/hdd/Downloads/ ~/Downloads.
The problemmatic path suggests you probably ran the ln command with the arguments in the wrong order at some point, or from the wrong directory at some point (e.g. ln -s ~/Downloads /mnt/hdd/Downloads).
Depending on when this happened, it could have placed a symlink at the path /mnt/hdd/Downloads on your SSD which would prevent the hdd from correctly mounting. In that case, follow the instructions for "If the drive isn't mounted"
You can get some more info about which drive a file is on with df /mnt/hdd/Downloads, but those details don't seem totally important to this problem.

One last note
This strange behavior doesn't look like it has anything to do specifically with rebooting Linux. If your ln command is being run by a script (at reboot or whenever), then you need to provide details about that script, as it is the most likely culprit.


text:
Q: Check if column name exist in mysql table i want to check if a particular column is present in my table or not. if it does not exist i want to add it using C programming language.
i tried following code:
mysql_query(sqlhnd, "SELECT * FROM my_table");
MYSQL_RES *confres = mysql_store_result(sqlhnd);
int totalrows = mysql_num_rows(confres);
int numfields = mysql_num_fields(confres);
MYSQL_FIELD *mfield;

while((row = mysql_fetch_row(confres)))
{
    for(i = 0; i < numfields; i++)
    {
        char *val = row[i];
        // do something with val...
    }
}

i want to compare val with the column name for example:
if( !strcmp(val,"column")) { create the column using alter table }

i am unable to do this part of the code

A: There are some ways in MySQL, but I omit the C code here:

*

*Do a desc my_table and look for your column in the output.

*Simply select your_col from my_table limit 1 and look for a real error (not an empty set)

*Do SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA='your_db' AND TABLE_NAME='my_table';
I'd prefer the 3rd option. It gives you a list of all column names of your particular table. I think with your attempt you don't get the column names but only their content.


text:
Q: Breaking horizontal layout of inline-blocks in CSS I have many LI that I am laying horizontaly using inline-block.
It works very nice, and I see
| [LI1]-[LI2]-[LI3] |
| [LI4   ]-[LI5]    |
| [LI6]-[LI7]-[LI8] |

on my browser, depending on the window width and the width of the individual LI's.
I would like that after some LIs, the "line breaks". For example, putting a "linebreak" after LI2, I would see
| [LI1]-[LI2]       |
| [LI3]-[LI4   ]    |
| [LI5]-[LI6]-[LI7] |
| [LI8]             |

Of course, it could be that LI3 breaks the line too.
I have full control over the CSS for every LI.
Thank you!

A: I wouldn't do this with a CSS trick - I'd modify my HTML to reflect the structure of the list you want to display.
Here you could say that each horizontal set of
 is its own
. So you have a list of lists.
Check this JsFiddle.
This way you get your result without the behaviour being hidden in some CSS, and it's easy to see what's happening in your markup.
EDIT: Ok since you can't touch the HTML, you can float all your
 to the left, then make the first
 on each row clear:left. See this edit to the JsFiddle...

A: If you want a specific element to "line break" you just need to add a clear.
.myelement {
  clear: both;
}

Hi

There

Neighbor!

Elements naturally migrate to the left.  If all the elements are set to float: left, they will all migrate to the left and then break each time they run out of room.  clear:both; makes them be the only item on that line.


text:
Q: If $m=\omega(N log N)$, then what is the order of $N$ in terms of $m$?
Assume $m=\omega(N \log N)$. What is the order of $N$ in terms of $m$?

My answer: I found that if $N=m^{1-a}$ where $0<a<1$, then $m=\omega(N \log N)$ holds. But, I think this is not a good representation.
Then I thought of Lambert $W$ function. I think we can say $\log{N}=o(W(m))$ thus $N=o(e^{W(m)})$. But, I need more simplification.  I should know the asymptotic behavior of $W(m)$ as $m \to \infty$. Any idea?

A: $N$ is of order
$\dfrac{m}{\log m}$.
To see this,
$\begin{array}\\
N \log N
&=\dfrac{m}{\log m} \log(\dfrac{m}{\log m})\\
&=\dfrac{m}{\log m} (\log(m)-\log \log m))\\
&=m-\dfrac{m\log \log m}{\log m}\\
&=m(1-\dfrac{\log \log m}{\log m})\\
&=m(1-o(1))\\
\end{array}
$

A: Take any variables $m,N \ge 0$ such that $m \in ω(N \log(N))$ as $N \to \infty$.
$
\def\lfrac#1#2{{\large\frac{#1}{#2}}}
$
Given any constant $c > 0$:
  As $m \to \infty$:
    If $N > c \cdot \lfrac{m}{\log(m)}$:
      $N \to \infty$.
      $m \ge \lfrac2c \cdot N \log(N) > 2 \lfrac{m}{\log(m)} ( \log(m) - \log\log(m) + \log(c)) > m$.
        [since $2 \log(m) > \log\log(m)$ as $m \to \infty$]
      Contradiction.
    Therefore $N \le c \cdot \lfrac{m}{\log(m)}$.
Therefore $N \in o(\lfrac{m}{\log(m)})$ as $m \to \infty$.

If it is not clear why the above proof is valid, you can translate it as follows. If there is a sequence of points for which $m \to \infty$ but $N > c \cdot \lfrac{m}{\log(m)}$, then $N \to \infty$ for that sequence, and we will get a contradiction in exactly the same way. Therefore given any sequence of points for which $m \to \infty$, eventually $N \le c \cdot \lfrac{m}{\log(m)}$.


text:
Q: SQL Server 2008 create trigger that set columns of a table to null after deleted row in another table Suppose I have 2 tables:
T1                  T2
--------------      --------------------
id  name            ver lyr1    lyr2
--------------      --------------------
1   apple           1   1   1
2   banana          2   1   2
3   orange          3   3   3
4   peach           4   2   3
                    5   1   4

I want to update lyr1 and lyr2 values to null whenever a row is deleted in T1. So when id = 3 is deleted, result would be
T1                  T2
--------------      --------------------
id  name            ver  lyr1   lyr2
--------------      --------------------
1   apple           1    1      1
2   banana          2    1      2
4   peach           3    null   null
                    4    2      null
                    5    1      4

Here's what I have so far:
CREATE TRIGGER trigDelFruit on T1
AFTER DELETE
AS
BEGIN
    SET NOCOUNT ON;

    UPDATE T2
    SET lyr1 = NULL, lyr2 = NULL
    FROM T2
    JOIN DELETED ON lyr1 = Deleted.id AND lyr2 = Deleted.id
END

A: --You cannot set particular columns set by this method. but you can achieve the same using "case when" statement.
CREATE TRIGGER trigDelFruit on T1
   AFTER DELETE
   AS
   BEGIN
   SET NOCOUNT ON;
   declare @id int;
   select @id=id from deleted;
   update T2 set
   lyr1=case when lyr1=@id then null else lyr1 end
   ,lyr2=case when lyr2=@id then null else lyr2 end;
   END


text:
Q: Matlab transfer functions I used the "c2d" to discretize a transfer function initially but MATLAB automatically took it as zero order hold because I didn't specify any kind of hold. The result for the zero order hold is different from the expected result. I'm not trying to use any hold in my discretization. Is there a way I can do this?

A: Read the documentation
https://www.mathworks.com/help/control/ref/c2d.html
and figure what discretization method you want, since you clearly don't want zoh

sysd = c2d(sysc,Ts,method)

The following methods are available, and each will have its pros and cons:

*

*zoh

*least-squares

*matched

*tustin

*impulse

*foh


text:
Q: String to array nodejs I format a string (I can format the string in any way)
e.g
   id1:234,id2:4566,id3:3000

then encrypt it and pass via query string
   ?qs=djdjdjfjf57577574h33h3h3hh3h3

then decrypt it on node
   id1:234,id2:4566,id3:3000

which is the best method to format the string and then turn it into an array in node
    arr[id1] = "234";
    arr[id2] = "4566";
    arr[id3] = "3000";

A: I think you would like to use hashmap (object) instead of array:
var obj = {}
then try:
"id1:234,id2:4566,id3:3000".split(",").forEach(function(e){
    var record = e.split(":");
    obj[record[0]] = record[1];
})

which give you:
{id1: "234", id2: "4566", id3: "3000"}

A: Firstly, what you have as your object model is more of a hash like object or simply a JavaScript object with keys and values, so the best way to do that is simply using JSON.parse.
So if you can do it as you said: I can format the string in any way, you better first change your formatting to have something like:
'{"id1":234,"id2":4566,"id3":3000}'

instead of :
id1:234,id2:4566,id3:3000

you can do it using JSON.stringify on the client side JavaScript using a JavaScript object without you needing to deal with string formatting:
//on the client side
var myObj = {};
myObj.id1 = 234;
myObj.id2 = 4566;
myObj.id3 = 3000;
var objStr = JSON.stringify(myObj);

let's say you encrypt your string using a function named encrypt:
var encryptedStr = encrypt(objStr);
//so now you should use encodeURI to be able to put it in the queryString
var queryStringParam = encodeURI(encryptedStr);

now you put the queryStringParam in the queryString.
Then on the node.js side, all you should do is parsing it as a JSON object. The other important point that you probably have considered doing it is using decodeURI. For the last step, let's say you are using e function named decrypt:
//the server-side code
var decryptedStr = decrypt(decodeURI(yourQueryString));
var obj = JSON.parse(decryptedStr);

Now obj is exactly what you want.


text:
Q: How do I sort a csv file so that my columns are in descending order? I'm trying to sort my CSV file so that the teams with the most gold, silver and bronze medals are at the top of the list and those with the least are at the bottom.
def rank_team(file_name):
import csv

file = open('medal.csv')
for line in file:
    print(line)

pass

rank_team('medal.csv')

This is the code that I have now. Just wondering how I would sort it all.
This is the CSV that I'm using.
CSV used to sort

A: you can use sorted function with key condition.
if you want to sort ascending [Gold,Silver,Bronze], then this code will help you.
import csv

def rank_team(file_name):
    with open('medal.csv') as f:
        reader = csv.reader(f)
        header = next(reader)
        data = [row for row in reader]
    print(header)
    print(sorted(data, key=lambda x: (x[1], x[2], x[3])))

rank_team('medal.csv')

A: Using the csv.reader and csv.writer functions, as well as sorted with a tuple key:
import csv

with open('medal.csv', 'r') as in_file:
    in_reader = csv.reader(in_file)
    header = next(in_reader)
    data = sorted(in_reader, key=lambda row: tuple(int(x) for x in row[1:]), reverse=True)

with open('sorted_medal.csv', 'w', newline='') as out_file:
    out_writer = csv.writer(out_file)
    out_writer.writerow(header)
    out_writer.writerows(data)

Result:
# Input: medal.csv
team,gold,silver,bronze
t1,17,12,38
t2,8,7,29
t3,17,11,39
t4,17,12,37
t5,8,9,30

# Output: sorted_medal.csv
team,gold,silver,bronze
t1,17,12,38
t4,17,12,37
t3,17,11,39
t5,8,9,30
t2,8,7,29

A: You can use pandas for this. Read the csv as a pd.DataFrame and use sort_values method:
import pandas as pd
df = pd.read_csv('medal.csv')
df = df.sort_values(by=['Gold','Silver','Bronze'], ascending=False)

Note: What you describe is descending order.

A: Here a link that might help you . Change the 3 by 0 since you want to use the first column.