text:
Q: How to initiate state from another state (by copying without referencing) I have a code as below
useEffect(() => {
    {
      updateLocalColumns();
    }
  }, []);

const updateLocalColumns = () => {
  let templocalColumns = [...localColumns];
  templocalColumns[0]..defaultSortOrder = "descend";
  setlocalColumns(templocalColumns);
}
const orderContext = useContext(OrderContext);
const { data, columns } = orderContext;
const [localColumns, setlocalColumns] = useState([...columns]);

return (

    {console.log(columns)}

)

'columns' is a state that is obtained by using hooks, I am trying to make a copy over local component that is 'localColumns" and thus modify from there without interfering the global 'columns'
I was expecting the original columns to remain as its original state, however when I print out, the original columns is the same as 'localColumns' which is the modified one.
Expected Output
localColumns: [
    {
      title: "Username",
      dataIndex: "username",
      key: "username",
      defaultSortOrder: "descend"
    }
    ]

columns: [
    {
      title: "Username",
      dataIndex: "username",
      key: "username",
    }
    ]

Current Wrong Output
localColumns: [
    {
      title: "Username",
      dataIndex: "username",
      key: "username",
      defaultSortOrder: "descend"
    }
    ]

columns: [
    {
      title: "Username",
      dataIndex: "username",
      key: "username",
      defaultSortOrder: "descend"
    }
    ]

I am suspecting the problem is when I initate the state, I did a referencing.
The way I did copy was from this link and this link

A: I would try a simpler code:
//Import this class in the proper place
//import { clone } from 'ramda';

const orderContext = useContext(OrderContext);
const { data, columns } = orderContext;

let localColumns0 = clone(columns) //This is done to make a deep copy of "columns"

localColumns0[id]['defaultSortOrder']="descend"

const [localColumns, setlocalColumns] = useState(localColumns0);

return (

    {console.log(columns)}

)

A: If you don't want only the copy of the state, maybe you need to look how to do the deep copy of an array, after you make a deep copy of the estate you can pass the state to your personal component with <PersonalCom {...deepCopyStateObj}/> and the PersonalCom need a constructor where you receive the props, like the following code.
 constructor(props) {
    super(props);
 }

Or something equivalent in JSX syntax.
However make a deep copy of the state and pass the object to component don't look like, because you need to clone the state each time that your app refresh the UI, and react refresh very frequently the UI, for this reason, I suggest cloning the propriety that you need inside the personal component.


text:
Q: delete column based on two conditions in a dataframe I am trying to delete column based on two conditions in a dataframe.
I am trying to delete a column from a data frame and I wrote the following code
DATAFRAME= DATAFRAME.drop(DATAFRAME.loc[(DATAFRAME['COLUMN1'] ==80) & (DATAFRAME['COLUMN2'] =='86%')])

and its showing an error.
"[col1,col2,col3,col4....coln] not found in axis"
selection is working
DATAFRAME.loc[(DATAFRAME['COLUMN1'] ==80) & (DATAFRAME['COLUMN2'] =='86%')]

A: you can use:
DATAFRAME = DATAFRAME.loc[~((DATAFRAME['COLUMN1'] ==80) & (DATAFRAME['COLUMN2'] =='86%'))]

A: Since selection works as intended you can get the index of the rows meeting your criteria and use this approach. For your case it would look like this:
DATAFRAME.drop(DATAFRAME.loc[(DATAFRAME['COLUMN1'] == 80) & (DATAFRAME['COLUMN2'] == "86%")].index)

A: Why don't you use just filtering here?
import pandas as pd
DATAFRAME = pd.DataFrame(
    {"COLUMN1":[80, 100, 80],
    "COLUMN2": ['84%','85%', '86%' ]})

These are the indicies where your conditions are satisfied
cond = (DATAFRAME['COLUMN1'].eq(80) &
     DATAFRAME['COLUMN2'].eq('86%'))

0    False
1    False
2     True
dtype: bool

So in order to drop them you can just filter
DATAFRAME[~cond]

which gives you the following output
   COLUMN1 COLUMN2
0       80     84%
1      100     85%

redpajama_set_name: RedPajamaStackExchange


text:
Q: ASP.NET MVC Controller Logic I am new to this whole MVC stuff, so please bear with me.
I am wondering what is the correct way to implement controller logic.
In other words, take this very simple example, a forgot password screen. In traditional ASP/ASP.Net, this could eaisly be handled in one page, hide/show a div or two based on the flow... done!!
I have come up with the following and just wanted to see if I was on the right track. Have a look at the following controller:
Namespace Controllers
    Public Class AuthenticationController
        Inherits ControllerBase

        Private MembershipProvider As New GTGMembershipProvider

        <HttpGet()>
        Function LogOn() As ActionResult
            If (User.Identity.IsAuthenticated) Then
                Return RedirectToAction("Index", "Main")
            End If

            Return View(New LogOnViewModel)

        End Function

        <HttpPost()>
        Function LogOn(Model As LogOnViewModel, ReturnUrl As String) As ActionResult
            If (Not ModelState.IsValid) Then
                Return View(Model)
            End If

            If (Not MembershipProvider.ValidateUser(Model.UserName, Model.Password)) Then
                ModelState.AddModelError("", "Invalid login. Incorrect password/user name.")
                Return View(Model)
            End If

            IssueAuthenticationTicket(Model)

            If (Not ReturnUrl.IsNullOrEmpty) Then
                Return Redirect(ReturnUrl)
            Else
                Return RedirectToAction("Index", "Main")
            End If

        End Function

        Function LogOff() As ActionResult
            FormsAuthentication.SignOut()
            Return RedirectToAction("Index", "Main")

        End Function

        <HttpGet()>
        Function ForgotPassword() As ActionResult
            Return View(New ForgotPasswordViewModel)

        End Function

        <HttpPost()>
        Function ForgotPassword(Model As ForgotPasswordViewModel) As ActionResult
            If (Not ModelState.IsValid) Then
                Return View(Model)
            End If

            Return RedirectToAction("PasswordSent")

        End Function

        <HttpGet()>
        Function PasswordSent() As ActionResult
            Return View()

        End Function

        Private Sub IssueAuthenticationTicket(Model As LogOnViewModel)
            Dim Profile As New CustomerProfile With {.FirstName = "Sam", .ID = 1, .LastName = "Striano"}

            Dim Ticket As New FormsAuthenticationTicket(1, Model.UserName, Now, Now.AddDays(30), Model.RememberLogon, Profile.ToString)
            Dim Cookie As New HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(Ticket))

            HttpContext.Response.Cookies.Add(Cookie)

        End Sub

    End Class
End Namespace

A: You are on the right track.  Three suggestions I have to make your code better are:

*

*Refactor IssueAuthenticationTicket to method on an IAuthenticationService implementation, where IAuthenticationService looks like
public interface IAuthenticationService{
      bool Authenticate(LogOnViewModel viewModel, HttpContextBase httpContext);
 }
That way your concerns are separated, so if you have to change the way the session is authenticated, you won't have to changed the controller logic.  You could actually even keep your MembershipProvider dependency in the implementation and make the interface look like:
public interface IAuthenticationService{
      bool Authenticate(LogOnViewModel viewModel, HttpContextBase httpContext, out string message);
}

