text:
Q: Implementing cookies with JS to recognize returning visitors I have a blog with locked content. User needs to enter their email address into a form in order to see the full content.
Problem now is that the same user has to enter their email on every post. How do I implement cookies so that:
1) on a form submit, user gets a cookie
2) on a blog page load, check to see if cookie exists, and if it does, load the full content
--
I have minimal experience using cookies. Thanks!

A: Cookies on the client will not give you the protection you seek because anyone with a browser could insert these cookies themselves. Moreover - client-side security over server-side content (the articles) inherently doesn't work. Any clever user will be able to get over any form of security measure that is not on the server.
That said, if you're entirely OK with users who do not install a specific extension or run a specific script to "unlock" your site - you can do something along the lines of:
if(document.cookie.indexOf("entered_email=true") === -1){
     // show email request field
} else {
     // show content
}

And when the user enters their email:
document.cookie += (document.cookie ? ";" : "") + "entered_email=true";

A: You could probably use the localStorage object for this:
HTML:
<input type="text" id="email"/>
<input type="button" id="submit" value="submit"/>

JS:
$(document).ready(function(){
    if (localStorage.getItem("email")){
        $("#email").val(localStorage.getItem("email"))
        // unlockContent();
        // otherStuff();
    }
    $("#submit").click(function(){
        localStorage.setItem("email", $("#email").val());
        alert("Saved: " + localStorage.getItem("email"));
        // unlockContent();
        // otherStuff();
    })
})

Fiddle: here.
edit: but as Benjamin mentioned in his answer, this is not really a secure mechanism -- unless you simply want to verify an email rather a particular email.

A: Creating JS cookies on the front-end is simple:
document.cookie="email=foo@bar.com";

Which creates a cookie named "email" that has a content of "foo@bar.com."
When a user goes to your site again, you can check whether the cookie exists.
if (document.cookie.indexOf("email")>=0) {
    // Log them in!
}
else {
    // Show log-in field!
}

You might also want a cookie to expire after a certain period of time. When you create a cookie, you can set an expire date:
document.cookie="email=foo@bar.com;expire=06/12/2015";

However this isn't as secure as using sever-side cookies.


text:
Q: Winnovative Hides Text of TextElements on PDFs There is a group somewhere in our organization that scans documents and converts them to PDFs.  They then associate those PDFs with an "event" record and store them in a database.  On demand, my application -- which uses Winnovative HTML to PDF v9.0.0.0 -- has to retrieve the PDFs associated with an event, place a header on the first page of each, and store them on the file system.  This header is a TextElement.
On some PDFs, the header displays beautifully.  On others, the header does not appear.  However, when viewing the PDF, the header can be "highlighted" with the cursor and its text successfully copied, so the header is indeed present and properly positioned.  (See the green arrow in the inserted image.)

I have identified two PDFs that were scanned by the same person thirty minutes apart and associated with the same event in the database.  On one, the header is displayed; on the other, it is not.  To investigate, I have set the BackColor of the TextElement to Crimson.  The Text appears and doesn't appear as before, but the TextElement always appears bright red.
The properties of the two Document and PDFPage objects are identical, including the TransparencyEnabled property.  This phenomenon is present in PDFs of all sorts of documents scanned by various people over time.  And it's not just this header TextElement, but TextElements everywhere on the PDF (e.g. Page X of Y, watermarks).  On a given PDF, if the Text of one is visible, the Text of all is visible, and vice versa.
I can find no pattern or explanation.  What could be causing some PDFs to "hide" the Text (and only the Text) of all TextElements that I put on them while others don't?
Private Sub AddTitleToFirstPage(ByRef pdf As Document)
    Dim headerSystemFont As New Font("Arial", 10)
    Dim headerFont As PdfFont = pdf.Fonts.Add(headerSystemFont)
    Dim headerTextElement As New TextElement(65, 20, "My Page Title", headerFont)

    headerTextElement.TextAlign = HorizontalTextAlign.Center
    headerTextElement.ForeColor = Color.DarkBlue
    headerTextElement.BackColor = Color.Crimson

    pdf.Pages(0).AddElement(headerTextElement)
End Sub

Friend Function UpdatePdfDoc(pdfBytes As Byte()) As Byte()
    Dim bytes As Byte()

    Using docStream As New MemoryStream(pdfBytes, 0, pdfBytes.Length)
        Dim returnDoc As Document = New Document(docStream)
        returnDoc.LicenseKey = WinnovativeLicenceKey

        AddTitleToFirstPage(returnDoc)

        bytes = returnDoc.Save()
        docStream.Close()
    End Using

    Return bytes
End Function

Friend Function GetEventObjectPdfSource(scannedDocIds As List(Of String)) As Object
    Dim scannedDocObjectPdfSourceList As New List(Of Byte())()

    For Each scannedDocId As String In scannedDocIds
        Dim scannedDocObjectPdfSource As Byte() = GetScannedDocBlobById(scannedDocId)
        scannedDocObjectPdfSource = UpdatePdfDoc(scannedDocObjectPdfSource)
        scannedDocObjectPdfSourceList.Add(scannedDocObjectPdfSource)
    Next

    Return scannedDocObjectPdfSourceList
End Function

Friend Function GetEventObjectPdf(eventId As String) As String
    Dim pdfFileName As String = GetPDFFileName(eventId)
    Dim scannedDocIds As List(Of String) = GetScannedDocumentsForEvent(eventId)
    Dim objectPdfSourceList As List(Of Byte()) = CType(GetEventObjectPdfSource1(scannedDocIds), List(Of Byte()))

    For Each objectPdfSource As Byte() In objectPdfSourceList
        Using docStream As New MemoryStream(objectPdfSource, 0, objectPdfSource.Length)
            Dim masterDoc As New Document(docStream)
            masterDoc.LicenseKey = WinnovativeLicenceKey

            Do While masterDoc.Bookmarks.Count > 0
                masterDoc.Bookmarks.Remove(0)
            Loop

            Try
                masterDoc.AutoCloseAppendedDocs = True
                masterDoc.Save(pdfFileName)
            Catch ex As Threading.ThreadAbortException
                Threading.Thread.ResetAbort()
            Finally
                masterDoc.DetachStream()
                masterDoc.Close()
            End Try

            docStream.Close()
        End Using
    Next

    Return pdfFileName
End Function

Please forgive the clunky code.  I didn't write it.  I just inherited it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why do some websites prevent you from using non-alphanumeric characters in your site password? I logged in to a website today and found this message:

As a part of new security systems upgrades, we are requiring all existing customers to change their password to enhance the protection of their private information.
  We recommend using a password which is easy for you to remember but difficult for others to guess. Please note the new password should be between 8 ~ 16 characters and special characters, "'", """, ";", "|", "?", "<", ">", "^", "*", ":", "=", and "#" are prohibited. Thanks for your understanding and cooperation.

16 characters is probably long enough, but I don't see a good reason for the length restriction.
More interesting to me is the disallowing of certain special characters.  There are still plenty of special characters available with this scheme, though I've heard of other sites that only allow alphanumeric characters.  Why should the content of my password matter to the hashing algorithm?  It's just a hash, or a base-64 encoding of that hash, right?

*

*Does this policy place the security of my account at risk?

*Is there a specific password handler can't deal with the character set ',";|?<>^*:=#?

*Should I be concerned about the security policies elsewhere on the site?

A: Almost certainly to stop people embedding code inside regular fields (a la SQL injection).

A: Because they did a crappy job of sql injection prevention.  I can almost understand not allowing ' and " (your grade goes from F to C) everything else is simply sloppy

A:
Should I be concerned about the
  security policies elsewhere on the
  site?

Yes, you should.
Because if they are able to know what characters are in your password, that means it's stored in plaintext in the database. And this is BAAAD.


text:
Q: what is the relation between change of variables in probability and calculus? I want to know if the change of variables formula in probability is a special case
of the change of variables in calculus, or something different.
Trying to think for myself, first write the CoV for probability within informal derivation,
$$
   p(y)dy = p(x)dx  \quad\Rightarrow\quad p(y) = p(x) \left| \frac{dx}{dy} \right|
$$
and I believe we could add integration to make it look more like the calculus case, though the answer is one
$$
 \int p(y) \, dy = \int p(x) \left|\frac{dx}{dy}\right| \, dx = 1
$$
Now writing the CoV for calculus, mulitidimensional form,
$$
\iint_\Omega f(g(p)) |J_g| \, dp = \iint_{g(\Omega)} f(p) \, dp
$$
and rewrite this to look like the probability case, $p\rightarrow x$
$$
\iint_\Omega f(y=g(x)) |J| \, dx = \iint_{g(\Omega)} f(x) \, dx
$$
move the $|J|$ to the other side, and name $f \rightarrow p$
$$
\iint_\Omega p(y) \, dx = \iint_{g(\Omega)} p(x) |J|^{-1} \, dx
$$
This does not quite look like the probability case, because on the left side it should be
$$
  \iint_\Omega p(y) \, \mathbf{d}y
$$
rather than
$$
  \iint_\Omega p(y) \, \mathbf{d}x
$$
Probably I made a mistake. Can anyone explain what the mistake is?
self studying


text:
Q: Angular UI Router separate files I'm trying to separate my routes into separate files but having problems getting it to load, but not getting any error information. This is in an Ionic tabs application which uses Angular UI Router.
My project is split into separate apps
main-routes.js
main-controllers.js
main-routes-end.js

app1
- routes.js
- controllers.js
app2
- routes.js
- controllers.js

Here are my routes JS files for the routes.
// main-routes.js
angular.module('myproj.routes', [])

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('tab', {
    url: '/tab',
    abstract: true,
    templateUrl: 'templates/tabs.html'
  })
});

// app1/routes.js
angular.module('myproj.routes', [])

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('tab.home', {
    url: '/home',
    views: {
      'tab-home': {
        templateUrl: 'templates/tab-home.html',
        controller: 'HomeCtrl'
      }
    }
  })
  .state('tab.odometer', {
    url: '/home/odometer',
    views: {
      'tab-home': {
        templateUrl: 'templates/home/odometer.html',
        controller: 'OdometerCtrl'
      }
    }
  })
});

// app2.js
angular.module('myproj.routes', [])

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('tab.messages', {
    url: '/messages',
    views: {
      'tab-messages': {
        templateUrl: 'templates/tab-messages.html',
        controller: 'MessagesCtrl'
      }
    }
  });
});

// main-routes-end.js
angular.module('myproj.routes', [])

.config(function($urlRouterProvider) {
  // if none of the above states are matched, use this as the fallback
  $urlRouterProvider.otherwise('/tab/home');
});

I've included these files in my index.html in the following order:
<script src="js/routes.js"></script>
<script src="js/app1/routes.js"></script>
<script src="js/app2/routes.js"></script>
<script src="js/routes-end.js"></script>

When I have all the routes in the js/routes.js file it works fine, but when I try to separate them out the screens don't render and unfortunately I don't get any errors in the console. I'm using a similar struture for controllers, which works fine, but I'm having problems with the routes. Any ideas?

A: Your main-routes.js should only have the module definition like angular.module('myproj.routes', [])
In other *.route.js you should js used the module create by the main-routes.js. No need to create a new module again & again.
Basically your problem is, you are reinitializing your myproj.routes module again & again which is flushing out old component(here its states) registered to it.
Make sure you create module once & Then you should use angular.module('myproj.routes') module to append the states to its config block.


text:
Q: Is it safe to have just C++17 compatibility in a project? I am starting a C++ project from scratch. Is it safe to solely support C++17? In other words, is it recommended for any functionality implemented in a C++17 way to have a corresponding functionality compatible with C++11 or C++14?

A: This has the notion of being opinion based but I think there is an objective view on this.
As a general rule I'd say, by the Ockham's Razor, it's bad to have different versions of the same functionality for whatever reason. Don't introduce it unless you have to. It's worse than copies.
Set for standard and be future ready - be ready to take on the new features once the target build infrastructure supports them, so that you can eventually deprecate and remove obsolete versions. There is a pretty good notion what's available in 3-6 years, so you can design your interfaces around it.
Providing backward standard compatibility is sometimes possible, but not always, and can be cumbersome. Assuming you start on some version and downgrade is a very risky idea.
You can't really say you use c++17 and provide backward compatibility, because it's impossible to do completely and keeping same interfaces.

A: What sort of software?
For example in a library or an application in a Linux distribution you have to deal with your consumers, and likely some of them will still be on older OS's and compilers, and not want to update. For libraries if you want to provide some with new features in the API while supporting old ones you may need some functionality behind macro's/compile options (e.g. std::string_view where supported and const std::string & otherwise). For applications id say stick to the lowest version required.
However for an application you distribute can use whatever version you want and bundle the dependencies. So you could use a newer version of the compiler than the system comes with, rebuild boost C++, etc., just make sure you either static link or bundle any DLL/so you need.


text: Q: Cannot set critical battery level to hibernate I cannot set the critical battery percentage before the laptop hibernates on Ubuntu 22.04 LTS; Linux 5.15.0-39-generic (x86_64). I cannot find options to set the critical level in /org/gnome/settings-daemon/plugins/power/.


text:
Q: trying to get unread message count with Microsoft graph on multiple emails I want to be able to get the number of unread emails for an specific name in my tenant.
Something like: https://graph.microsoft.com/v1.0/me/mailFolders/Inbox/messages?$filter=isRead ne false&$count=true]
but be able to change the me for an specific user, the above works in graph explorer for my signing user.
I tried this example here. Which bring me a list of users and was trying to modified it without success.
the app have api permission for microsoft graph to read mail in all mailboxes.

A: To access a users mailbox other than the signed in user. You will need to call the api with an application (app-only) token. This will require requesting application permissions (not delegate permissions) for Mail.Read.
More information on getting access without a user context is available here https://learn.microsoft.com/en-us/graph/auth-v2-service?context=graph%2Fapi%2F1.0&view=graph-rest-1.0
The request would be
GET https://graph.microsoft.com/v1.0/users/{id | userPrincipalName}/messages
You can use the id from calling
GET https://graph.microsoft.com/v1.0/users
or use the upn which is their email address in most cases that you may already have.
More documentation is available here https://learn.microsoft.com/en-us/graph/api/user-list-messages?view=graph-rest-1.0&tabs=http
You can actually test these request calls in our Postman collections. Graph Explorer is purely for on-behalf of flow request calls. Setup instructions are here https://learn.microsoft.com/en-us/graph/use-postman

A: I may be misunderstanding your question, but I think your trouble is you're replacing me in the URI with the user identifier. If that's correct, you need to replace it with user/useridentifier instead.
That would make the query:
https://graph.microsoft.com/v1.0/user/myemail@mysite.com/mailFolders/Inbox/messages?$filter=isRead ne false&$count=true

A: Just pass UserID in GET API
{{UserId}} - username/mailid/principalName

 https://graph.microsoft.com/v1.0/users/{{UserId}}/mailFolders/Inbox/messages?$filter=isRead ne true&$count=true


text:
Q: Setting delegate to the parent of pushed scene In my HelloWorldLayer code I am pushing a SettingsLayer scene onto the stack.
        [[CCDirector sharedDirector] pushScene:[CCTransitionFade transitionWithDuration:0.5 scene:[SettingsLayer scene]]];

The SettingsLayer needs to call a delegate method implemented in the HelloWorldLayer. But I am at a lost as to how I can set the HelloWorldLayer as the SettingsLayer's delegate. Can someone show me the proper pattern for this? I tried alloc-init of the SettingsLayer, and setting the delegate before the pushscene but this did not work.

A: In your code:
SettingsLayer *mySettingsLayer = [[SettingsLayer alloc] init];
mySettingsLayer.delegate = self;
[[CCDirector sharedDirector] pushScene:[CCTransitionFade transitionWithDuration:0.5
                                 scene:[[mySettingsLayer class] scene]]];

The problem is in the last line:
[[mySettingsLayer class] scene]

This creates a new instance of the SettingsLayer class which has no delegate set (it will be nil). The mySettingsLayer you created before isn't actually presented as a scene, it goes out of scope and deallocates (assuming you are using ARC, if not, this would actually leak the mySettingsLayer object).
To fix it pass in your already existing mySettingsLayer instance:
[[CCDirector sharedDirector] pushScene:[CCTransitionFade transitionWithDuration:0.5
                                 scene:mySettingsLayer]];


text:
Q: Asymmetric Least Squares Conversion from Equation to Matrix In solving for asymmetric least squares baseline correction as defined in the article by Eilers and Boelens, the general equation is defined as:
$$S = \displaystyle\sum_i w_i (y_i-z_i)^2 + \lambda \displaystyle\sum_i (\Delta^2 z_i)^2$$
The paper then immediately states "The minimization problems leads to the following system of equations:'"
$$(W + \lambda D' D)z = Wy$$
where $W = \operatorname{diag} (w)$ and $Dz = \Delta^2 z$.
The problem is that I really can't figure out this transition.  I understand that we set $S=0$, but the only way I see this solving the equation is if we modify the general equation to be:
$$S = \displaystyle\sum_i w_i (y_i-z_i) + \lambda \displaystyle\sum_i (\Delta^2)^2 z_i$$
There must be some way of clearing out the variables, but I can't figure it out.  (Thanks in advance for your help!)

A: If $W = \operatorname{diag} (w)$ is nonnegative, then the quadratic cost function can be written in the form
$$\begin{array}{rl} S &= \|W^{\frac{1}{2}} (y - z)\|_2^2 + \lambda \|D z\|_2^2\\\\ &= (y-z)^T W (y-z) + \lambda \, z^T D^T D z\\\\ &= \begin{bmatrix} y\\ z\end{bmatrix}^T \begin{bmatrix} W & -W\\ -W & W\end{bmatrix} \begin{bmatrix} y\\ z\end{bmatrix} + \lambda \begin{bmatrix} y\\ z\end{bmatrix}^T\begin{bmatrix} O & O\\ O & D^T D\end{bmatrix} \begin{bmatrix} y\\ z\end{bmatrix}\\\\ &= \begin{bmatrix} y\\ z\end{bmatrix}^T \begin{bmatrix} W & -W\\ -W & W + \lambda \, D^T D\end{bmatrix} \begin{bmatrix} y\\ z\end{bmatrix}\end{array}$$
Taking the gradient of $S$ with respect to $(y,z)$, we obtain
$$\nabla S = 2\begin{bmatrix} W & -W\\ -W & W + \lambda \, D^T D\end{bmatrix} \begin{bmatrix} y\\ z\end{bmatrix}$$
As the gradient must vanish at the minimum, we obtain the following linear system
$$\begin{bmatrix} W & -W\\ -W & W + \lambda \, D^T D\end{bmatrix} \begin{bmatrix} y\\ z\end{bmatrix} = \begin{bmatrix} 0\\ 0\end{bmatrix}$$
which yields the equation
$$(W + \lambda \, D^T D) z = W y$$
and also the equation $W y = W z$. Hence, $\lambda \, D^T D z = 0$.


text:
Q: Mapbox not loading streets and details: Failed to load mapbox://mapbox.mapbox-streets-v6 Just installed MapboxGL through cocoapods.
I initialize it in my ViewController like the example given:
 @IBOutlet weak var mapViewWrapper: UIView!

    var mapView: MGLMapView!

    override func viewDidLoad() {
        super.viewDidLoad()

        // Map
        let styleURL = NSURL(string: "asset://styles/dark-v7.json")
        mapView = MGLMapView(frame: mapViewWrapper.bounds, styleURL: styleURL)
        mapView.autoresizingMask = .FlexibleWidth | .FlexibleHeight

        // set the map's center coordinate
        mapView.setCenterCoordinate(CLLocationCoordinate2D(latitude: 38.894368,
            longitude: -77.036487),
            zoomLevel: 15, animated: false)
        mapViewWrapper.addSubview(mapView)

    }

When I launch the app, I see a black square and a Mapbox logo but no streets, see image below

In the logs I'm getting this:
[ERROR] {Map}[Style]: Failed to load [mapbox://mapbox.mapbox-streets-v6]:
[ERROR] {Map}[Style]: Failed to load [mapbox://mapbox.mapbox-terrain-v2]:

Any ideas what I did wrong?

A: Thanks for reporting this on GitHub, much appreciated. To close the loop here, this problem happened because the Mapbox iOS SDK was inappropriately caching requests made with bad access tokens, which tended to give vague errors that looked like connection issues.
Fixed in v3.1 by this.

A: This may have been an intermittent network or API problem? The usage looks right.


text:
Q: Is it possible to 'freeze pane' in WPF datagrid Is it possible with a WPF datagrid to do like in Excel and Freeze the first few columns so that they always appear
If so how ?
Thanks

A: You have the property FrozenColumnCount.
If you set it to 2 for example, then you can scroll the DataGrid horizontally but the first two columns will always be visible
<DataGrid FrozenColumnCount="2" ...>

A: Try: DataGrid.FrozenColumnCount.


text:
Q: The array return by func must be one-dimensional, but got ndim=2. How can we rectify the error Please provide the solution for this code - The array return by func must be one-dimensional, but got ndim=2
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import math
def scp(y,z):
dh=  0.07 #internal diameter(m)
tk = 0.002 #thickness of the absorber tube(m)
do = dh+ 2*tk #outer diamater of the absorber tube
kat = 45 #thermal conductivity of the absorber tube
usDPE =0.5 #velocity of the diphenyl-ether (m/s)
I = 800 #global insolation (W/m2K)
Cr = 25 #concentration ratio
nuo = 0.785 #optical efficiency
epsr = 0.095 #emissivity of the solar selcective coating
sigm =5.67*10**-8 #Stefan Boltzann constant
Pat= math.pi*dh #perimeter of the tube
Tsurr = 293
Tht=y[0]
B1=0.2336
B2=120.57
B3=-147.33
B4=7E-07
CpDPE=(1/(B1+(B2/Tht)+(B3/Tht**2)+(B4*Tht)))*1000 #Specific heat coefficient J/kgK
B5=1.33718
B6=-0.9233E-03
B7=-0.08992E-06
rhoDPE=(B5+(B6*Tht)+(B7*(Tht)**2))*1000  #Specific heat coefficient kg/m3
B8=0.0451
B9=0.0034
kDPE=B8*math.exp(B9*Tht) #Thermal conductivity of DPE (W/m.K)
D=4.832
mu0=0.063
T0=136.7
muDPE=math.exp(math.log(mu0)+((D*T0)/(Tht-T0)))/1000 #viscosity of DPE (kg/m.s)
ReDPE=(dh*usDPE*rhoDPE)/muDPE #Reynolds number of DPE
PrDPE=(CpDPE*muDPE)/kDPE #Prandtl number of DPE
NuDPE=0.023*ReDPE**0.8*PrDPE**0.4 #Nusselt number of DPE
hj=(NuDPE*kDPE)/dh #heat transfer coefficent of fluid
Uo= (hj*kat)/(kat+(tk*hj)) #Overall heat transfer coefficent of fluid
At= ((math.pi)/4)*dh**2 #Area of the tube
mDPE = rhoDPE*usDPE*At #mass flow rate of DPE
ppar = [(epsr*sigm),0,0,Uo,-(I*Cr*nuo+(Uo*Tht)+(epsr*sigm*Tsurr**4))]
Tw = np.roots(ppar)
Tw1=Tw[3:4]
Tw2=abs(Tw1)
print(Tw2)
dThtdz= (-(4/do)*Uo*(Tht-Tw2))/(rhoDPE*usDPE*CpDPE)
return [dThtdz]
y0 = 563
# length points
z=np.linspace(0,50,1000)
# solve ODE
y = odeint(scp,y0,z,rtol=None,atol=None)
Tht=y[:,0]
plt.figure(1)
plt.plot(z,Tht)
plt.xlabel('length')
plt.ylabel('Heat transfer fluid temperature (K)')

A: scipy.integrate.odeint accepts a callable that returns the derivative of y at t and this should be a value that is a single dimension array. So don't return a list from this function.
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
import math
def scp(y,z):
    dh=  0.07 #internal diameter(m)
    tk = 0.002 #thickness of the absorber tube(m)
    do = dh+ 2*tk #outer diamater of the absorber tube
    kat = 45 #thermal conductivity of the absorber tube
    usDPE =0.5 #velocity of the diphenyl-ether (m/s)
    I = 800 #global insolation (W/m2K)
    Cr = 25 #concentration ratio
    nuo = 0.785 #optical efficiency
    epsr = 0.095 #emissivity of the solar selcective coating
    sigm =5.67*10**-8 #Stefan Boltzann constant
    Pat= math.pi*dh #perimeter of the tube
    Tsurr = 293
    Tht=y[0]
    B1=0.2336
    B2=120.57
    B3=-147.33
    B4=7E-07
    CpDPE=(1/(B1+(B2/Tht)+(B3/Tht**2)+(B4*Tht)))*1000 #Specific heat coefficient J/kgK
    B5=1.33718
    B6=-0.9233E-03
    B7=-0.08992E-06
    rhoDPE=(B5+(B6*Tht)+(B7*(Tht)**2))*1000  #Specific heat coefficient kg/m3
    B8=0.0451
    B9=0.0034
    kDPE=B8*math.exp(B9*Tht) #Thermal conductivity of DPE (W/m.K)
    D=4.832
    mu0=0.063
    T0=136.7
    muDPE=math.exp(math.log(mu0)+((D*T0)/(Tht-T0)))/1000 #viscosity of DPE (kg/m.s)
    ReDPE=(dh*usDPE*rhoDPE)/muDPE #Reynolds number of DPE
    PrDPE=(CpDPE*muDPE)/kDPE #Prandtl number of DPE
    NuDPE=0.023*ReDPE**0.8*PrDPE**0.4 #Nusselt number of DPE
    hj=(NuDPE*kDPE)/dh #heat transfer coefficent of fluid
    Uo= (hj*kat)/(kat+(tk*hj)) #Overall heat transfer coefficent of fluid
    At= ((math.pi)/4)*dh**2 #Area of the tube
    mDPE = rhoDPE*usDPE*At #mass flow rate of DPE
    ppar = [(epsr*sigm),0,0,Uo,-(I*Cr*nuo+(Uo*Tht)+(epsr*sigm*Tsurr**4))]
    Tw = np.roots(ppar)
    Tw1=Tw[3:4]
    Tw2=abs(Tw1)
    print(Tw2)
    dThtdz= (-(4/do)*Uo*(Tht-Tw2))/(rhoDPE*usDPE*CpDPE)
    return dThtdz

y0 = 563
# length points
z=np.linspace(0,50,1000)
# solve ODE
y = odeint(scp,y0,z,rtol=None,atol=None)
Tht=y[:,0]
plt.figure(1)
plt.plot(z,Tht)
plt.xlabel('length')
plt.ylabel('Heat transfer fluid temperature (K)')

I removed the list when you return dThtdz


text:
Q: How to bring the item's detail to another page when the item was clicked using PHP? I'm working on a site that consists of clickable image products. Every product has its own name, price and description that comes from the database but I'm not really sure about how can I do this by clicking the product will bring its product name, price and description to another page? Here's an illustrative example of what I mean:

Here's what I did trying to make it appear to another page:
<div class="product-100" id=<?PHP echo("'".$ItemID."'"); ?>>
<?PHP echo ""; ?>

<?PHP echo($ItemName); ?>

    <?PHP echo($ItemPrice);?>

    <?PHP echo($ItemDesc);?>

And here's what the other page I did with:
$ItemID = $_GET['ItemID'];
$viewproducts = "SELECT * FROM tbl_Items WHERE ItemID = '".ItemID."'";

Of course, ItemID of the product is the only one that shows to the other page.

A: Comment to answer, to close 'er up:
.ItemID. is being treated as a constant.
Put the $ in there '".$ItemID."'.
Checking for errors would have thrown "undefined constant ItemID..."

*

*http://php.net/manual/en/function.error-reporting.php


text:
Q: What does "I'm so sorry for you to hear that" mean? Suppose you witnessed someone hearing something unpleasant, and you want to express sympathy for them.
Can we say

"I'm so sorry for you to hear that"

?
It it grammatical and natural?
I guess we could also say:

I'm so sorry that you heard that (it occurred just a while ago that you heard that)

Or

I'm so sorry that you have to hear that. (Does this mean something different?)

A: Let us assume that there are three people: Jack, Bob and Claire. Bob says to Claire: "By the way, your dog died". Jack, Claire's friend, says to Claire, "I'm so sorry for you to hear that."
Hearing that your dog died is a painful thing to hear for Claire. Jack empathises with Claire and wants to express his sympathy for her pain, so he says "I'm sorry for you to hear that" -- it is an expression of empathy.
So, both 1. and 2. are close, but should include the idea of expressing empathy.

A: 1) I'm so sorry (that) you heard that (it occurred just a while ago that you heard that).
1) Someone hears something they were not meant to hear. Past Tense.
2) I'm so sorry (that) you have to hear that.
2) I'm telling you now you are doing a poor job. I am so sorry you have to hear that. Present Tense
Neither of those can be expressed as: I'm sorry for you etc.
To be sorry for someone means to pity them.
So, the only way to pity someone if they hear something they should not while using the preposition for would be to say:
I'm sorry for you as or because you heard that or have to hear that or had to hear that.
It is not usually what one might say.


text:
Q: Pingaccess getting error when saving rule Pingaccess configure() method in @Rule class which extends RuleInterceptor class giving error while saving from UI
I can see the value for the configuration pojo coming inside the configure() method


text:
Q: Why does Dropbox break my Drupal site? I'm using Apache 2.4 on Ubuntu 14.04 and Drupal 7.  I wanted an easy remote backup for my Drupal site, so I tried putting it in Dropbox.  Then, something happened, and Apache started giving 403 errors ("You don't have permission to access / on this server.") for the site.
I recovered from an old backup, but I still can't figure out what happened.  I diffed the Dropbox directory and the backup, and they're the same.  I reset all the permissions in the Dropbox directory to match the backup, but the version in Dropbox still won't work.  I also tried copying the files from the Dropbox directory into the location of the backup, and that still didn't work.
I'm a bit at a loss as to what went wrong.  Does anyone have ideas as to what Dropbox might have broken?

A: Rather than trying to run the site from a Dropbox location, why not just make Dropbox the repository for backups?
Try this:
https://www.drupal.org/project/backup_migrate_dropbox
This will also backup your database which you didn't mention as part of your Dropbox backup strategy.
Or you could run a cron task to run incremental backups via rsync to the Dropbox folder (Assuming you have already gone through getting Dropbox connected any syncing with Ubuntu).  I use the process documented at this location and it has worked perfectly on a number of different web servers:
http://hadzimahmutovic.com/rsnapshot-mysql/rsnapshot-backing-mysql-databases


text:
Q: Where is the IcedTea Control Panel? I want to disable the sandbox banner on Java Webstart applications, and the official documentation hints at a control panel, but I am unable to find it.

A: The IcedTea control panel is launched using the command itweb-settings from a terminal.


text:
Q: pure css arrow help The image below describes the issue. I am creating our comment forms. And want to create the pointer arrow in ffffff background color, and a border of 1px aaaaaa and border bottom fff so it sits comfortably on our container div
The issue I have is I can make a solid color pointer, but not sure if I can make what I want, so thought I would ask here please.

The css for the pointer is:
div.comment-reply .arrow{
border-bottom: 8px solid #888;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
height: 0;
left: 30px;
line-height: 0;
position: absolute;
top: -8px;
width: 0;

}

A: @422; you can do with css like this rotate property.
css

#C{
    height:200px;
    width:200px;
    background:red;
    border:1px solid #000;
    position:relative;
    }

.arrow{
     height: 20px;
     width: 20px;
     margin-left:30px;
    margin-top:-11px;
    background:red;
    -moz-transform:rotate(45deg);
    -webkit-transform:rotate(45deg);
    border-right:1px solid #000;
    border-bottom:1px solid #000;
    position:absolute;
    bottom:-10px;
    left:20px;
}

html

you can use :after, :before instead of span.
for IE you can use ie filter
filter: progid:DXImageTransform.Microsoft.Matrix(sizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476); /* IE6,IE7 */
-ms-filter: "progid:DXImageTransform.Microsoft.Matrix(SizingMethod='auto expand', M11=0.7071067811865476, M12=-0.7071067811865475, M21=0.7071067811865475, M22=0.7071067811865476)"; /* IE8 */

CHECK THIS http://jsfiddle.net/sandeep/Hec3t/7/

A: Using some :before and :after magic, I was able to create this with the following code:

Here is a comment

__
.comment div:before {
    content:"";
    border:10px solid transparent;
    border-bottom-color:#ccc;
    width:0px;
    height:0px;
    display:block;
    position:absolute;
    top:-10px;
    left:21px;
}
.comment div:after {
    content:"";
    border:12px solid transparent;
    border-bottom-color:#fff;
    width:0px;
    height:0px;
    display:block;
    position:absolute;
    top:-10px;
    left:19px;
}
.comment {
    position:relative;
    margin:10px;
    padding:10px;
}
.comment div {
    padding:1em;
    border:1px solid #ccc;
}

It's not perfect, but it avoids the need for an empty tag to contain your arrow.
Demo: http://jsfiddle.net/yGsKd/2/


text:
Q: What is bounty mode? When setting up an AI skirmish, there is a tick box for "Bounty Mode". Hovering over the box or label does not show a tool tip like the other options.
What is bounty mode?

A: According to a post here, bounty mode gives awards for killing other players' commanders.

Is it a permanent boost to eco when you kill another players commander?
Yep! Also, if the commander dies via suicide or some other way that means no enemy unit killed it, the bonus afaik is awarded to the last player who damaged their army.

This is confirmed in this article:

With this mode enabled, when a commander dies the enemy that killed them gets a percentage bonus to their income, this bonus is set in the lobby. Someone self-destructs? Last person to attack their army gets the bonus. No more hiding, you fight or you die.


text:
Q: Winston daily rotation node js I use logging through the winston / daily rotation plugin. Now I want a log file every day, this is going well.
But now I would like to zip the log of the day before.
Does anyone have a good solution to test this without having to wait a day?
This is my logger:
const write = new (winston.Logger)(
{
    transports: [
        new (winston.transports.DailyRotateFile)({
            //filename: `${logDir}/%DATE%-log`,
            filename: `${logDir}/${Math.random()}`,
            timestamp: tsFormat,
            datePattern: 'DD-MM-YYYY',
            prepend: true,
            zippedArchive:true,
            maxFiles: 3

As you can see, I tried it with Math.random() but that does not work.
I fill my test file this way:
const str = 'Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World! Hello World!';
setInterval(function () {
    for (i = 0; i < 10; i++)
        write.info(str);
}, 5);


text:
Q: Estimate the second moment of a latent variable using a conditionally unbiased proxy The Setup: Let $X_t$ denote an unobservable stochastic sequence where the first two unconditional moments are finite constants; ie $\mathbb{E} X_t = \mu < \infty$ and $\mathbb{E} X_t^2 = \gamma < \infty$. Assume that $X_t$ obeys some minimum set of regularity conditions such that a weak law of large numbers applies to its first two sample moments; ie conditions that limit the dependence in the sequence and bound the higher order moments.
Let $Y_t$ denote a conditionally unbiased proxy for $X_t$. That is, $\mathbb{E} [Y_t | X_t] = X_t$, and hence $\mathbb{E} Y_t = \mathbb{E} X_t = \mu$. Assume that $Y_t$ also obeys a minimum set of regularity conditions such that a weak law of large numbers applies to its first two sample moments.
Let $S_T = T^{-1} \sum_{t=1}^T Y_t$. Given the assumptions on $X_t$ and $Y_t$, it follows that $\mathbb{E} S_T = \mu$ and $S_T \overset{\mathbb{P}}{\rightarrow} \mu$, hence $S_T$ is a consistent, unbiased estimator for $\mu$
My Question: Given the setup, how can I estimate $\mathbb{E} X_t^2 = \gamma$?
Things I Know: From Slutsky's theorem, $(S_T)^2 \overset{\mathbb{P}}{\rightarrow} (\mathbb{E} X_t)^2 \neq \mathbb{E} X_t^2 = \gamma$, via Jensen's inequality, so in general $(S_T)^2$ will be a poor estimator for $\gamma$. Also, $T^{-1} \sum_{t=1}^T Y_t^2$ may not be a good estimator since the assumption set does not guarantee that $\mathbb{E} X_t^2 = \mathbb{E} Y_t^2$.
Final Note: I would be happy with any answer that improves upon the properties of $(S_T)^2$. So an approximation type estimator obtained via some sort of series expansion would be great. That's what I've mainly been looking into thus far, but with little luck. Even suggestions regarding expansions I might look into would be most welcome.
Thanks in advance to all responders.

A: I'm not sure you can do much more with what you've got to work with.
I mean, you can lower bound $\gamma \geq \mu^2$, as
$$
\mathbb{Var}(X_t) = \mathbb{E}(X_t^2)-\mathbb{E}(X_t)^2 = \gamma-\mu^2 \geq 0
$$
then estimate $\mu$ from the arithmetic mean of your set of samples $S_T$ as usual.
If we have the situation where $Y_t$ is equal to $X_t$ plus some uncorrelated noise, then you can upper bound it too as
$$
\mathbb{E}(Y_t^2) \geq \mathbb{E}(X_t^2).
$$
To see why, look at Innuo's splendid comment on your original post, and note that the variance of $Z_t$ must be positive. If the covariance between it and $X_t$ is zero, then the inequality becomes pretty clear. If the correlation between $X_t$ and $Z_t$ is positive, then it still holds, albeit more weakly.
So we have $\mathbb{E}(Y_t^2) \geq \gamma \geq \mu^2$ for uncorrelated or positively correlated additive noise. I think that's all that can be said. If those bounds are sufficiently tight then maybe that will do? If not, then either $X_t$ or $Z_t$ has a big variance, and beyond taking more direct measurements somehow I'm not sure if you can tell which.


text:
Q: Prove $(A \cup B) \setminus C \subseteq A \cup (B\setminus C)$ I have to prove that $$(A \cup B) \setminus C \subseteq A \cup (B \setminus C) $$
I am not sure how to do this, but one of my ideas is to show that there is an $x$ that belongs to $(A \cup B) \setminus C$, and it is arbitrary. And then to show that $x$ belongs to $A \cup (B \setminus C)$  as well.
Do you think that it is a good way to do it or you have other ideas?

A: HINT:
Prove that
$$
(A \cup B)\setminus C=(A\setminus C) \cup(B\setminus C) \tag{1}
$$

I will show how to prove $(1)$.
Assume $x\in (A \cup B)\setminus C$, then $x\in A$ or $x \in B$, and $x \notin C$. That means $x \in A \setminus C$ or $x \in B \setminus C$. Then $x \in (A \setminus C) \cup (B \setminus C)$. So that $(A \cup B)\setminus C\subseteq(A\setminus C) \cup(B\setminus C) $.
From the other side, assume $x\in (A\setminus C) \cup(B\setminus C)$, then $x \in A\setminus C $ or $x \in B\setminus C$, which means $x \notin C$ and $x $ belongs to either $A$ or $B$. So $x \in (A \cup B) \setminus C$. Thus
$$
(A \cup B)\setminus C=(A\setminus C) \cup(B\setminus C) \subseteq A\cup(B\setminus C)
$$

A: Let $x\in (A\cup B)\setminus C$. Then, by definition, $x\in A\cup B$ but $x\notin C$. If $x\in A$, then so be it; the fact that $x\notin C$ is irrelevant. If $x\in B$, though, of course, we still have $x\notin C$. Hence $x\in A\cup(B\setminus C)$. Therefore, $ (A\cup B)\setminus C\subseteq A\cup(B\setminus C)$.


text:
Q: Excel VBA how to return variable from function Example of the code:
Sub

   Dim NOSSPrefix As String
   NOSSPrefix = Cells(1, 6).Value
   NOSSSpecific(NOSSPrefixSpec)

End Sub

Function NOSSSpecific(NOSSPrefixSpec)

   If NOSSPrefixSpec = "6" Or NOSSPrefixSpec = "17" Or NOSSPrefixSpec = "19" Then
       NOSSPrefix = NOSSPrefixSpec
   Else
       NOSSPrefix = "999"
   End If

End Function

Tried alreaddy return, set, ...
Just want to return the NOSSPrefix back from the function to the routine above.

A: Something like this:
Sub Main()
    Dim NOSSPrefixSpec As String
    NOSSPrefixSpec = "12"
    Debug.Print NOSSSpecific(NOSSPrefixSpec) //Returns "999"
End Sub

Function NOSSSpecific(NOSSPrefixSpec As String) As String
    If NOSSPrefixSpec = "6" Or NOSSPrefixSpec = "17" Or NOSSPrefixSpec = "19" Then
        NOSSSpecific = NOSSPrefixSpec
    Else
        NOSSSpecific = "999"
    End If
End Function

Note:

*

*You have to define NOSSPrefix. I changed it to NOSSPrefixSpec

*I've explicitly added String as the function argument type and return value


text:
Q: Console.log only ever shows the original state, even though I'm 100% sure the state is being updated in React My app has state that is a 2d array filled with 0s. As I run the app, 2d array is traversed and those 0s are changed to 1s as the traversal occurs. This is reflected on the screen, as the grid cell changes color from clear to blue when it changes from 0 to 1.
So basically what I'm saying is that I can see that the state is updating. If I look at the components tab in the dev tools my state reflects that as well. So, here comes my problem:
When I console.log the state, the only thing I ever see is the ORIGINAL state filled with 0s. The grid traversal is executing on a loop, so every second I can see that state is changing, but every loop the console.log does not change.
I've read other questions on here about react state updates being asynchronous, and people try to log the new state before it is done updating. But that does not seem to be my problem, because I am literally 100% sure that state has updated, as confirmed by the visual in my browser as well as in the dev tools.
Here is a link to the github repo with my code: https://github.com/jeffpalmeri/graph-traversal/blob/master/src/App.js
Any ideas why this is happening?
The console.log I'm referring to is on line 121.

A: I think this might have something to do with your reference and when you open the console and watch it.
Ex.
You have a array a=[1,2,3], the reference to this a is not changed during the printout, so at this second it's 1,2,3 and next second it'll be 2,3,4. In the end it'll be stable as 3,4,5.
If you open the console tab in the last minute, i think you'll see everything is 3,4,5. Unless during the print out, you do
  console.log(a.slice())

A: You are using the useCallback hook. The React documentation says:

useCallback will return a memoized version of the callback that only changes if one of the dependencies has changed.

https://reactjs.org/docs/hooks-reference.html#usecallback
Since you don't specify any dependencies, your callback will never change and will always print the same value of grid due to closure (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures). In addition, you are calling your callback within your callback using setTimout. Since your callback never changes, it will always refer to the initial callback even if you would specify dependencies, again due to closure.
If you want to do something with your grid state after it has been updated, use useEffect (https://reactjs.org/docs/hooks-reference.html#useeffect)


text:
Q: Switched graphics card, now major problems I have an old nVidia 9600GT, which I pulled out of my computer dual booting with Windows 7 and 13.04. I then plugged in a HD6670. I didn't think to uninstall drivers in 13.04, so I started my computer up and tried to do it after I have plugged the card in. Big mistake. Windows 7 works fine, but my Ubuntu is a mess.
On booting into Ubuntu, the graphics were very glitchy with colours everywhere and flickering. I could make out my terminal from ctrl-alt-t, and followed the instructions to download and install AMD drivers. Everything went well until I got to the config, which failed. I tried a few solutions posted online, but nothing worked, so now I've swapped my 9600GT back in.
I don't have the official nVidia drivers, but the graphics at least aren't glitchy. However, my desktop has dissappeared, and just my wallpaper is visible. I can launch a terminal, which is how I'm writing this message, but not much else.
I've tried reinstalling ubuntu-desktop, where it merely states the most recent version is already installed. I also tried resetting unity, which gave me the following output:
ERROR: the reset option is now deprecated

And now I'm stuck. I played around with a few files including xorg which seems to have got me in my current mess. Any help with my situation would be greatly appreciated!


text:
Q: Open docx content within Eclipse XML editor Given the docx format basically just consists of a bunch of zipped xml files, I wonder whether it is possible to view / edit it within the Eclipse IDE without manual unzipping and rezipping.

A: This plugin provides the wanted feature:

*

*Eclipse Zip Editor
Usage:

*

*Install plugin via Eclipse Marketplace

*Right-click on a docx file

*Choose Open With > Other and select ZipEditor

*Double-click on document.xml

*Run the formatter via Ctrl+Shift+F

*Edit the content and save

*On tab close ZipEditor asks about updating the zip file


text:
Q: Abstract Class to Display Static Varibles Basically what I have to do is create an abstract class with all of my variables/shared code in it. I then have to extend the class to make the variables unique to each class that extends the abstract. I'm relatively familiar with PHP but have never dealt with abstract classes and I'm completely lost.
HTML/PHP (index.php):

      <?php
        require 'Card.php';
        $name = new Card();
      ?>

<?php echo $name->name;?>

<?php echo $name->business;?>

<?php echo $name->email;?>

<?php echo $name->website;?>

<?php echo $name->phone;?>

<?php echo $name->address;?>

<?php echo $name->city;?>

<?php echo $name->state;?>

<?php echo $name->zip;?>

PHP (card.php):
<?php
abstract class Card{
    public $name = "John Q Public";
    public $business = "Q Public Incorporations";
    public $email = "john@qpublic.com";
    public $website = "jqpinc.com";
    public $phone = "555-555-5555";
    public $address = "123 Main Street";
    public $city = "Bowling Green,";
    public $state = "Kentucky";
    public $zip = "42101";
}


text:
Q: iOS 7 - Identify segue that called view to unwind correctly I have a UIViewController that can be presented by two different other views. It's a search form that act exactly the same for both views.
Let's say View1 and View2 can perform segues that present an instance of SearchView. How could I know which view presented SearchView so that I can perform an unwind segue that is linked to the corresponding action?
As both View1 and View2 are TabViews, I don't want to use a navigationController in each of them as I find it a little bit of overpower for a simple task.
In this example:
View1.m
-(IBAction)didClickButton:
{
    [self performSegueWithIdentifier:@"searchSegue1"];
}

View2.m
-(IBAction)didClickButton:
{
    [self performSegueWithIdentifier:@"searchSegue2"];
}

SearchView.m
// Here is where I should know which segue to call
if (***ConditionToSegue1***)
    [self performSegueWithIdentifier:@"unwindToSegue1"];

else if (***ConditionToSegue2***)
    [self performSegueWithIdentifier:@"unwindToSegue2"];

What is this condition? Is the best way to do it to just set a property of SearchView in the prepareForSegue methods that tells me what view that originated the call? Please keep in mind this I do no wish to use a NavigationController.
Best regards

A: In your SearchView.h add  the line @property (nonatomic) int tag.
Then in View1.m add the following method:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"searchSegue1"])
        [segue.destinationViewController setValue:1 forKey:@"tag"];
}

Do the same thing in View2.m but replace 1 with 2. Then change your if statement to:
if (self.tag == 1)
    [self performSegueWithIdentifier:@"unwindToSegue1"];
else if (self.tag == 2)
    [self performSegueWithIdentifier:@"unwindToSegue2"];

A: First of all you should know whether you are using storyboard or programatically creating storyboard for PERFORMING SEGUE.
    1.If you directly connect the segue through the click button(one view controller to another view controller),you don't need to write your above coding.Just it is enough to give segue name.
            click->SHOW THE ATTRIBUTES OF RIGHT SIDE UTILITY AREA.
                 ->NOW YOU CAN SEE THE STORYBOARD SEGUE WITH-IDENTIFIER,STYLE
                 ->IN IDENTIFIER TEXTFIELD JUST GIVE YOUR SEGUE NAME(WHATEVER YOU WANT)
                   (IN STYLE-PUSH IS DEFAULT IF YOU CONNECT THE SEGUE AS A PUSH)

A: In your situation it may be as simple as [self dismissViewControllerAnimated: YES completion: nil];
Check out this blog post near the end that's titled Unwind Segues.
http://chrisrisner.com/Unwinding-with-iOS-and-Storyboards
You can wire up an action to the Exit component on the Storyboard which will do the unwinding for you.
-(IBAction)reset:(UIStoryboardSegue *)segue {
    //do stuff
}

A: I've found out that there is an easy answer to this. Apparently, if I create an unwind action on both view controllers named just the same, I can create just one unwind segue for both of them as well.
If I perform this segue on the SearchView it calls the correct action depending on who presented it.
This seems to work for now, I don't really know why or how it happens. Would appreciate if anyone could explain.
UPDATE:
Nope, it doesn't work as expected. Although the correct view is presented both actions are called, resulting in unwanted behavior.


text:
Q: I'm unable to initialize my ServletContextListener. The .java class will not compile. Can anyone point me into what is going on? The error message indicates that I'm not overriding the abstract class and/or method appropriately.  Interestingly, I'm following code that's in a book; and it's supposed to be a compilable  example (Head First Java Servlets and JSP)
Command/Error:
javac -classpath /usr/local/Cellar/tomcat/8.5.13/libexec/lib/servlet-
api.jar:classes:. -d classes
src/com/example/MyServletContextListener.java
src/com/example/MyServletContextListener.java:6: error:
MyServletContextListener is not abstract and does not override abstract
method contextDestroyed(ServletContextEvent) in ServletContextListener
public class MyServletContextListener implements ServletContextListener
{
  ^1 error

Here's my code:
package com.example;
import javax.servlet.*;

public class MyServletContextListener implements ServletContextListener{

  public void contextInitialized(ServletContextEvent event){

    ServletContext sc = event.getServletContext();
    String dogBreed = sc.getInitParameter("breed");
    Dog d = new Dog(dogBreed);
    sc.setAttribute("dog", d);

  }

  public void contextDestroyed(ServletContext event) {

    //System.out.println("1");
  }

}

You'll notice that I tried overriding contextDestroyed() (now commented out), as the error implies that it might be the issue, but I get the same result.  However the book I'm using even just says to not worry about it because we don't need to clean up because the context only goes away when the app goes down.
<context-param>
  <param-name>adminEmail</param-name>
  <param-value>someemail@gmail.com</param-value>
  <param-name>mainEmail</param-name>
  <param-value>someother@place.com</param-value>
  <param-name>breed</param-name>
  <param-value>Great Dane</param-value>
</context-param>

<servlet>
  <servlet-name>ListenerTester</servlet-name>
  <servlet-class>com.example.ListenerTester</servlet-class>
</servlet>

<servlet-mapping>
  <servlet-name>ListenerTester</servlet-name>
  <url-pattern>/ListenTest.do</url-pattern>
</servlet-mapping>

<listener>
  <listener-class>com.example.MyServletContextListener</listener-class>
</listener>

</web-app>

Does it matter where this web.xml is when I compile? I've tried with it in the same dir, and in the etc directory that I setup as part of the tutorial. I would have thought it only mattered at runtime.  Also, as fyi, I have multiple servlets in the same web.xml.
here's my version info:
java version "1.8.0_121"
Java(TM) SE Runtime Environment (build 1.8.0_121-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.121-b13, mixed mode)

A: The error message is telling you exactly what is wrong:
MyServletContextListener is not abstract and does not override abstract
method contextDestroyed(ServletContextEvent) in ServletContextListener

The class of the parameter for the contextDestroyed method needs to be ServletContextEvent not ServletContext


text:
Q: Dynamic initialization of POCO classes based on DTO class I want to di initialization only for those classes they are mapped not necesserily 1:1 to dto object class.
I need this in order to generate valid XML file without empty tags (this would be the case if I put ...=new() on each my POCO class and subclass objects)
So if my dto object contains for example:
public class Dto
{
public string? Name {get;set;}
public Foo? Foo {get;set}
public Bar? Bar {get;set}
}

and I have mapping something like:
var model = new Invoice();
var dto = new Dto();
model.ContractDocumentReference!.Id = dto.Foo.RequestId;
//for example lets say this is a nullable int

model.OrderReference!.Name= dto.Bar.CitizenName;
//have some value "John"

Can I somehow dynamically initialize  only OrderReference (because only Bar.CitizenName has actually a value) through reflection?
Is there any other approach? Definitely I would need a map when I initialize some class and when I dont (based on dto class object)


text:
Q: Validating data before inserting into database I want to validate the data contained by Value Objects before inserting into the database (e.g. check that php string is smaller than 255 chars before inserting into a column of type varchar(255) or that a string is not inserted in an int(11) table column, php date has the correct format etc.).
Is there any framework or easy way to validate data before SQL INSERT or UPDATE operations?
Thanks!

A:
Is there any framework or easy way to
  validate data before SQL INSERT or
  UPDATE operations?

php has validation builtin the data filter package.
I would not advice you to use a complicated framework for this, because it would kill your performance without any real benefits.


text:
Q: Equation input with preview in classic editor I use WordPress as a headless CMS, and my frontend is made with React. There's no theme or live preview.
I'm looking for a plugin to add/edit and preview equations (LaTeX) in the classic editor.
This is an example of what I want, but with CKEditor:
https://jsfiddle.net/isaul32/3wjrkLdv/

Most of the plugins I find are outdated, and some of them like KaTeX (which I'm planning to use its js library for frontend) only support live preview in gutenberg blocks.
The reason I'm looking for classic editor (TinyMCE) support is because I have multiple text editing fields in a post - made with ACF - and ACF only has WYSIWYG editor, which is the same as TinyMCE. As far as I know, they are not going to add block editor as a field like the classic editor.
So:

*

*Is there an updated, maintained plugin for this?

*If not, is it possible to load the KaTeX js library inside the admin area and make it render the shortcodes? For example [katex]\nabla[/katex] inside the "text" tab, renders as ∇ in the "Visual" tab?


text:
Q: Using ant, check if a particular string is found in a file My requirement is that, using waitfor condition, ant should periodically check if string "Build Successful" is displayed in log file. If the string is found, then particular action should be performed.

A: Here's an example of one way you might do this:
<target name="wait-for">
    <waitfor maxwait="15" maxwaitunit="second" timeoutproperty="build.timeout">
        <resourcecontains resource="build.log" substring="Build Successful" />
    </waitfor>
    <antcall target="build-success" />
</target>

<target name="build-success" depends="build-fail" unless="build.timeout">
    <echo message="Success" />
</target>
<target name="build-fail" if="build.timeout">
    <echo message="Fail" />
</target>

Use the resourcecontains condition to look for the string in the named resource - in this case the file 'build.log'.
If it's not found in the allotted time, the build.timeout property is set.  There are two targets, one that is to be run
if the string is found, the other if not.  The 'target' attributes if, unless, and depends are used to make the if-else logic need.  If you only need to take an action in the case of success or failure, you can simplify slightly.


text:
Q: How to access cookies and session in Capybara 2.4.1 I'm using rails 4 with the following gems:

*

*guard-rspec (4.3.1)

*rspec (3.0.0)

*rspec-core (3.0.3)

*rspec-expectations (3.0.3)

*rspec-mocks (3.0.3)

*rspec-rails (3.0.2)

*rspec-support (3.0.3)

*capybara (2.4.1)

*capybara-webkit (1.1.0)

Capybara works as expected in normal scenarios/examples, but when I want access to a cookie or session, I get a NameError:
undefined local variable or method `session'

I have a custom class I'm using that stores cookie data and retrieves it to remember things about the user and then present certain things on the screen.
But I can't seem to get the tests to pass and I can't view the cookie or session.
Does it need to be mocked? How can I do this?

A: Capybara.current_session.driver.request.session works in 2.17.0. I'm assuming much hasn't changed though since 2.4.

A: Webkit exposes cookies like this:

page.driver.browser.manage.all_cookies

Reference here: https://github.com/thoughtbot/capybara-webkit/issues/168


text:
Q: do I need two useEffect for mount and state change? Suppose you want to fetchData on mount and when a variable nonApproved changes.
Do I need two useEffect or only one?
   useEffect(() => {
     fetchData()
   }, [])

   useEffect(() => {
     fetchData()
   }, [nonApproved])

A: The second one covers the first one, it will be triggered after component mounted (initial render) and when ever nonApproved changed  you only need:
useEffect(() => {
 fetchData()
}, [nonApproved])

A: 1 useEffect is enough.
Below runs both on mount as well as when nonApproved value is changed.
useEffect(() => {
     fetchData()
   }, [nonApproved])


text:
Q: Python setuptools: How can I list a private repository under install_requires? I am creating a setup.py file for a project which depends on private GitHub repositories.  The relevant parts of the file look like this:
from setuptools import setup
setup(name='my_project',
    ...,
    install_requires=[
        'public_package',
        'other_public_package',
        'private_repo_1',
        'private_repo_2',
    ],
    dependency_links=[
        'https://github.com/my_account/private_repo_1/master/tarball/',
        'https://github.com/my_account/private_repo_2/master/tarball/',
    ],
    ...,
)

I am using setuptools instead of distutils because the latter does not support the install_requires and dependency_links arguments per this answer.
The above setup file fails to access the private repos with a 404 error - which is to be expected since GitHub returns a 404 to unauthorized requests for a private repository.  However, I can't figure out how to make setuptools authenticate.
Here are some things I've tried:

*

*Use git+ssh:// instead of https:// in dependency_links as I would if installing the repo with pip.  This fails because setuptools doesn't recognize this protocol ("unknown url type: git+ssh"), though the distribute documentation says it should.  Ditto git+https and git+http.

*https://<username>:<password>@github.com/... - still get a 404.  (This method doesn't work with curl or wget from the command line either - though curl -u <username> <repo_url> -O <output_file_name> does work.)

*Upgrading setuptools (0.9.7) and virtualenv (1.10) to the latest versions.  Also tried installing distribute though this overview says it was merged back into setuptools.  Either way, no dice.
Currently I just have setup.py print out a warning that the private repos must be downloaded separately.  This is obviously less than ideal.  I feel like there's something obvious that I'm missing, but can't think what it might be. :)
Duplicate-ish question with no answers here.

A: Here's what worked for me:
  install_requires=[
      'private_package_name==1.1',
  ],
  dependency_links=[
      'git+ssh://git@github.com/username/private_repo.git#egg=private_package_name-1.1',
  ]

Note that you have to have the version number in the egg name, otherwise it will say it can't find the package.

A: I found a (hacky) workaround:
#!/usr/bin/env python

from setuptools import setup
import os

os.system('pip install git+https://github-private.corp.com/user/repo.git@master')

setup( name='original-name'
     , ...
     , install_requires=['repo'] )

I understand that there are ethical issues with having a system call in a setup script, but I can't think of another way to do this.

A: Via Tom Hemmes' answer I found this is the only thing that worked for me:
    install_requires=[
        '<package> @ https://github.com/<username>/<package>/archive/<branch_name>.zip']

A: I couldn't find any good documentation on this, but came across the solution mainly through trial & error. Further, installing from pip & setuptools have some subtle differences; but this way should work for both.
GitHub don't (currently, as of August 2016) offer an easy way to get the zip / tarball of private repos. So you need to point setuptools to tell setuptools that you're pointing to a git repo:
from setuptools import setup
import os
# get deploy key from https://help.github.com/articles/git-automation-with-oauth-tokens/
github_token = os.environ['GITHUB_TOKEN']

setup(
    # ...
    install_requires='package',
    dependency_links = [
    'git+https://{github_token}@github.com/user/{package}.git/@{version}#egg={package}-0'
        .format(github_token=github_token, package=package, version=master)
        ]

A couple of notes here:

*

*For private repos, you need to authenticate with GitHub; the simplest way I found is to create an oauth token, drop that into your environment, and then include it with the URL

*You need to include some version number (here is 0) at the end of the link, even if there's no package on PyPI. This has to be a actual number, not a word.

*You need to preface with git+ to tell setuptools it's to clone the repo, rather than pointing at a zip / tarball

*version can be a branch, a tag, or a commit hash

*You need to supply --process-dependency-links if installing from pip

A: I was trying to get this to work for installing with pip, but the above was not working for me. From [1] I understood the PEP508 standard should be used, from [2] I retrieved an example which actually does work (at least for my case).
Please note; this is with pip 20.0.2 on Python 3.7.4
setup(
    name='<package>',
...
    install_requires=[
        '<normal_dependency>',
         # Private repository
        '<dependency_name> @ git+ssh://git@github.com/<user>/<repo_name>@<branch>',
         # Public repository
        '<dependency_name> @ git+https://github.com/<user>/<repo_name>@<branch>',
    ],
)

After specifying my package this way installation works fine (also with -e settings and without the need to specify --process-dependency-links).
References
[1] https://github.com/pypa/pip/issues/4187
[2] https://github.com/pypa/pip/issues/5566

A: Using archive URL from github works for me, for public repositories. E.g.
dependency_links = [
  'https://github.com/username/reponame/archive/master.zip#egg=eggname-version',
]

A: With pip 20.1.1, this works for me
install_requires=[ "packson3@https://tracinsy.ewi.tudelft.nl/pubtrac/Utilities/export/138/packson3/dist/packson3-1.0.0.tar.gz"],

in setup.py

A: This work for our scenario:

*

*package is on github in a private repo

*we want to install it into site-packages (not into ./src with -e)

*being able to use pip install -r requirements.txt

*being able to use pip install -e reposdir (or from github), where the dependencies are only specified in requirements.txt

https://github.com/pypa/pip/issues/3610#issuecomment-356687173

A: Edit: This appears to only work with public github repositories, see comments.
dependency_links=[
    'https://github.com/my_account/private_repo_1/tarball/master#egg=private_repo_1',
    'https://github.com/my_account/private_repo_2/tarball/master#egg=private_repo_2',
],

Above syntax seems to work for me with setuptools 1.0. At the moment at least the syntax of adding "#egg=project_name-version" to VCS dependencies is documented in the link you gave to distribute documentation.


text:
Q: no value for username when parsing json data RegisterActivity.java

This is register Activity and use of Asyntask class for json parsing I got error when i submitted data to the server and when i submitted data then no value for UserName is occued.

public class RegisterActivity extends ActionBarActivity {

    EditText etUsername, etUserEmalAdd, etUserPass, etRe_enterPass;
    Switch aSwitch;
    TextView tvLoginLink;
    Button bRegister;
    Context con;
    String userName,EmailAdd,password,Confirm_Pass;
    String UserName = "",Email = "",Password = "";
    String RegisterMessage = "", RegisterMessageInfo = "";

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

        bRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                userName = etUsername.getText().toString().trim();
                EmailAdd = etUserEmalAdd.getText().toString().trim();
                password = md5(etUserPass.getText().toString().trim());
                Confirm_Pass = md5(etRe_enterPass.getText().toString().trim());

                if (TextUtils.isEmpty(userName)
                        ||TextUtils.isEmpty(EmailAdd)
                        ||TextUtils.isEmpty(password)
                        ||TextUtils.isEmpty(Confirm_Pass)
                        ||(!Patterns.EMAIL_ADDRESS.matcher(EmailAdd).matches())
                        ||(!Confirm_Pass.equals(password))){

                    if (!Patterns.EMAIL_ADDRESS.matcher(EmailAdd).matches()){
                        etUserEmalAdd.requestFocus();
                        etUserEmalAdd.setError("Required..!!");
                    }
                    else if (TextUtils.isEmpty(EmailAdd)){
                        etUserEmalAdd.requestFocus();
                        etUserEmalAdd.setError("Required..!!");
                    }
                    else{

                    }

                    if (TextUtils.isEmpty(password)){
                        etUserPass.requestFocus();
                        etUserPass.setError("Required..!!");
                    }
                    else{

                    }

                    if (TextUtils.isEmpty(Confirm_Pass)){
                        etRe_enterPass.requestFocus();
                        etRe_enterPass.setError("Required..!!");
                    }
                    else if (!(password.equals(Confirm_Pass))){
                        etRe_enterPass.requestFocus();
                        etRe_enterPass.setError("Both password should be same..!!");
                    }
                    else {

                    }

                    if (TextUtils.isEmpty(userName)){
                        etUsername.requestFocus();
                        etUsername.setError("Required..!!");
                    }
                    else {

                    }
                }
                else {
                    new RegisterCheckTask().execute();
                }
            }
        });

        tvLoginLink.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent i = new Intent(con,LoginActivity.class);
                startActivity(i);
            }
        });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_register, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
    public void declareData(){
        setContentView(R.layout.activity_register);
        getSupportActionBar().hide();
        con = RegisterActivity.this;

        etUsername = (EditText) findViewById(R.id.etUsername);
        etUserEmalAdd = (EditText) findViewById(R.id.etUserEmail);
        etUserPass = (EditText) findViewById(R.id.etUserPassword);
        etRe_enterPass = (EditText) findViewById(R.id.etUserReenterPassword);

        aSwitch = (Switch) findViewById(R.id.switchd);

        tvLoginLink = (TextView) findViewById(R.id.tvLoginLink);

        bRegister = (Button) findViewById(R.id.btnRegisterUser);
    }

    class RegisterCheckTask extends AsyncTask<Void, Integer, JSONObject> {
        private ProgressDialog p_dialog;

        JSONObject jObject;

        @Override
        protected void onPreExecute() {
            // TODO Auto-generated method stub
            super.onPreExecute();
            p_dialog = new ProgressDialog(con);
            p_dialog.setMessage("Please Wait ...");
            p_dialog.setIndeterminate(false);
            p_dialog.setCancelable(false);
            p_dialog.show();
        }

        @Override
        protected JSONObject doInBackground(Void... params) {

            jObject = JSONParser.RegisterNewUser(etUsername.getText().toString(),
                    etUserEmalAdd.getText().toString(), md5(etUserPass.getText().toString()));

            Log.d("TAG", "JSON OBJECTSSSSSSS : " + jObject);
            Log.d("TAG","RegisterMessage:"+RegisterMessage);
            String msg = "Nothing Happened...";
            try {
                if (jObject != null) {
                    Log.d("TAG", "RESULT " + jObject.getString("status"));
                    Log.d("TAG", "RESULT Info:" + jObject.getString("message"));

                    RegisterMessage = jObject.getString("status");
                    RegisterMessageInfo = jObject.getString("message");

                    UserName = jObject.getString("UserName");
                    Email = jObject.getString("Email");
                    Password = md5(jObject.getString("Password"));

                } else {
                    Log.d("TAG", "Login Time Already Syncd....");
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                Log.e("TAG", "Warn :" + e.getLocalizedMessage());

            }
            return null;
        }

        @Override
        protected void onPostExecute(JSONObject result) {
            super.onPostExecute(result);
            p_dialog.dismiss();
            //here is error
            //i get result is null
            Log.d("TAG:","REsultttttt:"+result);
            if (RegisterMessage == null || RegisterMessage.equals("false"))
                ShowErroMessage("Not Registerd",
                        "Please try Again Later");
            else {
                if (RegisterMessage.equals("true")) {

                    Intent i = new Intent(con, FistLoginPageActivity.class);
                    startActivity(i);
                    finish();

                } else {
                    ShowErroMessage(RegisterMessage, RegisterMessageInfo);
                }
            }
        }
    }

    public void ShowErroMessage(String message, String messageInfo) {
        LayoutInflater layoutInflater = LayoutInflater.from(con);
        View promptView2 = layoutInflater.inflate(R.layout.row_error_message,
                null);
        final Dialog dialogDisplayParameter2 = new Dialog(con,
                R.style.FullHeightDialog);
        dialogDisplayParameter2.setContentView(promptView2);
        dialogDisplayParameter2.show();

        ((TextView) promptView2.findViewById(R.id.tvErrorMessageHeading))
                .setText(message);

        ((TextView) promptView2.findViewById(R.id.tvErrorMessageText))
                .setText(messageInfo);

        ((Button) promptView2.findViewById(R.id.btnErrorMessageOk))
                .setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        dialogDisplayParameter2.cancel();
                        if (RegisterMessage
                                .equals("succeed")) {
                            //Log.d("RegisterMessage:",RegisterMessage);
                            Intent i = new Intent(con, LoginActivity.class);
                            startActivity(i);
                            finish();
                        }
                    }
                });
    }
    private static final String md5(final String password) {
        try {

            MessageDigest digest = java.security.MessageDigest
                    .getInstance("MD5");
            digest.update(password.getBytes());
            byte messageDigest[] = digest.digest();

            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < messageDigest.length; i++) {
                String h = Integer.toHexString(0xFF & messageDigest[i]);
                while (h.length() < 2)
                    h = "0" + h;
                hexString.append(h);
            }
            Log.d("MD5", hexString.toString());
            return hexString.toString();

        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return "";
    }
}

JsonParser.java
package com.ninja.mock.ninjamockapplication.parser;

import android.util.Log;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.KeyStore;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Shreeya Patel on 12/28/2015.
 */

public class JSONParser {

    static String SITE_URL = "https://api.otentik.id/post/";

    static String url;
    static String result;
    static HttpPost httpPost;
    static HttpClient httpClient;
    static JSONObject jsonObject;
    static JSONArray jsonArray;
    static HttpEntity httpEntity;
    static InputStream is;
    static HttpResponse httpResponse;
    static List<NameValuePair> pairs;
    static String json = "";

/**
     * Initialization of Variables
     */

    private static void init() {
        // TODO Auto-generated constructor stub
        result = "";
        jsonObject = null;
        httpPost = null;
        is = null;
        jsonArray = null;
        httpClient = getNewHttpClient();
    }

    private static String getResult(InputStream is) {
        BufferedReader reader;
        StringBuilder stringBuilder = null;
        try {
            reader = new BufferedReader(
                    new InputStreamReader(is, "iso-8859-1"), 8);

            stringBuilder = new StringBuilder();
            String line = null;

            while ((line = reader.readLine()) != null) {
                stringBuilder.append(line + "\n");
            }
            is.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return stringBuilder.toString();

    }
    public static JSONObject RegisterNewUser(String UserName,
                                             String Email,
                                             String Password) {
        // TODO Auto-generated method stub

        try {
            init();

            url = SITE_URL + "register/ortu";
            Log.d("TAG", url);
            httpPost = new HttpPost(url.toString());
           /* httpPost.setHeader("Content-Type", "application/json; charset=UTF-8");
            httpPost.setHeader("Accept", "application/json");*/

            Log.d("TAG", "IN ADD USER JSON PARSING  : " + UserName + "\n" + Email + "\n" + Password);
            Log.d("TAG", "HTTP POST" + httpPost);
            pairs = new ArrayList<NameValuePair>();

            pairs.add(new BasicNameValuePair("UserName", UserName));
            pairs.add(new BasicNameValuePair("Email", Email));
            pairs.add(new BasicNameValuePair("Password", Password));

            Log.d("TAG", "IN ADD USER JSON PARSING  : " + UserName + "\n" + Email + "\n" + Password);
            httpPost.setEntity(new UrlEncodedFormEntity(pairs));

            Log.d("TAG", "HTTP POST" + httpPost);

            httpResponse = httpClient.execute(httpPost);
            int responseCode = httpResponse.getStatusLine().getStatusCode();
            Log.d("TAG", "HTTP RESPONSE Code" + responseCode);
            Log.d("TAG", "HTTP RESPONSE" + httpResponse);
            httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

/* Convert response to string */

            result = getResult(is);
            Log.d("TAG", "RESULTTTTTTTTTTTTT : " + result);
            jsonObject = new JSONObject(result);
            Log.d("TAG", "JSON OBJECT : " + jsonObject);

        } catch (ClientProtocolException e) {
            Log.e("TAG", "Error in Client Protocol : " + e.toString());
        } catch (JSONException e) {
            Log.e("TAG", "Error Parsing data " + e.toString());
        } catch (Exception e) {
            Log.e("TAG", "Error in HTTP Connection : " + e.toString());
        }
        Log.d("TAG", "JSON OBJECTTTTTTTTTTTTTTTTTT : " + jsonObject);
        return jsonObject;
    }

    public static HttpClient getNewHttpClient() {
        try {
            KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
            trustStore.load(null, null);

            MySSLSocketFactory sf = new MySSLSocketFactory(trustStore);
            sf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);

            HttpParams params = new BasicHttpParams();
            HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
            HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);

            SchemeRegistry registry = new SchemeRegistry();
            registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
            registry.register(new Scheme("https", sf, 443));

            ClientConnectionManager ccm = new ThreadSafeClientConnManager(params, registry);

            return new DefaultHttpClient(ccm, params);
        } catch (Exception e) {
            return new DefaultHttpClient();
        }

    }
}


text:
Q: Reading ID with For Loop I know it's a syntax error but how can i read the ID which includes vat then the i of the for loop and continues with Email
Error: Syntax error, unrecognized expression: [id^="vat"[i]"Email"]

Any help is appreciated. Thanks

A: From your given information and without having more information, I would change the code this way:
for (i = 1; i < $('[id^="vat"]').length; i++) {
   $('[id^="vat' + i + 'Email"]').each(function () {
      $(this).val($wteemail.val());
   });
}


text:
Q: Key listener for composite? I want to add a key listener for a composite.
My code is as follows:
@Override
protected Control createDialogArea(Composite parent) {
    //add swt text box , combo etc to parent
}

The composite is a: org.eclipse.swt.widgets.Composite
Now i want to add a key listener to the composite parent.
Like when ever user presses ctrl or escape, user should get notified.
Even if the focus is on one the text or combo field even then , the parent listener should be notified.
Thanks for the help.

A: Ok, here you go: Add a Filter to your Display. Within the Listener you check if the parent of the current focus control is the Shell of your Composite. If so, you check the key code.
In conclusion, you will handle the key event, if your focus is "within" your Composite and ignore it if it is "outside" your Composite.
public static void main(String[] args)
{
    Display display = new Display();
    final Shell shell = new Shell(display);
    shell.setLayout(new GridLayout(1, false));

    final Composite content = new Composite(shell, SWT.NONE);
    content.setLayout(new GridLayout(2, false));

    Text text = new Text(content, SWT.BORDER);
    Button button = new Button(content, SWT.PUSH);
    button.setText("Button");

    display.addFilter(SWT.KeyUp, new Listener()
    {
        @Override
        public void handleEvent(Event e)
        {
            if (e.widget instanceof Control && isChild(content, (Control) e.widget))
            {
                if ((e.stateMask & SWT.CTRL) == SWT.CTRL)
                {
                    System.out.println("Ctrl pressed");
                }
                else if(e.keyCode == SWT.ESC)
                {
                    System.out.println("Esc pressed");
                }
            }
        }
    });

    Text outsideText = new Text(shell, SWT.BORDER);

    shell.pack();
    shell.open();
    while (!shell.isDisposed())
    {
        if (!display.readAndDispatch())
        {
            display.sleep();
        }
    }
    display.dispose();
}

private static boolean isChild(Control parent, Control child)
{
    if (child.equals(parent))
        return true;

    Composite p = child.getParent();

    if (p != null)
        return isChild(parent, p);
    else
        return false;
}


text:
Q: Data in SQLflite database is not deleting, in my Flutter project So I have an issue of data not being deleted from my database. It is supposed to happen when a dismissible widget is swiped away.
This is the model class:
class DateModel {
  //define schema
  int? id;
  final String dateText;

  DateModel({this.id, required this.dateText});

  //convert json data to DateModel instance
  factory DateModel.fromMap(Map<String, dynamic> json) {
    return DateModel(id: json["id"], dateText: json["dateText"]);
  }

  //convert DateModel instance to json
  Map<String, dynamic> toMap() => {"id": id, "dateText": dateText};
}

Below is where some CRUD operations are defined. I concluded that the error is because I'm not properly storing the id upon insert (in the "add" function). Although I'm not certain I'm doing this right.
class DatabaseHelper {
  static Database? _db;

  //create singleton
  DatabaseHelper._constructor();
  static final DatabaseHelper instance = DatabaseHelper._constructor();

  Future<Database> get db async {
    return _db ??= await init_db("Date.db");
  }

  //create database when it doesn't exist
  Future<Database> init_db(String name) async {
    //locate database
    var databasePath = await getDatabasesPath();
    String path = join(databasePath, name);

    //open database and return
    return await openDatabase(path, version: 1, onCreate: _onCreate);
  }

  //Create date table
  Future _onCreate(Database db, int version) async {
    await db
        .execute("CREATE TABLE Dates (id INTEGER PRIMARY KEY, dateText TEXT)");
  }

  //add user input to table
  Future<int> add(DateModel dateModel) async {
    Database db = await instance.db;

    //store id of inserted date (generated by db.insert method)
    final id = await db.insert("Dates", dateModel.toMap());
    return dateModel.id = id;
  }

  //remove date from table
  Future<int> remove(int id) async {
    Database db = await instance.db;
    return await db.delete("Dates", where: "id = ?", whereArgs: [id]);
  }

  Future<List> getDates() async {
    Database db = await instance.db;
    final data = await db.rawQuery("SELECT dateText FROM Dates");
    if (data.isNotEmpty) {
      return data;
    } else {
      return [];
    }
  }
}

And lastly, this is where the delete action is supposed to take place (in dismissible's onDismissed property):
 Widget build(BuildContext context) {
    return Consumer<Date>(builder: (context, date, child) {
      return Scaffold(
        body: FutureBuilder(
          future: DatabaseHelper.instance.getDates(),
          builder: (context, AsyncSnapshot<List<dynamic>> snapshot) {
            if (!snapshot.hasData || snapshot.connectionState != ConnectionState.done) {
              return CircularProgressIndicator();
            }

            return ListView.builder(
                shrinkWrap: true,
                itemCount: snapshot.data!.length,
                itemBuilder: (context, index) {
                  return SlideTransition(
                    position:
                        Tween<Offset>(begin: Offset(1, 0), end: Offset(0, 0))
                            .animate(CurvedAnimation(
                                parent: _controller, curve: Curves.bounceIn)),
                    child: Dismissible(
                        key: UniqueKey(),
                        direction: DismissDirection.horizontal,
                        onDismissed: (direction) async {
                          final dateModel =
                              DateModel(dateText: date.dateList[index]);

                          //remove from list
                          date.dateList.removeAt(index);

                        //remove from database
                         await DatabaseHelper.instance.remove(dateModel.id!);
                        },
                        child: ListTile(title: Text(snapshot.data![index].toString()))),
                  );
                });
          },
        ),
      );
    });
  }

I get the error that I'm doing a null check on a null value, which I believe is the dateModel.id.
I tried storing the id upon insert a couple of different ways. Nothing changed.

A: This is because you are trying to do exactly that: Putting a null check operator on a null value.
You are creating the dateModel like this:
final dateModel = DateModel(dateText: date.dateList[index]);

You do not pass any value for the id, which then is null.
Try something like this:
Map<String, dynamic> dateJson = snapshot.data![index] as Map<String, dynamic>;
DateModel dateModel = DateModel.fromMap(dateJson);
date.dateList.removeAt(index);
await DatabaseHelper.instance.remove(dateModel.id);

PS: You should not make the id optional in your DateModel class since this should always be given.


text:
Q: Finding a unified ratio from two separate ratios I'm self-studying with Stroud & Booth's amazing Engineering Mathemathics, 7th edition. I'm stuck at a problem set that gives me two ratios of variables A and B, and B and C respectively, an expects me to "unify" them, so to speak, in order to produce an A:B:C ratio. To be more precise:

A, B and C are mixed according to the ratios $A:B = 2:5$ and $B:C = 10:11$. Find the common ratio $A:B:C$.

Just please keep in mind that I'm still on the first chapter, Arithmetic.

A: I work this kind of problem out by imagining totals that turn the ratios into amounts. I choose totals to make the arithmetic easy. Since I see $2$ and $5$ and $10$ and $11$ I'll suppose I have $2 \times 10 \times 11 = 220$ things. Then using $x$ to represent the number of things of type $X$ I know
$$
a + b + c = 220.
$$
I also know that since $a/b = 2/5$,
$$
2b = 5a
$$
and, similarly,
$$
11b = 10c.
$$
Now solve those three linear equations ih three unknowns.
If you don't like the $220$ total I started with you can use
$$
a + b + c = 1
$$
instead. Then the answers will be the appropriate fractions of the whole.

A: $A:B = 2:5$ and $B:C = 10:11$
$A:B = 4:10$ and $B:C = 10:11$
$A:B:C = 4:10:11$

A: You have 2 of A per every 5 of B and you have 10 of B per every 11 of C. It's not hard to see that you need twice the amount of A per B to cover the amount of B per C:
$$
2\cdot 2:2 \cdot 5:11\implies\\
4:10:11
$$


text:
Q: How to express the good in difference? One of the local companies has a slogan that literally translates to

We are all different... fortunately

I sense that "fortunately we are all different" sounds better in English. However, it misses the order of conveying the information:

*

*we are all different

*and that's not a bad thing at all

Question: How to express the good in difference? (within provided context)

A: The expression vive la difference has been added to the lexicon.
From ODO:

vive la difference [exclamation] humorous
An expression of approval of difference, especially that between the
  sexes.

The positive aspects of there being differences are obviously highlighted.

A: I don't think there's a good way to do this that will fit within a short length.
"Our differences are positive."
"Our differences paint a complete picture."
"Differences are what make us unique."
"Without our differences, there would be no 'you' or 'me'."

A: Especially as a slogan (where you're allowed more leeway than formal writing) I think the literal translation you give works quite well.
Possibly substituting luckily or thankfully as alternatives to fortunately.


text:
Q: combine get_where and limit in active record codeigniter I am little confused here.
I have a modal like this :
public function selectRequestPerUser($nama_user, $start_row, $limit) {
    $query = $this->db->get_where('tbl_requestfix', array('nama_user' => $nama_user), $start_row, $limit);
    return $query->result_array();
}

So, I use this modal to create a pagination in CI like this :
$nama = $this->session->userdata('nama');
$start_row = $this->uri->segment(2);
$per_page = 3;

if(trim($start_row) == ''){
  $start_row = 0;
};

$this->load->library('pagination');
$config['base_url'] = base_url().'control_closing/';
$config['total_rows'] = $total_rows;
$config['per_page'] = $per_page;

$this->pagination->initialize($config);

$data['pagination'] = $this->pagination->create_links();

$request = $this->model_request->selectRequestPerUser($nama, $start_row, $per_page);
$data['data_request'] = $request;
$this->load->view('view_closing', $data);

in view, just :
<?php echo pagination ?>

It just give me a blank page. I think in my modal get_where is the problem. Anybody can help ?

A: The syntax of get_where() is
$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);

You need to change this line in your model (alter $start_row and $limit) to make it work,
$query = $this->db->get_where('tbl_requestfix', array('nama_user' => $nama_user), $limit, $start_row);


text:
Q: Executing exe file from nodejs I'm setting up a new application for my final project. I'm trying to execute an exe file using node.js, but it looks that it's not working right.
I don't get any errors...
var {execFile} = require('child_process');
var executablePath = "C:\\Users\\MyUser\\Desktop\\finalProject\\routes\\api\\testcpp.exe";

const child = execFile(executablePath, ['--version'], (error, stdout, stderr) => {
    if (error) {
        throw error;
    }
    console.log(stdout);
});

A: var {execFile} = require('child_process');
var executablePath = "C:/Users/MyUser/Desktop/finalProject/routes/api/testcpp.exe";
const child = execFile(executablePath, ['--version'], (error, stdout, stderr) => {
if (error) {
  throw error;
}

console.log(stdout);
});


text:
Q: Queue or event as a switch between processes I have a system formed by 3 processes: a main one, and 2 child processes.
The first child process is constantly checking for a condition, and once this condition is verified, something happens in the second child process.
This can happen multiple times.
So I was wondering...is it possible to use a mp.Event as trigger? I'm thinking of...switching it, like a True/False bool variable, and looking for it in the second process.
Something like this:
main process
import multiprocessing as mp
from multiprocessing import set_start_method, Queue, Event
from p01 import P01_Initializer
from p02 import P02_Initializer
import time
import sys

def main():
    set_start_method("spawn")
    sw_event = mp.Event()

    p01 = mp.Process(target=P01_Initializer, args=(sw_event, ))
    p01.daemon = True
    p01.start()
    p02 = mp.Process(target=P01_Initializer, args=(sw_event, ))
    p02.daemon = True
    p02.start()

    ## close everything after 15 seconds
    t_start = time.time()
    while True:
        if time.time() - t_start > 15:
            p01.terminate()
            p02.terminate()
            sys.exit(0)

if __name__ == "__main__":
    main()

first child process
import time

def P01_Initializer(sw_event):
    process_01 = P01(sw_event)
    process_01.run()

class P01():
    def __init__(self, sw_event):
        self.sw_event = sw_event

    def run(self):
        while True:
            if condition:
                self.sw_event.set() ### switching it, like a bool variable

second child process
import time

def P02_Initializer(sw_event):
    process_02 = P02(sw_event)
    process_02.run()

class P02():
    def __init__(self, sw_event):
        self.sw_event = sw_event

    def run(self):
        while True:
            if self.sw_event == False:
                do nothing
            else:
                self.sw_event.set() ### switch it back to False, waiting for next occurence
                do something

Is something like this possible, or should I just use a boolean variable and pass it between processes using a Queue?

A: Ok, so basically you can set/unset (?) the event by using:
sw_event.set()
sw_event.clear()

once you do that, you can check the status of the event by:
sw_event.is_set()


text:
Q: mergesort in c++:segmentation fault I am getting segmentation fault while implementing mergesort.
I have checked for array out of bounds.I would love some help to find out where I have gone wrong.I have tried inputs for small arrays such as of size 10 where I have taken size of temp as static(>10).I have been pulling my hair out for hours.
UPDATE:  I only needed to change mid=(low+high)/2.
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

void merges(int arr[],int low,int mid,int high)
{
    int i=low,j=mid+1,k=0;
    int temp[high-low+1];
    while(i<=mid && j<=high)
    {
           if(arr[i]<arr[j])
            {
                temp[k++]=arr[i];
                i++;
            }
            else
            {
                temp[k++]=arr[j];
                j++;
            }
    }
    if(i>mid)
    {
        while(j<=high)
        {
            temp[k++]=arr[j];
            j++;
        }
    }
    else
    {
        while(i<=mid)
        {
            temp[k++]=arr[i];
            i++;
        }
    }
    j=0;
    for(i=low;i<=high;i++)
    {
        arr[i]=temp[j++];
    }
}

void mergesort(int arr[],int low,int high)
{
    if(low<high)
    {
    int mid=low+high/2;
    mergesort(arr,low,mid);
    mergesort(arr,mid+1,high);
    merges(arr,low,mid,high);
    }
}

int main(){
    int n;
    cin >> n;
    int arr[n];
    for(int arr_i = 0;arr_i < n;arr_i++){
    cin >> arr[arr_i];
    }
    int i,j,k;
    mergesort(arr,0,n-1);
    for(i=0;i<n;i++)
        cout<<arr[i];
    return 0;
}

A: i only needed to change mid=(low+high)/2. Thank you @Gerado Gálvez for your suggestion

A: You're recursively calling mergesort. Although your general case seems legitimate, I cannot ascertain your base case (i.e. to exit the recursion).


text:
Q: I'm getting crazy with this Promise stuff hope someone can help.
I am working on a translation part in magic mirror. I use the inside node_helper.js of a weather modul: Let me show u the code:
            if (this.config.lang != 'en'){
                console.log("in Translate");
                    translate(alerts.description, {to: this.config.lang}).then((res) => {console.log(res.text); return res;});
                    translate(alerts.expires, {to: this.config.lang}).then(res => {console.log(res.text)});
                translate(alerts.message, {to: this.config.lang}).then(res => {console.log(res.text)});
            }

and so on. If i look into config.log i get all results i love to see, but iam unable to use them in the following code ,,,, PLEASE HELP

A: You can use Promise.all() to coordinate when three operations that all return a promise are done and then use use those results in the resulting .then() callback:
        if (this.config.lang != 'en'){
            console.log("in Translate");
            Promise.all([
                translate(alerts.description, {to: this.config.lang}),
                translate(alerts.expires, {to: this.config.lang}),
                translate(alerts.message, {to: this.config.lang})
            ]).then(function(results) {
                // results[0], results[1], results[2] contain the three results
                // use those three values in the code inside this callback
            })
        }


text:
Q: Grant privileges on database names matching a pattern I want to create a mysql user who can only access databases which have names starting with netdata_. I use the following statement to create such user:
GRANT ALL PRIVILEGES ON `netdata_*`.* TO netdata@"%" IDENTIFIED BY "My_Top_Secret";

However, with this user netdata, I can see nothing other than the information_schema. So is there anything wrong in my grant statement? Thanks.