*Look into Inversion of Control and Dependency Injection to inject your dependencies automatically into the controller via the constructor.  My favorite tool for this is StructureMap.  This way you don't have to couple the controller to a specific implementation and you don't have to handle any creation logic from within the controller.  (The only thing this would affect in your sample would be the call to create a New GTGMembershipProvider.  This isn't a big deal here, but with more complicated controllers with more complex dependencies, this could really take up a lot of space and make your code less readable).

*You COULD put the logon model validation logic in a ModelValidator.  But, this may or may not be a good idea, because it requires multiple instances of the MembershipProvider.  If your membership provider is implemented as a singleton then this would make sense.
Sorry about the C# - I figure it's better to write it right in C#, then maybe write it right in VB.

A: I think this is good for being the authentication controller, some people migth suggest to create a level of abstraction and move code to another class, but in this case I don't think is necessary, for other controllers where you do deal with your business objects it will be necessary, the rule of thumb (IMHO) is that the only function the controller actions should perform is to gather the data for the model that will be displayed and passed to the view, how you get that data should be in other classes, but again, in this particular controller, I think this is simple enough to keep it this way


text:
Q: Delete first four rows in Excel with Powershell I have a powershell script that opens an excel file, re-assigns a blank password, and then saves the file.  I want to add a task to the script to remove the first 4 rows of the excel file before saving it.

A: You can't use OleDB for deleting data from Excel document. As per MSDN docmentation:

Although the Jet OLE DB Provider allows you to insert and update
  records in an Excel workbook, it does not allow DELETE operation

What you can do is use Exel's COM interface to delete rows. Remember to release COM object too. Like so,
$file = c:\temp\MyExcelFile.xls
# Star Excel, hide window
$excel = new-object -com Excel.Application -Property @{Visible = $false}
$workbook = $excel.Workbooks.Open($file) # Open the file
$sheet = $workbook.Sheets.Item(1) # Activate the first worksheet
[void]$sheet.Cells.Item(1, 1).EntireRow.Delete() # Delete the first row

$workbook.Close($true) # Close workbook and save changes
$excel.quit() # Quit Excel
[Runtime.Interopservices.Marshal]::ReleaseComObject($excel) # Release COM


text:
Q: Dropdown and MySQl I have a dropdown I dynamically populated from mysql
When I save the information it to mysql, it do not save the value of the dropdown list.
How do I set the selected value for the dynamic dropdown
Here is the code use to fill the dropdown.
How do I set the selected value on change in php
echo "<option value=\"" . utf8_encode($row['school_name']) . "\">" . utf8_encode($row['school_name']) . "</option>";

im have problems setting the correct format using this example
<option value="My School"<?php if ($row[school_name] == 'My School') echo ' selected="selected"'; ?>>My School</option>

Where My School should be the value populated from database
Ok
   <select id="school_name" "name="school_name" style="width:200px;" name="school_name">
                        <option selected="">Select Province School</option>

                        </select>

i then fill the dropdownlist with following.
$sql="SELECT * FROM ppSD_schools where province_code ='".$_POST['c_id']."'";
$res = $conn->query($sql);
$num_rows = $res->num_rows;

if($num_rows > 0) {
    echo "<option value=''>------- Select --------</option>";

    while($row = $res->fetch_assoc())

    {
    ?>
        echo "<option value=\"" . utf8_encode($row['school_name']) . "\">" . utf8_encode($row['school_name']) . "</option>";

    }

But when ever i select another school. it dont save the value selected to MySql
My guess is it dont mark the value as selected because it get filled dynamic
I now have to change the code so when i select it it must marked is as selected

A: I would use a repeated function to compare the value against the row value
<?php
    function selected($a, $b) {
        return ($a === $b) ? ' selected' : '';
    }
?>

<option name="school" value="My School" <?= selected($row["school_name"], "My School"); ?>>My School</option>

<option name="school" value="Your School" <?= selected($row["school_name"], "Your School"); ?>>Your School</option>


text:
Q: Change volume serial of vfat partition without reformatting on Linux I'm using a vfat formatted USB stick to play mp3 on my car radio. This device seems to create an index of the connected USB storage in it's own memory. And if I copy additional mp3 tracks to the stick, the index sometimes is not updated and the new tracks can not be played.
But when I connect another stick, it will find all tracks on it. Obviously, the index is updated when the media changes.
I would like to always use the same stick (currentls, it's only half full), add new tracks every now and then, and force the car radio to update it's index by pretending it's another stick.
Copying all files to the PC, reformatting the stick, and copying them back is not an option, because it just will take too long on a 64GB USB2 stick. I've also tried a USB3 stick, but the car radio does not work reliably with it.
So I think the only solution would be to manipulate the volume serial of the stick. Can I do that on Linux ? Preferrably not with low-level tools like dd, hex-editors, ...
This question is related to Change UUID of vfat partition, but when I added an answer just in order to add my use case to the existing question, it was deleted by the admins and they advised me to ask my own question.

A: Hmm, that seems very odd.
First, you should not ask a question in a answer to a question. (use a comment for that).
Second, as the answer to your question is within the refereed link, the admins shouldn't have advised you to ask a new question.
Third, this question now technically qualifies as a duplicate of the linked question, and actually should get closed.
As stated in one of the comments in the referred link, the tool you are looking for is called mlabel from the package mtools.
The comment also provides an example:
sudo mlabel -i /dev/mmcblk0p1 -N 12345678
whereby the serial number of the vfat partition ( e.g. 1234-5678) is provided as 12345678to the mlabel command.


text:
Q: wordpress child theme twentyeleven showing featured images I am trying to make a child theme out of twentyeleven, and so far so good as far as the css goes, but now I want to display a featured image and I don't know how.
I added this to my functions.php;
// add featured images
add_theme_support('post-thumbnails');
set_post_thumbnail_size(500, 200);

Which means featured images are enabled but it still won't show up. I have used featured images in other, premade, layouts so I know I'm not doing anything wrong as far as setting the image goes. I think I have to add a bit of code in my single.php file or maybe my post.php file? I found this piece of code;
if (has_post_thumbnail()) {
    the_post_thumbnail();
}

and put in my (empty) single.php file of my child theme but it didn't work. What piece of code do I need and where do I need to put it to show these featured images?

A: <?php echo get_the_post_thumbnail($post_id, 'large', array('class' => 'class_here')); ?>

or if you want to link to another size:
<?php
if ( has_post_thumbnail()) {
    $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id(), 'large');
    echo '';
    the_post_thumbnail('large');
    echo '';
}
?>

More in codex WP
Hope this helps
/Paul


text:
Q: How does Table behave differently? I have some functions, that I cannot break down to a reasonable MWE, so I'm going to try for an abstract question without providing the code. If need be, I'll include the extra code.
I have some functions that do some stuff. They seem to work when executed directly. When I put them in a Plot it's really slow, because function evaluations can be 1 second each. So I'm making a Table of values for a ListLinePlot, which is quicker (I've tried PerformanceGoal and Mesh and they were all slow). My problem is that I get errors that I cannot reproduce directly/manually. One example is if I run the following code,
maxThresh[findQ2[6]]

I get,
0.172831

But if I run,
Table[maxThresh[findQ2[q1]], {q1, {6}}]

I get,
During evaluation of In[702]:= NMinimize::nrnum: The function value -0.00996218+0.113392 I is not a real number at {x} = {0.516997}. >>

and a whole bunch more of similar errors. So the direct evaluation worked and gave me the right numerical answer, and the Table evaluation gives me an error. I was hoping to gain an understanding as to how these two things are at all different. Does Table not simply loop over the values and substitute in for q1? There is a subtlety here, because running that function with the value 6 works (btw, it works for most values, but 20% fail with errors like these, that I cannot reproduce if I just execute the function directly).
Still haven't got my head around Mathematica substitutions...


text:
Q: how to generate private key with Keytool when generating CSR Apple server require a CSR(CertificateSigningRequest) in order that apple MFI provide a pem certificate.
I generated the CSR with the following keyhole commands:
keytool -genkeypair -keystore mycompany.jks -alias mycompany.com -keyalg RSA -keysize 2048 -dname "CN=MFi-111111, O=MYCOMPANY Inc."
keytool -certreq -keystore mycompany.jks -alias mycompany.com -sigalg SHA256withRSA

but when I want to connect to the apple server it's required to use the private key with the certificate I got from apple.
How to generate the private key with Keytool from mycompany.jks ?

A: First export from keystore file ("JKS") to standardized format PKCS
keytool -importkeystore -srckeystore mycompany.jks -destkeystore keystore.p12 -deststoretype PKCS12 -srcalias mycompany.com -deststorepass mypassword -destkeypass mypassword

then with openssl export unencrypted private key (convert from p12 to pem):
openssl pkcs12 -in keystore.p12  -nodes -nocerts -out key.pem


text:
Q: .NET Database project and encrypted procedures Is there any way how use database project and have encrypted stored procedures?
I need to have encrypted stored procedures like this:
CREATE PROCEDURE [dbo].[test]
WITH ENCRYPTION
AS
    SELECT 1

but when I do Schema compare against DB with encrypted stored procedure, it displays me:
CREATE PROCEDURE [dbo].[test]
WITH ENCRYPTION
AS
BEGIN
--The script body was encrypted and cannot be reproduced here.
    RETURN
END
GO


text:
Q: OpenStreetMap and Hadoop I need some ideas for a weekend project about Hadoop and OpenStreetMap.
I have access to AWS EC2 instance with OpenStreetMap snapshot in my EBS volume.
The OpenStreetMap data is in a PostgreSQL database.
What kind of MapReduce function can be run on the OpenStreetMap data, assuming I can export them into xml format, and then place into HDFS ?
In other words, I am having a brain cramp at the moment, and cannot think what kind of MapReduce operation that can extract valuable insight from the OpenStreetMap xml?
(i.e. extract all the places designated as park or golf course. But this needs to be done once only, not continuously)
Many Thanks

A: *

*An interesting idea of my coworkers is to find nodes which are not connected, but should be. For example a street which abruptly ends and continues 1m further in a separate path.

*Precalculate shortest paths


text:
Q: Jump to complex filter trim? Example:
ffmpeg.exe -i "input1.mp4" -filter_complex "[0:v]trim=start=3624.005:end=3630.005,setpts=PTS-STARTPTS[vidFinal];" -map [vidFinal] output.mp4

ffmpeg just reads through the entire video file just to cut 6 seconds out of the video. Is there a way to avoid this with -filter_complex? Because I have multiple trims of multiple large video files and reading through a couple of 6 hour video files when needing only 6 seconds parts is too much.


text:
Q: Is there a way to identify and remove similar GPS tracks in PostGIS or ArcGIS? I have a large number of GPS tracks from a number of different users. I'd like to identify tracks that take the same route and remove those duplicates. For example, a user takes the same streets from the same origin/destination, but obviously with GPS accuracy issues, the lat/longs aren't exactly the same.
Any sort of intersect function simply provides a large set of intersecting sections, but doesn't compare a full track from start to finish.
Currently using PostGIS, but trialing in ArcGIS to visualize and test a procedure before applying it to the 1,000+ tracks and 8 million datapoints.

A: @relet seems to be going in the right direction but I think it would be better to create
ST_Buffer around the lines and then use ST_AREA on the intersection of the two buffers and compare it to the area of the buffer of each track. Determining if the tracks go in the same direction would be more difficult though, comparing of segments suggested earlier seems to be the best.

A: The ST_Hausdorffdistance can be used to compare each line_geom against every other one with the same user_id. 500 feet is my boundary to check the two trips' origin points distance from each other to confirm the same route direction and the difference in trip lengths is determined before computing the Hausdorff distance.
A Hausdorff distance that is less than 5% of the total trip length, for our project's purpose denotes two routes that take essentially the same path (that part is in a separate query).
SELECT a.user_id AS user_id_a, a.trip_id AS trip_id_a, b.trip_id as trip_id_b,
ST_Length(a.line_geom) AS a_trip_length,
(CASE
WHEN abs(ST_Distance(a.orig,
        b.orig)) < 500 AND abs(ST_Length(a.line_geom)-ST_Length(b.line_geom)) < 500 THEN
        ST_HausdorffDistance(a.line_geom,b.line_geom) END) AS max_dist_diff
FROM t_routes_lines a, t_routes_lines b
WHERE a.user_id = b.user_id
ORDER BY a.user_id, a.trip_id asc, b.trip_id asc;

A: From the way you write it, the order of the points in the track is not important.
Assuming this, you can split each track into its individual points.
Now, for every two tracks, calculate the sum of distances (or their squares) from each point in the one track, to any point in the other track. If the sum remains below your threshold, the tracks can be considered equal.
If that sum reaches a certain threshold, you can assume that the two tracks are distinct, and continue. In most of the cases, that threshold will be reached with the first point you consider, so the loop should complete reasonably fast. Depending on your threshold function and the differences you expect, you may want to divide by the total length of the track.

A: Depending on how accurately you must do the matching and how valuable it is to you, and assuming these tracks lie on streets (as you hint in your question), you could convert your tracks to routes on the street network. Once you've done the conversion, the routes are directly comparable. Of course, this raises the question of how to convert the tracks to routes on the street network (and requires that you have a database of all the streets.)
I would approach the conversion by taking the street network, buffering each street, then intersecting the track with the street buffers. If the track really is following streets, you should be able to find each segment on the street network from the beginning intersection to the ending one on each street. Not a trivial undertaking, but it would be very accurate for matching purposes.


text:
Q: Getting null values in FB request response dictionary I am trying to fetch all list of albums in a logged in facebook account with the following code...
But unfortunately i am not able to get any list at all th result is dictionary..is like
{
    data =     (
    );
}

Any idea what i did wrong in the below code...
 FBRequest* friendsRequest = [FBRequest requestForGraphPath:@"me/albums"];

   [friendsRequest startWithCompletionHandler: ^(FBRequestConnection*connection,NSDictionary* result,NSError *error) {
                                                          if(!error)

                                                       {
                                                              NSLog(@"%@",result);
                                                              //NSArray *albums;

                                                          }

Here is the full method
- (BOOL)retrieveFacebookPhotosWithCompletionBlock:(void (^)(NSArray *, NSError *))completionBlock
{
    //FBSession *activeFBSession=[FBSession activeSession];

    //activeFBSession.state;

    [FBSession openActiveSessionWithReadPermissions:nil
                                       allowLoginUI:YES
                                  completionHandler:^(FBSession *session,
                                                      FBSessionState state,
                                                      NSError *error) {
                                      if (error) {

                                          NSLog(@"Error");
                                      } else if (session.isOpen) {

                                          [[FBRequest requestForMe] startWithCompletionHandler: ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
                                              if (error) {
                                                  //error
                                                  completionBlock(nil, error);
                                              }else{
                                                  FBRequest* friendsRequest = [FBRequest requestForGraphPath:@"me/albums"];

                                                  [friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,NSDictionary* result,NSError *error) {
                                                      if(error)
                                                          completionBlock(nil, error);
                                                      else
                                                      {
                                                          NSLog(@"%@",result);
                                                          //NSArray *albums;

                                                      }
                                                  }];
                                              }
                                          }];

                                      }
                                  }];

        return YES;
}

A: you need to get permission for "user_photos" for getting the albums.
When I tried it without the permissions then I received the same response as you. Using graph api explorer
When I got new access_token with permission than I received proper response from the api.

A: To get access to photos you need user_photos permission while you open the Facebook session.Try to change the code as below.
[FBSession openActiveSessionWithReadPermissions:
[NSArray arrayWithObjects:@"user_photos",nil] allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
                                         //YOUR CODE
                                           }];

A: Yes it is because of the permissions you have given .As mentioned above you have to give permission for accessing photos via key user_photos. Either you can refer the sample project provided by facebook SDk for more keys and the particular permissions each offer.or the facebook developer page.


text:
Q: Highcharts load ajax via Json I can't parse my Json response correctly. Basically I have a function with my highchart:

*

*I send some post parameters and I get a Json response.

*I use json encode and json headers on my php File.

*I get a Json response.

*I used different ways but I can't parse the json result in order to activate my highcart function.

I'm Getting this:

My Code:
JS
function makeChart2(data) {

$('#container23').highcharts({
    chart: {
        type: 'pie',
        options3d: {
            enabled: true,
            spacingLeft: 0,
            spacingRight: 0,
            alpha: 45
        }
    },
    title: {
        text: "2dfdf"
    },
    subtitle: {
        text: ('Datos Extraídos de las Encuestas')
    },

    plotOptions: {
        pie: {
            innerSize: 100,
            depth: 45,

            dataLabels: {
                format: '<b>{point.name}</b>: {point.percentage:.1f} %',

                enabled: true,
                distance: 45,

            },

        }
    },
    series: [{
        name: 'Respuestas',
        data: data
    }]
});

};

var dataString = '&opper=' + opper + '&sel3=' + valueSelected + '&sel4=' +   nationality;

$.ajax({
type: "POST",
url: "select-ajaxselect3.php",
data: dataString,
cache: false,
async: false,
dataType: "json",
success: function(response) {

    makeChart2(response);
}

});

RESPONSE (PHP)
"[['er',1],['erer',0],['erer',0],['er',3],['er',0]]"

A: Ok, The JS code is fine.
But the PHP Json Response not.
We have to ensure Json is valid.
Instead
"[['er',1],['erer',0],['erer',0],['er',3],['er',0]]"

This
"[["er",1],["erer",0],["erer",0],["er",3],["er",0]]"

A: Single Quotes '..' inside JSON is not correct format of JSON
"[['er',1],['erer',0],['erer',0],['er',3],['er',0]]"

Your PHP response should be
'[["er",1],["erer",0],["erer",0],["er",3],["er",0]]'

If you are getting reponse like this and can't change then you need to replace single quote with double quotes.
response = response.replace(/\'/g, '"');


text:
Q: What is the name of this 3D shape? I plotted $z = x^2+y^2$ and got this shape. Is there a name for this shape?
How about $z \ge x^2 + y^2$ ?

A: The surface is a "circular paraboloid" (a special case of the "elliptic paraboloid"). Slices by planes perpendicular to the $z$ axis are (concentric) circles, while slices by planes parallel to the $z$ axis are (identical) parabolas.
It's an example of a surface of revolution, in this case obtained by revolving the basic parabola shape (think $y = x^2$) about its axis.
The filled counterpart would simply be a "solid circular paraboloid".

A: A paraboloid, see the Wikipedia page:
https://en.wikipedia.org/wiki/Paraboloid


text:
Q: PushJS does not open link when click in notification Using PushJS libary to use Push Notifications, when I add link option

A relative URL path to navigate to when the user clicks on the
notification on mobile (e.g. if you want users to navigate to your
page http://example.com/page, then the relative URL is just page). If
the page is already open in the background, then the browser window
will automatically become focused. Requires the serviceWorker.js file
to be present on your server to work.

Does not work when clicking.
const showButton = document.querySelector(".show-button");

showButton.onclick = function() {
    Push.create("Notion TIIIIME!!", {
        body: "Dá uma olhada nas suas obrigações lá o Notion!",
        icon: "",
        timeout: 5000,
        requireInteraction: true,
        link:"https://www.notion.so/",
        onClick: function() {
            console.log(this);
        }
    });
};


text:
Q: Failed to convert value of type 'java.lang.String' to required type 'java.time.LocalDateTime' (Spring Boot) Estoy teniendo problemas para poder hacer funcionar esta pequeña aplicación en Spring Boot. La cual consiste en traer todos los "clientes" que hayan sido registrados entre 2 fechas.
Colocare aquí el código:
Entidad
@Entity
@Setter
@Getter
@Table(name = "clientes")
public class Cliente implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private Long id;

    @Column(name = "nombre")
    private String nombre;

    @Column(name = "apellido")
    private String apellido;

    @Column(name = "fecha_de_registracion")
    private LocalDateTime fechaDeRegistracion;
}

Repositorio:
@Query(value = "SELECT * FROM clientes WHERE fecha_de_registracion >= :desde AND
fecha_de_registracion <= :hasta", nativeQuery = true)
List<Cliente> findClientesRegistrados(LocalDateTime desde, LocalDateTime hasta);

Servicio:
    @Transactional
    public List<Cliente> findClientesRegistrados(LocalDateTime desde, LocalDateTime hasta)
     throws Exception {
        try {
            return clienteRepository.findClientesRegistrados(desde, hasta);
        } catch (Exception e) {
            throw new Exception(e.getMessage());
        }

Controlador:
@GetMapping("/buscarClientes/{desde}/{hasta}")
    public ResponseEntity<?> getClientesRegistrados(@PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime desde,
                                                    @PathVariable @DateTimeFormat(pattern = "yyyy-MM-dd") LocalDateTime hasta) {
        try {
            return ResponseEntity.status(HttpStatus.OK).body(clienteService.findClientesRegistrados(desde, hasta));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("{\"message\": \"Error. Please try again later.\"}");
        }
    }

Y estos son los registros que tengo hasta el momento en mi base de datos (trabajando con MySql):

El endpoint que intento en Postman es el siguiente:
http://localhost:9000/api/v1/clientes/buscarClientes/2021-06-03/2021-06-03
Al ejecutarlo me trae el error del título de esta pregunta. Seguramente estoy cometiendo un error bastante grave.
Aclaración: estoy trabajando en la entidad 'Cliente' con LocalDateTime porque luego tengo que trabajar con las horas y minutos que obtenga de los registros.
Desde ya muchas gracias por cualquier tipo de ayuda!


text:
Q: Cassandra / Hector = Is there a function to jump to a position in the index? does Cassandra/Hector provide a method, that supports "jumping" (=accessing) a specific position in an Index for both and:

((Rows))

and

Columns

I know of tombstones... I would not mind... (they can be included in the results/calculation)
IMPORTANT: I know that Rows are distributed over a lot of machines. So the question applies mainly to Columns (that reside on one machine).
I am looking for use cases like "Give me the "Record=((Row))/Column" that is exaclty in the middle of the index... Or give me the "Record=((Row))/Column" that is at Position 454654. Both for Rows and for Columns.
Is this somehow supported like getColumAtIndexPosition(int index) ? If not, why not? Wouldn't it be easy to just internally count the index records up to the correct position in Cassandra an return the rsult?
Thanks very much!
Jens

A: There isn't such a function.
Hector is a layer over the Cassandra api.  For retrieving columns, the Cassandra api method that comes closest to what you want is get_slice, which allows you to perform queries such as get the first N columns where column name is > X, or all the columns whose name is between X and Y, but not the 500'th column.


text:
Q: Python: How do I find which pip package a library belongs to? I got a script transferred from someone else. And there is a module imported into the script. I'm wondering what is the best way to find out which pip package installed this library (other than search online).
I tried to import the package and then just do help() on it but didn't got much information. Is there a reliable and pythonic way to achieve this?
For example:
In the script it has a line
from impala.dbapi import connect

Without searching on internet, how can I find out that following package can install this library? as you can see in this case the package name is is different from the name used in pip.
pip install impyla

A: If you do not have the package installed, you'll have to use a pip search or a poetry search (or a Google search).
In the case you have the package already installed (i.e. you can import it) , you can get the package name with importlib.metadata:

*

*In Python >=3.8, you can use the standard library importlib.metadata

*For Python <3.8, there is importlib_metadata (link to documentation). Replace importlib.metadata with importlib_metadata in the examples below.
Example on usage:
>>> from importlib.metadata import packages_distributions

>>> packages_distributions()

 'asttokens': ['asttokens'],
 'backcall': ['backcall'],
 'bitarray': ['bitarray'],
 'colorama': ['colorama'],
 'decorator': ['decorator'],
 'executing': ['executing'],
 'importlib_metadata': ['importlib-metadata'],
 'impala': ['impyla'],
 'IPython': ['ipython'],
 'jedi': ['jedi'],
 'matplotlib_inline': ['matplotlib-inline'],
 'parso': ['parso'],
 'pickleshare': ['pickleshare'],
 'pip': ['pip'],
 'prompt_toolkit': ['prompt-toolkit'],
 'pure_eval': ['pure-eval'],
 'puresasl': ['pure-sasl'],
 'pygments': ['Pygments'],
 '_distutils_hack': ['setuptools'],
 'pkg_resources': ['setuptools'],
 'setuptools': ['setuptools'],
 'six': ['six'],
 'stack_data': ['stack-data'],
 'thrift': ['thrift'],
 'thrift_sasl': ['thrift-sasl'],
 'traitlets': ['traitlets'],
 'wcwidth': ['wcwidth'],
 'zipp': ['zipp']}

In this case, you would look for the "impala" entry in the packages_distributions() dictionary:
>>> packages_distributions()['impala']
['impyla']

You may also check for example the version of the package:
>>> from importlib.metadata import version

>>> # Note: Using the name of the package, not the "import name"
>>> version('impyla')
'0.18.0'

Bonus: Checking the name of the module from a function or class name
>>> connect.__module__.split('.')[0]
'impala'

Note that this does not guarantee that a package was installed from PyPI. You could, if you want, create your own package called "impyla", "matplotlib", whatsoever, install it, and use it as you wish.

A: Short answer: You can't.
The core of the reason is that the name to import the package and the name to install the package come from different namespaces. When you run the import command, Python is looking for the package in the local environment. When you tell pip to install a package, it's looking for something to install from PyPI (or somewhere else if you told pip to look elsewhere).
It would make sense for these two names to always be the same, but there's no guarantee. Installation is a matter of choosing which set of files to download and install, while importing is a matter of choosing what installed files to run, but the names for those files do not have to stay the same during the installation process. And that's how we get confusion like pip install impyla, import impala.
If you had access to the setup.py file for the package, you could look in there for the name (if you look at the GitHub for impyla/impala, you'll see a name='impyla', line inside the call to setup), but if the package was installed via pip, you won't have the setup.py file locally, so this option is pretty much right out.
It's not a great state of affairs. There's simply no guarantee that you can find the PyPI name for a package from just having local access to the package code and the "real" import name for the package. That said, if you're unfamiliar with the package anyway, you're probably going to want to look up documentation and more info on the internet anyway. Just one more thing to look up, I guess.


text:
Q: Find and classify critical points of $\ f(x,y)=\cos(x^2 + y^2)$ I have to classify the critical points of$\ f$, but the problem says to only consider the points$\ (0,0),\left(\sqrt{\frac{π}{2}},\sqrt{\frac{π}{2}}\right)$.
So, long story short, after using the second derivative test I got that$\ D=0$ at both critical points.
How should I proceed with this problem?

A: At $(0,0)$, the function has a local maximum, because $f(0,0)=1$ and $f(x,y)<1$ if $(x,y)$ is near to (but distinct from) $(0,0)$.
At $\left(\sqrt{\frac\pi2},\sqrt{\frac\pi2}\right)$, $f$ has a local minimum, although not a strict one. In fact $f(x,y)=-1$ at every point of the circle $x^2+y^2=\pi$ (to which the point $\left(\sqrt{\frac\pi2},\sqrt{\frac\pi2}\right)$ belongs) and $f(x,y)>-1$ at all other points near $\left(\sqrt{\frac\pi2},\sqrt{\frac\pi2}\right)$.


text:
Q: Ubuntu doesn't read some DVD discs I have some DVD discs which are not read by Ubuntu (16.04). I have 16 DVD discs with TV series (4 seasons, every season has 4 DVDs), in every season there is one DVD disc containing 4 episodes and 3 discs with 3 episodes. I can watch movies from all the discs with 3 episodes but discs with 4 episodes don't work. I tried to run the discs in VLC - nothing happens while trying to open disc. I also tried to run it in Totem - then I get an error "cannot run a movie".
I have Windows 8 on this computer (with the same DVD drive) and I can play these DVDs in VLC on Windows, so these DVD discs are OK and it's not a hardware issue.


text:
Q: PHP Fatal error: Uncaught exception PharException with message manifest while trying to install  composer.phar through command line  , got an error
 PHP Fatal error: Uncaught exception 'PharException' with message manifest cannot be larger than 100 mb in phar

please support me to solve this problem, i am trying to installing symfony2.1

A: It appears you got a corrupted phar for some reason. Try downloading a new one from https://getcomposer.org/download/ - if the CLI instructions do not work out for you you can just download the last snapshot by hand from https://getcomposer.org/composer.phar


text:
Q: How to create statistics from output of Java code?
Summary: I need a function based on the output. The problem is
  connecting Eclipse or a Java code with another software.

I'm studying Physics. I needed a code that works the following way:

*

*first, it declares a random number n;

*then it outputs a "winner" number (based on some rules; the code
itself is irrelevant now I think), 20 times (but should be more,
first I need something to record the values, though).

I have n and 20 other numbers which are each between 1 and n (including 1 and n). I want, after compiling the code once, to see the 20 values, how they are distributed (for example, are they around one particular number, or in a region, is there a pattern (this is based on the rules, of course)).
The problem is, I'm only familiar with basic Java (I used eclipse), and have no clue on how I should register for example 2000 instead of the 20 numbers (so for an n number the code should print 2000 or more numbers, which should appear on a function: domain of the function is 1, 2, ..., n, and range is 0, 1, ..., 2000, as it might happen that all 2000 numbers are the same). I thought of Excel, but how could I connect a Java code with it? Visual interpretation is not necessary, although it would make my work easier (I hope, at least).
The code:
import java.util.Random;
public class korbeadosjo {
public static void main(String Args[]){
Random rand = new Random();
int n = (rand.nextInt(300)+2);
System.out.println("n= " + n);

int narrayban = n-1;
int jatekmester = n/2;
int jatekmesterarrayban = jatekmester-1;

System.out.println("n/2: " + jatekmester);
for(int i=0; i<400; i++){
    int hanyembernelvoltmar = 1;
    int voltmar[] = new int[n];
    voltmar[jatekmesterarrayban]=1;
    int holvan=jatekmester;
    int holvanarrayban = holvan-1;
    fori: for(;;){
        int jobbravagybalra = rand.nextInt(2);
    switch(jobbravagybalra){
    case 0: //balra
        if(holvanarrayban ==0){
            holvanarrayban = narrayban;
        }else {
            --holvanarrayban;
        };
        if(voltmar[holvanarrayban]==0){
            voltmar[holvanarrayban] =1;
            ++hanyembernelvoltmar;
        }
        break;
    case 1: //jobbra
        if(holvanarrayban == narrayban){
            holvanarrayban = 0;
    } else {++holvanarrayban;};
    if(voltmar[holvanarrayban]==0){
        voltmar[holvanarrayban]=1;
        ++hanyembernelvoltmar;
    }
    break;

    }if(hanyembernelvoltmar==n){
        System.out.println(holvanarrayban+1);
        break fori;
    }}}}}

A:
basic Java (I used eclipse)

Unrelated.
I could only find two prompts in your question:

How to create statistics from output of Java code?

You are likely not wanting to get the output alone. Use those numbers in your Java program to find what you want and output it.
How did you store 2000 values? An array, list, queue...? So also iterate on that data structure and generate the statistics you need.

I thought of Excel, but how could I connect a Java code with it?

There is this site.


text:
Q: MVC linq keeps returning the last row of data I'm trying to get some data from 3 combined tables.
My class is ProizvedeniProizvodiBO which consists of three classes within it (ProizvodBO, ProizvodjacBO, ProizvodnjaBO). The classes all mimic the structure of tables.
Here's the code:
public IEnumerable<ProizvedeniProizvodiBO> NadjiProizvod(int idProizvoda)
{
            List<ProizvedeniProizvodiBO> lista = new List<ProizvedeniProizvodiBO>();
            Proizvod proizvod = azilEntities.Proizvods.FirstOrDefault(x => x.idProizvoda == idProizvoda);
            ProizvodBO trazeniProizvod = new ProizvodBO();
            ProizvodjacBO trazeniProizvodjac = new ProizvodjacBO();
            ProizvodnjaBO trazenaProizvodnja = new ProizvodnjaBO();
            ProizvedeniProizvodiBO noviProizvedeniProizvod = new ProizvedeniProizvodiBO();
            trazeniProizvod.IdProizvoda = proizvod.idProizvoda;
            trazeniProizvod.Kolicina = proizvod.kolicina;
            trazeniProizvod.NazivProizvoda = proizvod.nazivProizvoda;

            foreach (Proizvodnja proizvodnja in azilEntities.Proizvodnjas.Where(x => x.idProizvoda == idProizvoda))
            {
                trazenaProizvodnja.IdProizvoda = proizvodnja.idProizvoda;
                trazenaProizvodnja.IdProizvodjaca = proizvodnja.idProizvodjaca;
                trazenaProizvodnja.DostupneKolicine = proizvodnja.dostupneKolicine;

                Proizvodjac proizvodjac = azilEntities.Proizvodjacs.FirstOrDefault(x => x.idProizvodjaca == proizvodnja.idProizvodjaca);
                trazeniProizvodjac.IdProizvodjaca = proizvodjac.idProizvodjaca;
                trazeniProizvodjac.NazivProizvodjaca = proizvodjac.nazivProizvodjaca;
                trazeniProizvodjac.Grad = proizvodjac.grad;
                trazeniProizvodjac.Ulica = proizvodjac.ulica;
                noviProizvedeniProizvod.proizvod = trazeniProizvod;
                noviProizvedeniProizvod.proizvodjac = trazeniProizvodjac;
                noviProizvedeniProizvod.proizvodnja = trazenaProizvodnja;
                lista.Add(noviProizvedeniProizvod);
            }
            return lista;
}

It returns the correct amount of rows (let's say there's 3 different combinations) but every row it returns is absolutely the same, and always the last row (I manually checked).
I tried running the relevant commands in SQL and they work as they should.
I am forwarding the data to a view.
Proizvod would basically translate to Product, Proizvodjac to producer and Proizvodnja is the table in the middle that is connecting them. Proizvodnja has 2 primary keys (idProizvoda and idProizvodjaca).
Any help?

A: What you need is to move instantiating of your objects to your foreach loop, then everything works as expected, something like this:
foreach (Proizvodnja proizvodnja in azilEntities.Proizvodnjas.Where(x => x.idProizvoda == idProizvoda))
{
    ProizvedeniProizvodiBO noviProizvedeniProizvod = new ProizvedeniProizvodiBO();

The reason is ProizvedeniProizvodiBO is a reference type so actually, when you are creating a new object outside of the loop and then assigning the values to the new object every time in your loop it will override the last data because it is a reference type. Therefore all of items inside your list are referring to the same object.


text:
Q: Ordinal-universal linear order on $\kappa$ elements The starting point of this question is the observation that if $\lambda$ is a countable ordinal, then there is an order-embedding $e:\lambda \hookrightarrow \mathbb{Q}$.
Given an infinite cardinal $\kappa$, is there a linearly ordered set $L_\kappa$ of cardinality $\kappa$ such that for every ordinal $\alpha$ with $|\alpha|=\kappa$ there is an embedding $e:\alpha \hookrightarrow L_\kappa$?

A: Let $\lambda$ be an infinite cardinal. Give $[\lambda]^{<\omega}$ the linear ordering $\leq$ where we set $A>B$ if there is some $\alpha\in B$ where $\alpha\cap A=\alpha\cap B$ and $\alpha\not\in A$.
We shall show using what is essentially transfinite induction that every ordinal less than $\lambda^+$ embeds into $[\lambda]^{<\omega}$. Suppose that $\alpha$ is the least ordinal where $\alpha$ does not embed into $\lambda^+$. Clearly $\alpha>0$. If $\alpha$ is a successor ordinal, then $\alpha=\beta+1$ for some $\beta$ and there is some embedding $f:\beta\rightarrow[\lambda]^\omega$. Now, define $g:\alpha\rightarrow[\lambda]^\omega$ by letting
$g(\delta)=\{0\}\cup\{1+\sigma\mid \sigma\in f(\delta)\}$ whenever $\delta<\alpha$ and by letting $g(\beta)=\emptyset$. Then $g$ is an order preserving embedding, so $\alpha$ cannot embed into $\lambda^+$. Now suppose that $\alpha$ is a limit ordinal. Then let $(x_\beta)_{\beta<\gamma}$ be a cofinal continuous increasing sequence in $\alpha$ with $x_0=0$ where $\gamma$ is a cardinal with $\gamma\leq\lambda$. Then for each $\beta<\gamma$, let
$f_\beta:[x_\beta,x_{\beta+1})\rightarrow[\lambda]^{<\omega}$ be an embedding. Then define an embedding $f:\alpha\rightarrow[\lambda]^{<\omega}$ by letting
$f(x)=\{\beta\}\cup\{\beta+1+\delta\mid \delta\in f_\beta(x)\}$ whenever $x\in[x_\beta,x_{\beta+1})$.
Observe that $[\lambda]^n$ is a well-ordered of order type $\lambda^n$ whenever $n\in\omega$. Therefore $[\lambda]^{<\omega}$ is the union of countably many well-ordered sets. Every totally ordered set $X$ which is the union of countably many well-ordered sets has no descending sequence of length $\omega_1$. Therefore, $[\lambda]^{<\omega}$ has no descending sequence of length $\omega_1$.

A: Let me mention one easy observation, which is that the order $2^{<\kappa}$ is universal for all linear orders of size $\kappa$. View the order as $\{-1,1\}^{<\kappa}$, where strings are ordered lexically, so that at the first difference, if the digit is $-1$ it is lower, and if $1$ it is higher. This is the same as the Surreal number line, generating for birthdays up to $\kappa$.
It often happens in set theory that $2^{<\kappa}$ has size $\kappa$, in which case this order is a linear order of size $\kappa$ that is universal for all linear orders of size $\kappa$. For example, this is true for $\kappa=\omega$, and it is true for any $\kappa$ under the generalized continuum hypothesis.
Meanwhile, it is consistent with ZFC that $2^{<\kappa}$ is strictly bigger than $\kappa$, and in these cases this order is larger than desired. There are quite subtle set-theoretic issues arising in these cases, discussed in the references mentioned at the other question, mentioned in the comments.
Lastly, you had asked for universality with respect to the ordinals of size $\kappa$, rather than all linear orders of size $\kappa$. I find it interesting to wonder whether these are the same---if a linear order of size $\kappa$ is universal for ordinals up to $\kappa^+$, must it be universal for all linear orders of size $\kappa$?


text:
Q: Selenium vba, How to avoid open "_blank" link to new tab HTML
google
VBA
driver.FindElementById("mylink").Click
How can I have the "driver" object refer to the new browser TAB or just open the link in the same browser TAB instead of opening into a new browser TAB even the link has a target="_blank" attribute.

A: I never used selenium, but I think you should be able to get href attribute value and open that as a link, something like:
driver.get( driver.FindElementById("mylink").getAttribute("href") );


text:
Q: Background of UILabel visible after a composite I am doing something a bit unusual.  I'm trying to tint all the components in my application red (you may have seen some other postings from me about this, but this is something more specific).  To do so, I'm intercepting all calls to CALayer's drawInContext: and after calling the original method, I composite red onto the layer using kCGBlendModeDarken (or kCGBlendModeMultipy).  This works surprisingly well for most UI components.  However, when I do this with UILabels, the previously transparent background becomes white (well, actually a red-tinted white).  You can see what this looks like in this image of my toolbar
http://www.thinkastronomy.com/RedLabels.png
Note that the UIImages also aren't tinted, but that is the topic of another question.
So can anyone explain why the UILabel background would be made visible by this compositing?  It seems to happen pretty much independent of the compositing mode.  How can I prevent this?

A: Is opaque set to NO on the labels and all transparent views behind them?  The opaque value is a quirk in UIViews that can cause problems with transparent backgrounds.  From the docs: "YES if it is opaque; otherwise, NO. If opaque, the drawing operation assumes that the view fills its bounds and can draw more efficiently. The results are unpredictable if opaque and the view doesn't fill its bounds. Set this property to NO if the view is fully or partially transparent. The default value is YES."


text:
Q: OpenCV detecting an application frame from a set of screenshots I have this problem, I would like to detect a particular window, from a set of screenshots. If i have 100 screenshots I would like to figure out which ones contain iTunes. I am still a noob when it comes to openCV, do i have to train and create a haar file for this or is there a simpler solution since application frames are not that different?

A: There are many different ways you could go about identifying an image containing iTunes amongst 100 screenshots.
The particular route you take will depend greatly on the details of your problem:

*

*Are you always looking for iTunes?

*How accurate does this have to be?

*Are false positives acceptable? How about false negatives?

*Are the screenshots always from the same system?

*Will iTunes always be maximized?

*Will the desktop background ever change?

*Must this identify iTunes under different conditions, e.g. coverflow, visualization, iTunes store?

*Will iTunes always look the same?

For starters, I would look at the absolute simplist metrics you can think of and see if they distinguish your iTunes from non-iTunes images.  For example, maybe there are more gray pixels in the iTunes images than in any other. In that case you could just count gray pixels.
If that doesn't work, consider making histograms of colors. Presumably iTunes uses the same colors most of the time (gray, white light blue and green). You could then build up a library of different color histograms corresponding to iTunes use cases (playlist, iTunes store, coverflow, etc) and identify images that contain iTunes by matching histograms. See this example from the O'reilly OpenCV book.


text:
Q: Moment Generating Function Supremum I'm studying probability, and am having trouble with the following:

Let $X$ be a uniform R.V. on $[0,1]$. Compute the moment generating function $M(t)$ of $X$. Compute $I(y) = \sup_{t \in \mathbb{R}}\{ty - \ln M(t)\}$.

Computing the moment generating function is easy enough; it's $M(t) = \begin{cases} \frac{1}{t}(e^t-1) &t\neq 0 \\ 1 &t=0 \end{cases}.$
However, I don't see how to compute $I(y)$.
I can see it is $$\sup_{t \in \mathbb{R}}\{ty - \ln M(t)\} = \sup_{t \in \mathbb{R}}\{\ln \left( e^{ty}/ M(t) \right) \}.$$
For $y \geq 1$, this seems to approach infinity as $t \to \infty$. For $y < 0$, the value goes to infinity as $t \to -\infty$.
For $y \in [0,1)$, the value goes to $-\infty$ as $t \to \infty$ and as $t \to -\infty$.
The desired supremum is attained when the argument $te^{ty}/{(e^t-1)}$ achieves its maximum. Its derivative is zero when
$$ M(t) = \frac{e^t-1}{t} = \frac{e^t}{yt+1}. $$
This doesn't seem to lead anywhere though. Is there some nifty probability trick to this? I think there must be a way to use the fact that $M$ is moment generating function, but I'm not seeing it...


text:
Q: Get an object property Here I have a problem for get and use the properties of an object, I don't understand why I'm stuck on the last few days ... I made a screenshot which may have see the list of properties and methods of the object.
In this case I would go to the "result" property. Problem: When I do "console.log (objet.result)", it returns me "undefined".
It's indeed a XHR object. The script upload files, it uses mainly this plugin : https://github.com/blueimp/jQuery-File-Upload/wiki/API
and here below the code of the script (look around the line "if(progress == 100)") :
$(function(){
var ul = $('#upload ul');

$('#drop a').click(function(){
    // Simulate a click on the file input button
    // to show the file browser dialog
    $(this).parent().find('input').click();
});

// Initialize the jQuery File Upload plugin
$('#upload').fileupload({

    // This element will accept file drag/drop uploading
    dropZone: $('#drop'),

    // This function is called when a file is added to the queue;
    // either via the browse button, or via drag/drop:
    add: function (e, data) {

        var tpl = $('
<input type="text" value="0" data-width="48" data-height="48"'+
            ' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" />

');

        // Append the file name and file size
        tpl.find('p').text(data.files[0].name)
                     .append('' + formatFileSize(data.files[0].size) + '');

        // Add the HTML to the UL element
        data.context = tpl.appendTo(ul);

        // Initialize the knob plugin
        tpl.find('input').knob();

        // Listen for clicks on the cancel icon
        tpl.find('span').click(function(){

            if(tpl.hasClass('working')){
                jqXHR.abort();
            }

            tpl.fadeOut(function(){
                tpl.remove();
            });

        });

        // Automatically upload the file once it is added to the queue
        var jqXHR = data.submit();
    },

    progress: function(e, data){

        // Calculate the completion percentage of the upload
        var progress = parseInt(data.loaded / data.total * 100, 10);

        // Update the hidden input field and trigger a change
        // so that the jQuery knob plugin knows to update the dial
        data.context.find('input').val(progress).change();

        if(progress == 100){
            data.context.removeClass('working');

            //THE VALUE THAT I WANNA GET IS A PROPERTY OF THE DATA OBJECT
        }
    },

    fail:function(e, data){
        // Something has gone wrong!
        data.context.addClass('error');
    }

});

// Prevent the default action when a file is dropped on the window
$(document).on('drop dragover', function (e) {
    e.preventDefault();
});

});
Please anybody can help me ??
Thankz by advance for your help and good week !

A: I think this is an issue of response. Javascript unable to evaluate the response(its consider as a string).
first solution->
var obj = eval('{' + res + '}');
second solution->
We can Parse result into json using
var response = jQuery.parseJSON(res);
and then access response.result

A: Finally, I've solved my problem.
I did not use the good call back reference to get my data. I put my nose deep in the plugin documentation and I've found an another method than "progress". I must use the "done" callback method if I want to get the "result" value.
However I want to thank you for your help.
Have a nice coding day !!
Mickael


text:
Q: How to create a web app with data from import.io I am fairly new to web dev and I know the basics of html, css, javascript and jquery, so just Front End.
As a challenge to learn more I want to create a web app that does the following:

*

*Get the pictures, description, link and price of rent properties from various sites. For web scraping I would use import.io to get the data I want and then query that API to manipulate and show the data.

*With this data I want to create an aggregator app that would show all the properties querying the import.io database let's say every 15 minutes to get new properties.

My question is how do I do that? What languages I need to learn? Or is just a matter of getting the data from import.io API in JSON form and then displaying it in html?

A: Yes, it' just a matter of getting the data from import.io and display them.
You could create your API in import.io and then do an ajax call in your app
$.ajax({
     "url":"https://api.import.io/store/connector/<yourimport.ioapi>",
     "crossDomain": true,
     "dataType": "json",

     'success': function(response){
    //do what you want with the data
    }
}

Or you could export the data to Google Sheets or plot.ly. You could schedule the API to get new data on a daily or weekly base so it won't make sense to look every 15 min for new data. The scheduler is also a beta feature.


text:
Q: Determinant of matrix with character elements in R I have the following code:
x1 <- c("x", "y")
x2 <- c("z", "w")
X <-data.frame(x1,x2)
A=as.matrix(X)

The matrix A is the following:
      x1  x2
[1,] "x" "z"
[2,] "y" "w"

How can I find the determinant of A? I want a result like xw-yz.
I tried det(A) but it does not work.
In general, I want to be able to find the determinant of any matrix whose elements are of character type.

A: you need a symbolic computation library:
library(rSymPy)

x1 <- List(Var("x"), Var("y"))
x2 <- List(Var("z"), Var("w"))
A = Matrix(x1, x2)
Det <- function(x) Sym("(", x, ").det()")
Det(A)
# [1] "w*x - y*z"

x <- Var("x")
y <- Var("y")
z <- Var("z")
A = Matrix(List(y+z,z,y), List(z,z+x,x), List(y,x,x+y))
Det(A)
# [1] "4*x*y*z"

a <- Var("a")
b <- Var("b")
c <- Var("c")
A = Matrix(List(0,b-a,c-a), List(a-b,0,c-b), List(a-c,b-c,0))
Det(A)
# [1] "0"


text:
Q: Is there a mathematical formula to determine how many diagonal sequences are there in a Tic-Tac-Toe game? C# I'm building a Tic-Tac-Toe game project with C#. My teacher asked me to create an array while its size is the max number of diagonal sequences that are possible in the specific board size (Not only 3x3). Problem now, is that my teacher gave me a wrong formula and it won't calculate it right.
For example, in a 3x3 board, there should be 2 possible diagonal sequences, but the formula calculates only 1.
This is the formula:
(rows-sequence+1)*(cols-sequence+1).
Which means:
(3-3+1)*(3-3+1) = 1
If someone knows the correct formula, I'll be grateful!

A: Think about it like this. How many ways are there to place seq * seq square within row * col rectangle. Teacher gave you that answer. There are two diagonals in any square, so number of what you call diagonals in row * col matrix are just 2 times the value that you get with teachers function.


text:
Q: How do those cheap shoebox-phone projectors throw any "decent" image? You've probably seen them; shoebox phone projectors.

They throw a very dim image, but I'm surprised it throws any image at all, since the lightsource is completely diffuse.
Why does it still somewhat work?
My theories are:

*

*The lens is mounted far from the screen, essentially eliminating most non-parallel rays.

*The phone has a screen that is most bright perpendicular to the screen.

*The lens automagically corrects the image? (Does it?)

If I hold one of these large LED lenses in front of my phone;

it throws an image too, so I'm questioning point 1.
That leaves point 2 and 3. If I watch my phone from the side I can still clearly make out the image on screen, so I cannot believe this is such a big factor.
That leaves point 3; every projector out there denounces projection using diffuse sources. I've seen only one instance of a DIY projector using a tight packed LED matrix as light source.
Can anyone explain why these shoebox projectors (somewhat) work?

A: If the entire screen of a phone is set to white, the screen 'appears' approximately as a diffuse light source. But each individual pixel acts as a point source - i.e. if one pixel is set to white and the rest of the screen is black, then the lit pixel acts approximately like a point source - radiating light in all directions. So you could replace that pixel with a tiny candle and the emitted light would look/behave approximately the same. Now if you have a thin lens with focal length $f$ and a candle at a distance $p$ to one side of the lens, then the lens will focus the candle's light onto a point at distance $q$ to the other side (where $1/p+1/q=1/f$). If the candle is at height $h$ above the centre axis of the lens then the image will be at height $-H$, where $H = (q/p)*h$. ($q/p = m$, where $m$ is the magnification of the system). See the figure below. This is all 'standard' thin lens optics that you would likely be introduced to in an elementary physics course.
If you now add a second candle at the same distance behind the lens but a different height $h'$, then its light would be focused the same distance away, but also at at a different height $H'$. So if you replace the candles by the pixels of a phone (all at the same distance $p$ but different heights (and different sideways displacements too) then each pixel will have it's light focused at distance $q$ on the other side, and with its height and displacement magnified by the ratio $m=p/q$.

A: If it is diffuse... how can you see anything on the screen when you hold the phone? Okay, I don't know how your phone is, but if it is similar to mine, it shows a nice image. It has not really good definition, but I can clearly read whatsapps and watch videos.
It seems you're confused about the term "diffuse". A point light source (if existed) would also emit in all directions, but you would be able to create an image of it. The fact that your phone emits in all directions does not mean it is diffuse. In fact, emmiters use to show a pattern which approximately follos Malus Law.
Diffuse would mean that every point emits in a totally different direction, so your eye couldn't tell if there is something behind that light spot. Your eye cannot extrapolate where the image comes from.
However, altough the phone is a large object, rays leave it with certain angle. For the lens, however, it is LIKE IF the rays came from much farther from an infinitesimal emmiter. The image, consequently, sould be nice enough (besides optical aberations).
The fact that you see it dimmer is because of energy loss through the lens and before it.


text:
Q: Android : JSON Parser with async task (GET and POST methods) Just want to check whether this JSON Parser with async task is it correctly done? When I put this code into my Eclipse, this (method.equals("POST") was underline red. And it state that the 'method' cannot be solved. Any suggestion or help in this? Thank you.
public class JSONParser {

  static InputStream is = null;
  static JSONObject jObj = null;
  static String json = "";
  String url=null;
     List<NameValuePair> nvp=null;
     // constructor
     public JSONParser() {

   }

  // function get json from url
  // by making HTTP POST or GET method
   public JSONObject makeHttpRequest(String url, String method,
        List<NameValuePair> params) {
      BackGroundTask Task= new BackGroundTask(url, method,  params);
    try {
        return Task.execute().get();
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    } catch (ExecutionException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        return null;
    }
}
public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
    List<NameValuePair> postparams= new ArrayList<NameValuePair>();
    String URL=null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
        URL=url;
        postparams=params;
    }
    @Override
    protected JSONObject doInBackground(String... params) {
        // TODO Auto-generated method stub
        // Making HTTP request
        try {
    // Making HTTP request
        // check for request method

    if(method.equals("POST")){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(postparams));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(postparams, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

   }
 }
}

A: You forgot to declare method property in your BackGroundTask class.
EDIT Like this:
public class BackGroundTask extends AsyncTask<String, String, JSONObject>{
    List<NameValuePair> postparams= new ArrayList<NameValuePair>();
    String URL=null;
    String method = null;
public BackGroundTask(String url, String method, List<NameValuePair> params) {
        URL=url;
        postparams=params;
        this.method = method;
    }
    @Override
    protected JSONObject doInBackground(String... params) {
        // TODO Auto-generated method stub
        // Making HTTP request
        try {
    // Making HTTP request
        // check for request method

    if(method.equals("POST")){
            // request method is POST
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setEntity(new UrlEncodedFormEntity(postparams));

            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();

        }else if(method == "GET"){
            // request method is GET
            DefaultHttpClient httpClient = new DefaultHttpClient();
            String paramString = URLEncodedUtils.format(postparams, "utf-8");
            url += "?" + paramString;
            HttpGet httpGet = new HttpGet(url);

            HttpResponse httpResponse = httpClient.execute(httpGet);
            HttpEntity httpEntity = httpResponse.getEntity();
            is = httpEntity.getContent();
        }

    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        jObj = new JSONObject(json);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

   }
 }
}

A: You need to set method as a class variable within BackGroundTask. You are passing it into the constructor but not going anything with it. Set it the same way you have done with url and postparams.


text:
Q: Does load distribution with consistent hashing provide an advantage over standard hashing for stateless servers while scaling a system? I understand that using consistent hashing for load distribution in case of  cache servers or (sharded) database servers offer a significant advantage over usual key-based hashing,  as while adding/removing server the the data movement required between the servers due to rehashing is minimized.
However, if we consider application servers or web servers, which are often designed to be stateless and hence not storing any user/session-related data, does consistent hashing offer any advantage here? If yes, what is the data being considered here or am I missing something?

A: If the server is truly stateless, then yes it doesn't matter. Then you optimize other parameters, like the distance to the client.
But for a server that process some business logic, there is an implicit state in its cache. The server has to have some persistent storage (let's call it a database), local or remote, otherwise the client wouldn't need to make the request if it already had all the information.
The database's or the appserver's cache would be already warmed up, and would have to be re-initialized each time the system scales up or down.
Even if the database is distributed too, the appserver's connection to a specific shard of the database could (or could not) also be a state.


text:
Q: Invalid API key/application pair–Clarifai I was reading the documentation and wanted  try out the api in  pycharm. So I copied the code and it told me that I had an "Invalid API key/application pair". I copied my Api key straight from my app I made on https://portal.clarifai.com/ and put it in.
My code literally an exact copy except api key was deleted I copied straight from my app was deleted, and I running it on pycharm.
`
from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel
from clarifai_grpc.grpc.api import resources_pb2, service_pb2, service_pb2_grpc
from clarifai_grpc.grpc.api.status import status_pb2, status_code_pb2

# Construct one of the channels you want to use
channel = ClarifaiChannel.get_json_channel()
channel = ClarifaiChannel.get_insecure_grpc_channel()

# Note: You can also use a secure (encrypted) ClarifaiChannel.get_grpc_channel() however
# it is currently not possible to use it with the latest gRPC version

stub = service_pb2_grpc.V2Stub(channel)

# This will be used by every Clarifai endpoint call.
metadata = (('authorization', 'Key {9f3d8b8ea01245e6b61c2a1311622db1}'),)
# Insert here the initialization code as outlined on this page:
# https://docs.clarifai.com/api-guide/api-overview/api-clients#client-installation-instructions

post_inputs_response = stub.PostInputs(
    service_pb2.PostInputsRequest(
        inputs=[
            resources_pb2.Input(
                data=resources_pb2.Data(
                    image=resources_pb2.Image(
                        url="https://samples.clarifai.com/metro-north.jpg",
                        allow_duplicate_url=True
                    )
                )
            )
        ]
    ),
    metadata=metadata
)

if post_inputs_response.status.code != status_code_pb2.SUCCESS:
    raise Exception("Post inputs failed, status: " + post_inputs_response.status.description)

`

A: Could you please try generating a new API key and trying that.

A: Philip, your metadata declaration is not correct. You don't put your API key within {}
# This will be used by every Clarifai endpoint call.
metadata = (('authorization', 'Key {9f3d8b8ea01245e6b61c2a1311622db1}'),)

There is an extra } towards the end, please adjust it to this
metadata = (('authorization', 'Key 9f3d8b8ea01245e6b61c2a1311622db1'),)


text:
Q: requiring RX.js in node.js I am getting an error when requiring rx into my file. in the browser console it says "Uncaught ReferenceError: require is not defined"
checked version and ref on github but don't see what it still doesn't work? simply want to try using a alert msg when clicking on the button.
here's my observ.js file located in /js
var Rx = require('rx');
var Observable = Rx.Observable;

var button = document.getElementById('button');

var handler = function(e) {
  alert('clicked!');
};

button.addEventListener('click', handler);

here is my html file located in /public
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
</head>
<body>
    <button id="button">Click me</button>
  <script src="../js/observ.js"></script>
</body>
</html>

here is my express js app just serving html in root folder
var express = require('express');
var app = express();

app.use(express.static(__dirname + '/public'));

app.get('/', function(req, res) {
  res.render('index');
});

app.listen(process.env.PORT || 3000, function() {
  console.log('Express listening on port 3000');
});

A: Looking at the documentation. It looks like you need to use an AMD loader like require.js to run this code on the client side.
For example:
<html>
<head>
    <title>test</title>
</head>
<body>
    <button id='button'>Test</button>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.1.22/require.js"></script>
    <script>
        requirejs.config({
            paths: {
                rx: 'rx'
            }
        });

        requirejs(['rx'], function(Rx) {
          var Observable = Rx.Observable;

          var button = document.getElementById('button');

          var handler = function(e) {
            alert('clicked!');
          };

          button.addEventListener('click', handler);

        });
    </script>
    </body>
</html>

To see working example, follow these steps.

*

*Copy the above code,

*Create a new local folder / html file

*Paste the above code in the HTML file

*Create a new file called rx.js at the root of your new folder

*Copy rx code from here and paste it in the rx.js file
Note: I have verified that this works. But you may want to also look at browserify if you are looking for more of an Isopmorphic approach.

A: For use node-module in frontend , use browserify. By default, Javascript dont have keyword require, module, exports


text:
Q: How do i fix these wrong URL's in my broken magento deployment? This is my first attempt at using Magento to develop a site. I have to admit the learning curve has been steep, but i have been able to navigate most of the challenges thus far. Here at the final hurdle, however, i have stumbled.
Specs:

*

*Magento 1.7.0.2

*Apache version 2.2.22

*PHP version 5.3.10

*MySQL version 5.1.65-cll

Magento is located in a folder on the server named magento one directory down, as in http://www.mydomain.co.za/magento
Problem:

No images are displayed in the front end or backend. It is as if it cannot access the stylesheets. When viewing the source, i can see that the paths are wrong. It searches for the stylesheets in http://www.mydomain.co.za/ and not in the magento folder. I can access the backend by typing in http://www.mydomain.co.za/magento/index.php/admin and that brings up the backend without any styling. After that however, every request results in 404. The URL looks like http://www.mydomain.co.za/magento/adminindex.php without a slash between admin and index. Introducing that slash manually after every 404 results in correct page being displayed (still without styling). So clearly the problem is here, but i can't seem to fix it. And YES, i do have the slash after the path in the database for both secure and unsecure.
Attempts to solve:

*

*Changed the url's in database link

*Changed app/etc/local.xml to use correct database

*Changed .htaccess to include this line: RewriteBase /magento/ (but i
removed it again)

*Deleted the appropriate cache and sessions folders

*Tried some of the suggestion given here link
Now, i am stuck. I have worked my way through error upon error (no fault of Magento, just the learning curve) and i am tired… :-( If someone can please give me some advice as to what to try next, it would be greatly appreciated.
I found these links of the (seemingly) similar problem. Clearly there is something happening here. The other thread never solved the issued, just found a work around. Is it possible that we have run into a bug? Something is stripping that slash out and it isn't any of the usual suspects… dum dum dum
link
link


text:
Q: Mock lazy interface with Moq I want mock lazy interface but I got object reference not set to an instance of an object exception.
Here is class under test:
public class ProductServiceService : IProductServiceService
{
    private readonly Lazy<IProductServiceRepository> _repository;
    private readonly Lazy<IProductPackageRepository> _productPackageRepository;

    public ProductServiceService(
        Lazy<IProductServiceRepository> repository,
        Lazy<IProductPackageRepository> productPackageRepository)
    {
        _repository = repository;
        _productPackageRepository = productPackageRepository;
    }

    public async Task<OperationResult> ValidateServiceAsync(ProductServiceEntity service)
    {
        var errors = new List<ValidationResult>();

        if (!await _productPackageRepository.Value.AnyAsync(p => p.Id == service.PackageId))
            errors.Add(new ValidationResult(string.Format(NameMessageResource.NotFoundError, NameMessageResource.ProductPackage)));

       .
       .
       .

        return errors.Any()
            ? OperationResult.Failed(errors.ToArray())
            : OperationResult.Success();
    }
}

and here is test class
[Fact, Trait("Category", "Product")]
public async Task Create_Service_With_Null_Financial_ContactPerson_Should_Fail()
{
    // Arrange
    var entity = ObjectFactory.Service.CreateService(packageId: 1);

    var fakeProductServiceRepository = new Mock<Lazy<IProductServiceRepository>>();

    var repo= new Mock<IProductPackageRepository>();
    repo.Setup(repository => repository.AnyAsync(It.IsAny<Expression<Func<ProductPackageEntity, bool>>>()));
    var fakeProductPackageRepository  = new Lazy<IProductPackageRepository>(() => repo.Object);

    var sut = new ProductServiceService(fakeProductServiceRepository.Object, fakeProductPackageRepository);

    // Act
    var result = await sut.AddServiceAsync(service);

    // Assert
    Assert.False(result.Succeeded);
    Assert.Contains(result.ErrorMessages, error => error.Contains(string.Format(NameMessageResource.NotFoundError, NameMessageResource.ProductPackage)));
}

fakeProductPackageRepository always is null. I followed this blog post but still I'm getting null reference exception.
How to mock lazy initialization of objects in C# unit tests using Moq
Update:
here is a screen that indicates fakeProductPackageRepository is null.

A: Here is a refactored version of your example:
[Fact, Trait("Category", "Product")]
public async Task Create_Service_With_Null_Financial_ContactPerson_Should_Fail() {
    // Arrange
    var entity = ObjectFactory.Service.CreateService(packageId = 1);

    var productServiceRepositoryMock = new Mock<IProductServiceRepository>();

    var productPackageRepositoryMock = new Mock<IProductPackageRepository>();
    productPackageRepositoryMock
        .Setup(repository => repository.AnyAsync(It.IsAny<Expression<Func<ProductPackageEntity, bool>>>()))
        .ReturnsAsync(false);

    //Make use of the Lazy<T>(Func<T>()) constructor to return the mock instances
    var lazyProductPackageRepository = new Lazy<IProductPackageRepository>(() => productPackageRepositoryMock.Object);
    var lazyProductServiceRepository = new Lazy<IProductServiceRepository>(() => productServiceRepositoryMock.Object);

    var sut = new ProductServiceService(lazyProductServiceRepository, lazyProductPackageRepository);

    // Act
    var result = await sut.AddServiceAsync(service);

    // Assert
    Assert.False(result.Succeeded);
    Assert.Contains(result.ErrorMessages, error => error.Contains(string.Format(NameMessageResource.NotFoundError, NameMessageResource.ProductPackage)));
}

UPDATE
The following Minimal, Complete, and Verifiable example  of your stated issue passes when tested.
[TestClass]
public class MockLazyOfTWithMoqTest {
    [TestMethod]
    public async Task Method_Under_Test_Should_Return_True() {
        // Arrange
        var productServiceRepositoryMock = new Mock<IProductServiceRepository>();

        var productPackageRepositoryMock = new Mock<IProductPackageRepository>();
        productPackageRepositoryMock
            .Setup(repository => repository.AnyAsync())
            .ReturnsAsync(false);

        //Make use of the Lazy<T>(Func<T>()) constructor to return the mock instances
        var lazyProductPackageRepository = new Lazy<IProductPackageRepository>(() => productPackageRepositoryMock.Object);
        var lazyProductServiceRepository = new Lazy<IProductServiceRepository>(() => productServiceRepositoryMock.Object);

        var sut = new ProductServiceService(lazyProductServiceRepository, lazyProductPackageRepository);

        // Act
        var result = await sut.MethodUnderTest();

        // Assert
        Assert.IsTrue(result);
    }

    public interface IProductServiceService { }
    public interface IProductServiceRepository { }
    public interface IProductPackageRepository { Task<bool> AnyAsync();}

    public class ProductServiceService : IProductServiceService {
        private readonly Lazy<IProductServiceRepository> _repository;
        private readonly Lazy<IProductPackageRepository> _productPackageRepository;

        public ProductServiceService(
            Lazy<IProductServiceRepository> repository,
            Lazy<IProductPackageRepository> productPackageRepository) {
            _repository = repository;
            _productPackageRepository = productPackageRepository;
        }

        public async Task<bool> MethodUnderTest() {
            var errors = new List<ValidationResult>();

            if (!await _productPackageRepository.Value.AnyAsync())
                errors.Add(new ValidationResult("error"));

            return errors.Any();
        }
    }
}

A: A Lazy<> as a parameter is somewhat unexpected, though not illegal (obviously). Remember that a Lazy<> wrapped around a service is really just deferred execution of a Factory method. Why not just pass the factories to the constructor? You could still wrap the call to the factory in a Lazy<> inside your implementation class, but then you can just fake / mock your factory in your tests and pass that to your sut.
Or, perhaps the reason that you're passing around a Lazy<> is because you're really dealing with a singleton. In that case, I'd still create a factory and take dependencies on the IFactory<>. Then, the factory implementation can include the Lazy<> inside of it.
Often, I solve the singleton requirement (without the lazy loading) via setting a custom object scope for the dependency in my IoC container. For instance, StructureMap makes it easy to set certain dependencies as singleton or per-request-scope in a web application.
I rarely need to assert that I've done a lazy initialization on some service inside of a system-under-test. I might need to verify that I've only initialized a service once per some scope, but that's still easily tested by faking the factory interface.

A: The thing is that you are creating a Mock of Lazy as fakeProductServiceRepository and later on are returning that instance where just a Mock is needed.
You should change
var fakeProductServiceRepository = new Mock<Lazy<IProductServiceRepository>>();
to
var fakeProductServiceRepository = new Mock<IProductServiceRepository>();

A: I have class where I have used mapper with Lazy keyword below is the example where I have added code example.
public class EntityBusinessComponent : BusinessComponent, IEntityBusinessComponent
{
    private readonly ITableBusinessComponent tableComponent;
    private readonly IEntityDefRepository entityDefRepository;
    private readonly Lazy<EntityCustomMapper> entityCustomMapper;
    private EntityCustomMapper EntityCustomMapper
    {
        get { return entityCustomMapper.Value; }
    }

    public EntityBusinessComponent(ITableBusinessComponent tableComponent,
        IEntityDefRepository entityDefRepository,
        Lazy<EntityCustomMapper> entityCustomMapper)
    {
        this.tableComponent = tableComponent;
        this.entityDefRepository = entityDefRepository;
        this.entityCustomMapper = entityCustomMapper;
    }
}

Mapper Used in below method code
private async Task<string> GenerateEntityTypeDefinition(Guid entityId)
{
    string entityTypeDefinition = string.Empty;
   EntityBase entity = EntityCustomMapper.ToEntityBase(entityDefinitionEo, assemblyName, AssemblyBuilderAccess.RunAndCollect);
   if (entity == null)
     return entityTypeDefinition;

   List<EntityBase> entityList = EntityCustomMapper.ToEntityRelations(entityDefinitionEo, entity);
   if (entityList.IsNotNullOrEmpty())
   {
      //Your Code
   }
   return entityTypeDefinition;

}

Below is XUnit test case created for Lazy Mapper
Step:1 I'm passing object mapper in constructor of EntityCustomMapper class if you dont have same scenario keep it blank.
var objectMapperMock = new Mock<IObjectMapper>();

var entityMapper = new Mock<EntityCustomMapper>(objectMapperMock.Object);

Step:2 Setup mock which value you want to return
entityMapper.Setup(r => r.ToEntityBase(It.IsAny<EntityDefinitionEO>(), assemblyName, AssemblyBuilderAccess.RunAndCollect)).Returns(entityBase);

Setp:3 Create mock of Lazy class
var entityMapperLazy = new Lazy<EntityCustomMapper>(() => entityMapper.Object);

Step:4 Pass mock object to component
public async Task UpdateTest()
{
    EntityThinEO entThin = new();
    Guid EntityId = new Guid("xxxxx-xxxx-xxxxx-xxxxxx");
    var entityRepository = new Mock<IEntityDefRepository>();
    var tableRepository = new Mock<ITableBusinessComponent>();
    var objectMapperMock = new Mock<IObjectMapper>();

var entityMapper = new Mock<EntityCustomMapper>(objectMapperMock.Object);

entityRepository.Setup(r => r.FetchThinEO(It.IsAny<Guid>())).ReturnsAsync(entThin);
entityRepository.Setup(r => r.SaveAllAsync(It.IsAny<EntityObject>())).ReturnsAsync(true);
EntityDefinitionEO entityDefinitionEO = new EntityDefinitionEO();
entityRepository.Setup(r => r.GetEntity(It.IsAny<Guid>())).ReturnsAsync(entityDefinitionEO);
entityMapper.Setup(r => r.ToEntityRelations(It.IsAny<EntityDefinitionEO>(), It.IsAny<EntityBase>())).Returns(entityList);

var entityMapperLazy = new Lazy<EntityCustomMapper>(() => entityMapper.Object);

objectMapperMock.Setup(x => x.Map(It.IsAny<EntityThinEO>(), It.IsAny<EntityThinEO>())).Returns(entThin);

var entityBusinessComponent = new EntityBusinessComponent(tableRepository.Object, entityRepository.Object, entityMapperLazy);
entityBusinessComponent.ObjectMapper = objectMapperMock.Object;

bool result = await entityBusinessComponent.UpdateTypeDefination(EntityId);
Assert.True(result);

}


text:
Q: Close console application window after key press or automatically after x minutes I have a console application in Visual Studio 2008, C# and .NET Framework 3.5.
When application finishes to do all the stuff I want to close the windows when user press a key or automatically after some minutes have been elapsed.
So at the end of my application I do:
static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();

public static int Main(string[] args)
{
   // Do some stuff
   Console.WriteLine("Press any key to close this window.");

   myTimer.Tick += new EventHandler(TimerEventProcessor);
   myTimer.Interval = 5000;
   myTimer.Start();

   Console.ReadKey();

   return 0;
}

private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
    myTimer.Stop();
    Environment.Exit(0);
}

The problem here is that window is not close after x minutes has been elapsed and even timer event is never raised since program is blocked waiting for a key (ReadKey).
So how to do it?

A: Try to move the work to be done into a separate thread:
public static int Main(...)
{
    new System.Threading.Thread(Work).Start();
}
private void Work()
{
    // work to be done here
}

This way the GUI thread will have time for raising the timer's tick event.

A: The problem you have is that you are using a Form timer, which is hung up on a UI thread -- for a console app. You are exiting an environment not of the Console.
We need to use the threading timer instead. But, this should be not too much different.
    static Timer myTimer;

    public static int Main(string[] args)
    {
        // Do some stuff
        Console.WriteLine("Press any key to close this window.");

        //Hey, I just met you and this is crazy
        myTimer = new Timer(CallMeMaybe, null, 5000, 0);

        //so call me maybe
        Console.ReadKey();

        return 0;
    }

    //Instead of a tick, we have this
    private static void CallMeMaybe(object state)
    {
        //But here's my number
        Environment.Exit(0);
    }

A: I have found a possible solution, but not sure if the best:
static System.Windows.Forms.Timer myTimer = new System.Windows.Forms.Timer();

public static int Main(string[] args)
{
   // Do some stuff
   Console.WriteLine("Press any key to close this window.");

   myTimer.Tick += new EventHandler(TimerEventProcessor);
   myTimer.Interval = 5000;
   myTimer.Start();

   // while (!Console.KeyAvailable)
   //{
   //     Application.DoEvents();
   //     Thread.Sleep(250);
   //}

   // Above code replaced with:
   Console.ReadKey(true);

   DisposeTmr();

   return 0;
}

private static void DisposeTmr()
{
    myTimer.Stop();
    myTimer.Dispose();
}

private static void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
    DisposeTmr();
    Environment.Exit(0);
}

Problem with that solution is that this type of timer is synchronous and it is needed to use Application.DoEvents as explained here. Also the timer remains in a suspended state while the UI thread is sleeping so this can cause timer event handler not continue capturing timer events while the main UI thread is sleeping.
To avoid this, there are two options, System.Timers.Timer and System.Threading.Timer. I have implemented System.Threading.Timer solution as below and it works perfectly:
static System.Threading.Timer myTimer;

public static int Main(string[] args)
{
   // Do some stuff
   Console.WriteLine("Press any key to close this window.");

   myTimer = new System.Threading.Timer(TimerCallback, null, 5000, Timeout.Infinite);

   while (!Console.KeyAvailable)
   {
        Thread.Sleep(250);
   }

   DisposeTmr();

   return 0;
}

private static void DisposeTmr()
{
    if (myTimer != null)
    {
        myTimer.Dispose();
    }
}

private static void TimerCallback(Object myObject)
{
    DisposeTmr();
    Environment.Exit(0);
}

A: This can be implemented pretty easily with async/await.
internal class Program
{
    private static async Task Main(string[] args)
    {
        await DoStuff();
        await Task.WhenAny
        (
            Task.Delay(3000),
            ExitOnKeypress()
        );
    }

    private static async Task ExitOnKeypress()
    {
        while (!Console.KeyAvailable)
        {
            await Task.Delay(1);
        }
    }
}


text:
Q: how to call an activity which extends the baseactivity i am writing one activity class like below
public class HeaderFooter extends Activity {
        public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.headerfooter);
        }
 }

and i am extending one more class from HeaderFooter class
public class Home extends HeaderFooter
{
        @Override
        public void onCreate(Bundle savedInstanceState)
        {
            super.onCreate(savedInstanceState);
            ViewGroup vg = (ViewGroup) findViewById(R.id.lldata);
            ViewGroup.inflate(Home.this, R.layout.home, vg);
        }
}

how to call the extended class from base class on listitemclick event
if i try with the following code
  Intent i=new Intent(HeaderFooter .this, Home .class);
                    startActivity(i);

i am getting the exception tell me how to call extended class from my main class.
Exception details:
03-21 07:17:44.173: E/AndroidRuntime(1522): FATAL EXCEPTION: main
03-21 07:17:44.173: E/AndroidRuntime(1522): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.pcmac.parentconnect/com.pcmac.parentconnect.Grades}: java.lang.NullPointerException
03-21 07:17:44.173: E/AndroidRuntime(1522):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at android.os.Looper.loop(Looper.java:137)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at android.app.ActivityThread.main(ActivityThread.java:5039)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at java.lang.reflect.Method.invokeNative(Native Method)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at java.lang.reflect.Method.invoke(Method.java:511)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at dalvik.system.NativeStart.main(Native Method)
03-21 07:17:44.173: E/AndroidRuntime(1522): Caused by: java.lang.NullPointerException
03-21 07:17:44.173: E/AndroidRuntime(1522):     at com.pcmac.parentconnect.LayerStack.onCreate(LayerStack.java:174)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at com.pcmac.parentconnect.Grades.onCreate(Grades.java:15)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at android.app.Activity.performCreate(Activity.java:5104)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-21 07:17:44.173: E/AndroidRuntime(1522):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-21 07:17:44.173: E/AndroidRuntime(1522):     ... 11 more

A: In this case, you want to use the other constructor of Intent:
 Intent i = new Intent();
 i.setClassName(context, getTargetActivityClassName() /* child class override this method and return a string */);