text:
Q: how to display data using isingleresult means LINQ to SQL in ASP.net with MVC architechure? i create a one dbml file under model folder.in that one table is there called CorporateAdmin.
and one sp is there called usp_CorporateAdmins_ActiveUsersList i.e used to display data from corporateadmin table.
I create one controller in that index action i wrote following code.
//code
public ActionResult Index()
    {

        ToystoreLINQDBDataContext dc = new ToystoreLINQDBDataContext();

        ISingleResult<usp_CorporateAdmins_ActiveUsersListResult> isr = dc.usp_CorporateAdmins_ActiveUsersList(1, 1);
        List<usp_CorporateAdmins_ActiveUsersListResult> myList = new List<usp_CorporateAdmins_ActiveUsersListResult>(isr);
        IEnumerable<usp_CorporateAdmins_ActiveUsersListResult> myenumrable = myList;

        return View(myList);
    }

and i create list view of index action.and in that code is as under.
//code
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<IEnumerable<ToystoreLINQ.Models.CorporateAdmin>>" %>

<% foreach (var item in Model)
   { %>

            <%= Html.ActionLink("Edit", "Edit", new { id=item.CorporateAdminID }) %> |
            <%= Html.ActionLink("Details", "Details", new { id=item.CorporateAdminID })%> |
            <%= Html.ActionLink("Delete", "Delete", new { id=item.CorporateAdminID })%>

            <%= Html.Encode(item.CorporateAdminID) %>

            <%= Html.Encode(item.CorporateID) %>

            <%= Html.Encode(item.UserName) %>

            <%= Html.Encode(item.FirstName) %>

            <%= Html.Encode(item.LastName) %>

            <%= Html.Encode(item.Email) %>

            <%= Html.Encode(item.IsSuperUser) %>

<% } %>

now,when i run this error is occured i.e
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[ToystoreLINQ.Models.usp_CorporateAdmins_ActiveUsersListResult]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[ToystoreLINQ.Models.CorporateAdmin]'.
Can somebody help me?

thanks for your quick response.
i wrote like your code but still no luck.
it gave me this error.
The model item passed into the dictionary is of type 'System.Collections.Generic.List1[ToystoreLINQ.Models.usp_CorporateAdmins_ActiveUsersListResult]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[ToystoreLINQ.Models.CorporateAdmin]'.
Is there any other option?

A: In your view you declare
Inherits="System.Web.Mvc.ViewPage<IEnumerable<ToystoreLINQ.Models.CorporateAdmin>>"`

meaning that your view will be handling an object of type IEnumerable<ToystoreLINQ.Models.CorporateAdmin>, but in your controller action you return an IEnumerable<usp_CorporateAdmins_ActiveUsersListResult>. So you probably should change what your view inherits to what your action is returning.
Have to say though that I don't have used stored procedure before in LINQtoSQL, but I think you can't cast your usp_CorporateAdmins_ActiveUsersListResult object to a Model.CorporateAdmin object straight away, that's why you are getting the error.
But if the above is the case, you have rewritten your view and it worked you could rewrite you Index() method to
ToystoreLINQDBDataContext dc = new ToystoreLINQDBDataContext();

ISingleResult<usp_CorporateAdmins_ActiveUsersListResult> isr = dc.usp_CorporateAdmins_ActiveUsersList(1, 1);
return View(isr.ToList());


text:
Q: Breakpoints not being hit in remote linux kernel debugging using gdb I am trying to remotely debug a linux kernel running on an arm cortex-a9 target using jtag probe and gdb.
I can connect to the kernel and halt it with gdb. I am able to set breakpoints in the kernel code and gdb confirms there placement as well but the problem is that once I start the execution and issue a continue command, the breakpoints are never hit and the kernel continues to run....
Please help me out in this regard.
Thanks.

A: As pointed in this thread, you should set the breakpoints as hardware breakpoints, namely - using the hbreak command. Only then the breakpoints will be hit.

A: For anyone reading this,  the debugger will not break with software breakpoints by default, see the relevant doc:
"If the architecture that you are using supports the kernel option CONFIG_STRICT_KERNEL_RWX, you should consider turning it off. This option will prevent the use of software breakpoints because it marks certain regions of the kernel's memory space as read-only. If kgdb supports it for the architecture you are using, you can use hardware breakpoints if you desire to run with the CONFIG_STRICT_KERNEL_RWX option turned on, else you need to turn off this option."
at https://www.kernel.org/doc/html/v4.14/dev-tools/kgdb.html
Disable RWX and recompile, then software breakpoints should work (they started working normally here after this)

A: Is some cases, KASLR (Kernel Address Space Layout Randomization) can be the culprit.
Even though you setup hbreak, the actual code location can be different from the address seen from the .elf file when using KASLR, so either pass --append "nokaslr" to the kernel boot argument, or configure the kernel with RANDOMIZE_BASE=n. This applies for arm64 and x86_64. (maybe other architectures too).

redpajama_set_name: RedPajamaStackExchange


text:
Q: git push fails: RPC failed; result=22, HTTP code = 411 I have only one branch. For a few months I have been using
git push origin master

to commit to my local repository. Last night after I made some minor changes to my local repository and tried to push using the same command, I got this error:
error: RPC failed; result=22, HTTP code = 411
fatal: The remote end hung up unexpectedly
fatal: The remote end hung up unexpectedly
Everything up-to-date

I googled and found questions such as this one and this one, but none of the answers to these questions solves my problem.
Most of the answers suggest the problem of detached head. Yet I don't think my head is detached. Nor do I think I am on the wrong branch (as I only have one branch...)
I did a few experiments to figure out what's wrong, and here are the results I got:
(1) First comes my git status output

# On branch master
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
# egal.aux
# egal.blg
# egal.out
# egal.pdf
# egalcar.aux
# egalcar.blg
# egalcar.pdf
nothing added to commit but untracked files present (use "git add" to track)

(2) When I type git reflog, I can see all my local commits, but the remote repository just won't get updated.
(3) When I type git branch -a, I get

* master
  remotes/origin/master

(4) When I type git remote show origin, I get

* remote origin
  Fetch URL: http://github.com/CherryQu921/egaldoc_en
  Push  URL: http://github.com/CherryQu921/egaldoc_en
  HEAD branch: master
  Remote branch:
    master tracked
  Local ref configured for 'git push':
    master pushes to master (fast-forwardable)

I think the last line of output (the "fast-forwardable") is weird, but I am not sure what is wrong...

A: None of the solutions provided worked for us.  We had to switch to ssh to make this work instead of the HTTPS solution.

A: If you attempt to push a large set of changes to a Git repository with HTTP or HTTPS, you may get an error message such as error: RPC failed; result=22, HTTP code = 411. This is caused by a Git configuration default which limits certain HTTP operations to 1 megabyte.
To change this limit run within your local repository
git config http.postBuffer *bytes*

where bytes is the maximum number of bytes permitted. For example:
git config http.postBuffer 524288000

For 500MB (thanks @Hengjie)

A: You can also do this globally -
git config --global http.postBuffer 524288000

That will allow all local repos to push up to 500MB of data.

A: If you are using TortoiseGit for Windows, the easiest way is using the integrated configuration.
In a file explorer press left mouse button, select TortoiseGit -> Settings. Accept the info message. Now, you can choose if you want to configure the property only for the current project or system whide. For systemwide configuration press "edit systemwide gitconfig" and add the next line to the section [http]:
postBuffer = 524288000

(it the section [http] doesn't exist, create it)

A: I solved the 22 error as follows:
In the "git clone" command I did NOT supply the user:password.
The clone worked, but not the push.
Solution for the 22 error:
Modify .git/config the url like this:
url=http://user:pwd@host/...
Then, the push worked.

A: use git lfs and track files greater than 1 mb and then again try to push


text:
Q: how do i force a tempdata to show up after the action returns from a jquery call I call this action using jquery
public ActionResult Delete(int Id){
   Schedule schedule = context.Schedules.FirstOrDefault(s => s.Id == Id);
   try{
       context.Schedules.Remove(schedule);
       context.SaveChanges();
       TempData["Message"] = "Succesfully removed schedule.";
       return Content(Boolean.TrueString);
   }catch(Exception ex){
       TempData["Message"] = "Something went wrong";
       return Content(Boolean.FalseString);
   }

}

On my view I have a div that handles the TempData["Message"] from the master

 <% if(ViewContext.TempData["Message"] != null { %>

        <%: ViewContext.TempData["Message"] %>

  <% } %>

this is exactly how my jquery looks like. using the Boolean.TrueString / FalseString return. I'm not really sure if that's the right way, as I'm still starting to learn jquery with actions.
http://ricardocovo.com/2010/09/02/asp-mvc-delete-confirmation-with-ajax-jquery-ui-dialog/
Basically my goal is to be able to show any errors, or notify the users of anything that is wrong or any instructions that needs to be done to finish the steps. Was thinking of maybe just using JSON as the return type? I'm not really sure how to handle it.
any recommendations is very much appreciated.

A: you are using an ajax call; the View won't get fully rendered again; to be able to show a message you'll have to return it as json for example and handle it in the jquery callback.

A: You should use ViewData instead of TempData in this scenario.
TempData is used to temporary store something between requests. And it uses Session object behind the scene. Like in Post->Redirect->Get .
In your case you use data in the same request. So TempData is not needed.

A: When you calling this function with jQuery, you are calling it async. This is done by AJAX and it's much easier to return the message in JSON:
Response.Write('{"message":"foo"}');

in jQuery you just have to call the dialog when the ajax-request is finished:
$.ajax({
  url: "test.aspx"
}).done(function(data) {
  $(".alert").text(data.message);
  $("#messages").dialog();
});


text:
Q: How to union same table in MySQL? Now I have the following sql:
SELECT MAX(a), MIN(a)
FROM t1 join t2 join t3
UNION ALL
SELECT MAX(b), MIN(b)
FROM t1 join t2 join t3
UNION ALL
SELECT MAX(c), MIN(c)
FROM t1 join t2 join t3
UNION ALL
SELECT MAX(d), MIN(d)
FROM t1 join t2 join t3

While table t1, t2, t3 are all huge, join them is very slow.
How can I join them just once in this query? Alias the table or create a temp table(query scope)?
And

*

*I don't want to transform them into 1 row 4 column.

*I tried to create view. It doesn't work.

Thanks in advance!

A: In SQL Server, you can use a lateral join:
SELECT v.x
FROM t1 join
     t2
     on . . . join
     t3
     on . . . cross apply
     (values (a), (b), (c), (d)) v(x);


text:
Q: Which branch of mathematics rigorously defines infinitesimals? I have some trouble doing standard computations in calculus because of the notion of a differential, otherwise known as an infinitesimal, being rather ill defined, in my experience.
Are there any fields of mathematics that someone can recommend for trying to come to a more rigorous grip on the notion of infinitesimals? I've heard and read up about non-standard analysis, but from what I can tell, even the rigour of non-standard analysis isn't as firm as that of more established branches of mathematics. How accurate is this perception?
Any help is appreciated, thank you.

A: Amusingly, one of the answers to the question you ask is that elementary calculus rigorously defines infinitesimals.
How does it do so? Via the notion of differential. The problem you're struggling with is almost backwards; the standard, traditional track is:

*

*Define the notion of derivative

*Use multivariable derivatives to define the notions of (tangent) vector and differential

*Conceptualize a notion of an "infinitesimal" neighborhood of a point

To elaborate on that last point, you're supposed to envision the points of the infinitesimal neighborhood to be enumerated by tangent vectors — the intuitive idea is that you take an "infinitesimal" step proportional to the tangent vector. Differentials are the functions on the infinitesimal neighborhood.
But this conceptualization is not trying to define anything new — it is merely a way of thinking about calculus. (albeit a very useful one!)
But the second point is bog standard. For example, in multivariable calculus, one incarnation of these notions is

*

*Tangent vectors to points in $\mathbb{R}^n$ are $n \times 1$ column vectors — the sort of thing you get when differentiating a vector function of one variable

*Differentials at points in $\mathbb{R}^n$ are $1 \times n$ row vectors — the sort of thing you get when differentiating a scalar function of $n$ variables

Both the subjects of differential geometry and algebraic geometry treat this sort of thing much more explicitly and more in-depth.

A: Your perception is wrong. Non-standard analysis is grounded on Logic and it's as solid as any other field of Mathematics. I suggest that you read Abraham Robinson's Non-standard Analysis.

A: Most objections to non-standard analysis seem to be about the use of the axiom of choice in the construction of the field of hyperreals. Non-standard analysis is completely rigorous, but if you're a hardcore constructivist then you may be a bit squeamish about it. Then again, there's always some things you need to take on faith in any branch of maths:

*

*If you're a hardcore finitist then you have to be really careful about analysis in general, since the conventional $\mathbb{R}$ as an object doesn't exist at all.

*If you don't accept the axiom of dependent choices then you're pretty limited in what you can do in real analysis, because many arguments rely on taking a sequence chosen arbitrarily.

*If you don't believe there is a nonprincipal ultrafilter on $\mathbb{N}$ then you can't construct the ultrapower required to create the hyperreals.

If you choose to allow more axioms ("there is an infinite set", "dependent choices", "there is a nonprincipal ultrafilter on $\mathbb{N}$") then you get access to correspondingly more interesting things you can do, but it's all still rigorous.
Note, however, that if you accept Choice then in a certain sense "anything you can do in non-standard analysis, you can also do without the hyperreals" (see https://math.stackexchange.com/a/51480/259262). It's an extra proof technique to make things easier by hiding many of the $\forall \exists$ quantifiers, rather than allowing you to prove genuinely new things that you couldn't prove before.

A: To answer the title question: "Which branch of mathematics rigorously defines infinitesimals?": the answer is "a serious undergraduate course in algebra, including the existence of a maximal ideal".  Indeed, that is all that's required to construct a hyperreal extension of the real field satisfying the requisite properties, such as existence of infinitesimals, etc.

A: Like others have pointed out, nonstandard analysis is perfectly rigorous, just a limited more complicated to set up. However, I will list some other, equally rigorous approaches to infinitesimals.

*

*Dual numbers: These are very simple to set up. A dual number is basically just a ordered pair of numbers. It is based on an infinitesimal called $\epsilon$, which is a number such that $\epsilon^2 = 0$. Their relation to differentiation is $f(a + b\epsilon) = f(a) + bf'(a)\epsilon$. In fact, if you use a programming language that implements dual numbers (like Haskell), you can find the derivative of any function by solving that instead of approximating the derivative with a secant line. However, do not expect to get very far in Calculus with them: they only help you define derivatives, they have no transfer principle, and they are not even a field.

*Surreal numbers: This fun little number system includes real numbers, infinitesimals, cardinal number, ordinal numbers, and every ordered field. It is also satisfies the field axioms itself. However, they have nearly no applications in Calculus, because they are too different from real numbers. They were actually invented for use in game theory, their seminal text being On Numbers and Games (which is a great book, by the way). They also have an extremely simple definition given their complexity, even simpler than the real numbers. Conway actually proposes that it would be simpler to construct the real numbers by first constructing the surreal numbers, and then getting rid of all the non-real surreal numbers.

A: There's an approach, by the names of synthetic differential geometry or smooth infinitesimal analysis, which considers a kind of 'real line extended with' nilpotent elements, in this case, objects $ d $ not necessarily equal to $ 0 $ satisfying
$ d^2 = 0 $
Note this implies one's no longer working with/inside a conventional algebraic field, and indeed the axiomatic development of this theory, though in some sense simpler than the more usual forms of Analysis, demands some specially careful attention


text:
Q: Convert Word file to PDF using Javascript/Jquery My requirement is to convert a word file(docx) to a pdf file in the client side before sending the file to the server.
I have already found solutions to implement this using c# and nodejs, but it doesn't meet my requirement since I'm not using nodejs in my project and to convert using c# I need to send the files to the server.

Any alternate methods such as converting the word file to html or a canvas before exporting as a pdf is fine.

A: gamage,
I am not sure if you are still looking for answer to this question but let me try to provide solution anyway for anyone in same scenario.
As you are not looking for nodejs solution, We can solve this by calling external api endpoint which does this work for us.
In one of my previous project I have used PDF.co library to extract data from PDF. PDF.co also has endpoint to convert Documents such as doc, docx to PDF.
Following is the pdf.co api endpoint and code snippets for converting doc to pdf.
API Endpoint:
https://api.pdf.co/v1/pdf/convert/from/doc
Sample Request:
{
    "url": "https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/doc-to-pdf/sample.docx",
    "pages": "0-",
    "name": "result.pdf"
}

Sample Output
{
    "url": "https://pdf-temp-files.s3.amazonaws.com/ce9c93849b604956bc9abadb0ce4b0b3/result.pdf",
    "pageCount": 1,
    "error": false,
    "status": 200,
    "name": "result.pdf",
    "remainingCredits": 930668,
    "credits": 21
}

Following is postman generated code snippet in case you want to consume this using jQuery.
var settings = {
        "url": "https://api.pdf.co/v1/pdf/convert/from/doc",
        "method": "POST",
        "timeout": 0,
        "headers": {
                "x-api-key": "--your-pdf-co-api-key--",
                "Content-Type": "application/json"
        },
        "data": JSON.stringify({"url":"https://bytescout-com.s3-us-west-2.amazonaws.com/files/demo-files/cloud-api/doc-to-pdf/sample.docx","pages":"0-","name":"result.pdf"}),
};

$.ajax(settings).done(function (response) {
        console.log(response);
});

Explore more about this API endpoint with documentation at here.
https://apidocs.pdf.co/23-pdf-from-doc-docx-rtf-txt-xps-document-to-pdf
Thank you!


text:
Q: Can I trade a Steam game that I don't want? The title pretty much says it all. If someone gave me a game, and I opened it for a few minutes to take a gander, can I still trade it to someone else? Or is it forever mine? For example, if someone were to gift me a copy of DotA 2 (not that I don't like DotA, it's just an example), and I opened it to see what was in it, can I still gift it to someone else?
Edit: Follow-up question: Can I have an opened copy of game X, but still receive additional copies of game X if I am, say, the middle-man for a Secret Santa or something of the like?

A: On Steam, you have a Library and an Inventory.  Your Library is the list of games you own and can play, but can't trade; your Inventory is the list of games you can trade but can't play.
If you want to play a game in your Inventory, you can add it to your Library, but games can't move in the other direction - once a game is in your Library, it's there forever and can never be traded.
You can view your inventory by going to Steam --> (Your Name) --> Inventory.
To add a game from your inventory to your library, click on it, then choose "Add to my Game Library" on the right.

..and I opened [the gift] it to see what was in it.

There is no such concept as "opening" a Steam gift.  When you receive a gift, Steam tells you immediately what game you were sent, then gives you three options:

*

*Add game to my Library. (This lets you play the game, but not trade it)

*Add game to my Inventory. Steam removed this option in 2019

*Decline (Returns the game to the gifter)

Can I have an opened copy of game X, but still receive additional copies of game X

Assuming you mean "If I have a game in my Library, can I also purchase/receive a second copy and put it in my Inventory?" the answer is yes, there are no restrictions on the games you can have in your Inventory.

A: It's forever yours. Only gifts that have not been added to your Steam library can be traded.
Source: Steam Support – Steam Trading

A: If someone gifted you it and you've played is less than 2 hours and you've had it for less then 14 days it can be refunded but only under those circumstances. I got his of the steam help page


text:
Q: Resize dat.gui in three.js I'm using a dat gui in three.js.
Unfortunately my gui is very very big, and I cant't resize it. I tried with autoplace=false.
How can I resolve this problem?

A: Try setting a width in the constructor parameters along with autoPlace: false
var gui = new dat.GUI( { autoPlace: false, width: 300 } );

A: I would use the following code to shrink your panel:
    function datgui(){
    let gui = new dat.GUI({
        width : 300
    });


text:
Q: Returning meaningful HTTP responses in ASP.NET Core 2.0 Web API I feel it's a good idea to return meaningful HTTP responses but I'm trying to come up with the right approach to handle that.
In my ASP.NET Core Web API app, the endpoints i.e. API action methods, simply receive a request, call my business layer for a response and return the response.
At the business layer, I check to see if the request is authorized or not. If it's not authorized, I throw an exception that incdicates the type of exception i.e. unauthorized request but in those cases, my API endpoint simply returns an HTTP 500. I'd rather return an HTTP 401.
Question is how to transfer my lower level exceptions to HTTP status codes.
Two questions:

*

*Is it worth trying to capture the type of exception that occurred at a lower level in the app and try to translate it to HTTP responses or should I simply let my API return an HTTP 500?

*If it's worth it, how do I handle it?

A: A Web API should strive to never return a 500 status code (Internal Server Error). If it does, then there is something wrong with the code you have written.
Having said that, you shouldn't be throwing an exception with the intent to send back a status code is a rather poor way to handle requests -- i.e. by doing a blanket catch all and masking it with some nice status code to the client.

You should run all your validation and logic on the request and send back your choice of any of the 4xx status codes.

Essentially, for a Web API the status codes should be
2XX -- Success //(ex: OK, created, no content, etc)
3XX -- Redirection //(ex: renamed an API's path/url to a new one)
4XX -- Client Error
       ex:
           405 //Method Not Allowed (ex: client sent a DELETE request to your API)
           409 //Conflict
           415 //Unsupported Media Type (ex: client requests for XML -- yuck! no!)
           416 //Range Not Suitable (ex: client asked for a million records)
           422 //Unpronounceable Entity (ex: client sent something invalid in the body)
5XX -- Server Error //(ex: a well written Web API will NEVER error! )

However, if you really do have an exception, then a 500 error code is correct -- that means you wrote bad code (refer back to my first point).

A: Assuming that your controller extends Microsoft.AspNet.MVC.Controller you'll have inherited some methods that do what you need like OK, Forbidden, BadRequest, ObjectResult, etc.. So in the case you've described above you could do something like
public async IActionResult DoMyThing()
{
    try
    {
        return ObjectResult(await DoMyInternalCall());
    }
    catch (Exception e)
    {
        //FigureOut the Exception type indications a security violation
        return Forbidden()
    }
    ....

Personally I prefer to build APIs that return a status instead of throwing an exception which makes this all a bit cleaner especially now that we have tuples. So something like
public async IActionResult DoMyThing()
{
        var (Status status, string myThing) = await DoMyInternalCall();
        switch(status)
        {
             case Status.OK: return ObjectResult(myThing);
                             break;

             case Status.AccessDenied: return Forbidden();
                                       break;

             case Status.NotFound: return Notfound();

             ...

That's just a taste thing though - I don't judge. The point is, Microsoft.AspNet.MVC.Controller  has built in methods to let you return valid HTTP status codes along with data.

A: I don't like this idea of throwing exceptions at all. A 500 is a sign that  there is something really wrong with your own code.
So, let's say that your business layer is checking to see if a user is authorised. What I would do is create a method which checks the authorisation, have that method return a simple Boolean response for example. Then your controller checks the flag, if it's false, return 401, job done. This is a much better way of communicating between your business layer and api layer.
Obviously I have no way of knowing how your business layer is built, but keep it simple, keep it clear, don't try to trap any exceptions, deal with everything cleanly and return appropriate HTTP codes.
The business layer should not care at all about the api, should not deal with HTTP codes, basically  this means you are not leaking abstractions everywhere and you keep things in the layer where they belong.

A: There's a whole host of HTTP response codes of course, and just because a request couldn't be properly handled doesn't necessarily mean it's a 500 Internal Server error.  What if someone requests an update to a non-existent object?  That wouldn't fall under the range of a 500 (unsure offhand exactly which would work - 4xx I'd guess, but a handy list of common HTTP responses while you're working on this would be recommended).  I generally feel that 500s are for "uh oh, something happened on our end and we don't know what..." type of thing.  For most other cases there's a more appropriate response.
With that said, I feel that exceptions are best generalized as they move further toward the top layers.  Entity Framework throws some esoteric exception, the data access layer wraps it up in a slightly more generic DataAccessException (with the original as the inner, of course), the repository maybe handles it even more generically, and by the time it gets to your controller for response handling, you should only have a handful of "actual" exceptions that ought to need to be handled.  Return something fairly generic, log the nested exceptions on the server, and go from there?
My 2cents


text:
Q: Difference between Azure price calculator and actual configured price - have I missed something? I am setting up our organisation's first Azure server as a kind of test bed for future projects.  We would like to create a simple FTP/SFTP server as an Azure Windows server.
The Microsoft pricing calculator for a Windows Server - Basic A1: 1-Core 1.75GB RAM 40GB comes in at £0.026/hour or £19.41 per month.
When I create a Windows server in the Azure Portal, the cheapest I can possibly create is £54.90 per month - nearly three times as much.
Is it possible to account for the difference, other than through over-enthusiastic marketing?
I've tried both 2008 R2 and 2016 servers, and I'm not choosing HPC machines or anything high-end at all.
By the way, I realise I can probably get a web-based subscription FTP service much cheaper
Many thanks.

A: By default the VM selector will select SSD for your disk type, this will only show the *S series VMs (DS, ES, FS etc.) which are more expensive. The A series, which is the cheapest option will not be shown.
Change the drop down to HDD and make sure you click the "show all" option on the VM selection window and you should see the A series VMs which are the cheapest.


text:
Q: Calculated Field Formula with IF AND Trying to get this calculated column value to work and having trouble with the syntax:
=IF(AND([Due Date]<=[Today],ISBLANK([Release Date])),"Yes", "No")

Pretty much if "Due Date" is less than or equal today and "Release Date" is blank then show "Yes" otherwise "No".

A: Your Calculated Column syntax is correct.
and could be shortened to:
=AND( [Due Date]<=[Today] , ISBLANK([Release Date]) )

BUT
[Today] does not behave like it does in Excel;
it will always be the date the Item was last touched
How to use Today and Me in Calculated column

A: Try
=AND( [Due Date]<=[Today()] , ISBLANK([Release Date]) )


text:
Q: ul list with only as many li's as filled custom fields I have a slider that contains li's with images. The first 3 images are required, but the user should be able to add as many as 20. I think I have to create a ul with actually 20 li's, the li's after the 3rd are set to display: none, but for some reason it breaks the slider. I have the same slider set with custom post types, with a loop, and it works fine, but it seems that if I  hardcode the li's, even if they are set to display: none, it breaks.
This is my code:
$imagen2            = get_field("imagen2");
$imagen3            = get_field("imagen3");
$imagen4            = get_field("imagen4");
$imagen5            = get_field("imagen5");
$imagen6            = get_field("imagen6");

...

 <img src="<?php echo $imagen1['url'] ?>">

 <img src="<?php echo $imagen2['url'] ?>">

 <img src="<?php echo $imagen3['url'] ?>">

 <img src="<?php echo $imagen4['url'] ?>">

The 4th li is an empty custom field, and so it breaks the slider even though is set to display: none;
How could I create some sort of loop that says, if there is data in the custom field, create the li with the custom field?
Right now I get an empty li with an img inside with scr(unknown).

A: You could add a check to only display the item if it exists:
<?php if ( $imagen4 ) { ?>

 <img src="<?php echo $imagen4['url'] ?>">

<?php } ?>

But it looks like you are using the Advanced Custom Fields plugin.  If this is the case, you would probably be better off using a repeater field, and specifying a minimum number of images.  Then, display it in a loop.
<?php if( have_rows('images') ): ?>

<?php while( have_rows('imagen') ): the_row();
$imagen = get_sub_field('imagen');
?>

 <img src="<?php echo $imagen['url'] ?>">

<?php endwhile; ?>

<?php endif; ?>

(The above code assumes your repeater is named "images")


text:
Q: how to fix "pharentesis in the textfield in flutter" on visual studio code? im not can do launcher this code, i have one error in a pharentesis, not speak much english. Help me.
@override
Widget build(BuildContext context) {
return Row(
  children: <Widget>[
    TextField(    //<=====error en este parentesis no se a que se debe
      decoration: InputDecoration (
        contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0,),
        hintText: inputText,
        border: OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(32.0)),
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(32.0)),
          borderSide: BorderSide(color: Colors.lightBlueAccent, width: 2.0),
        ),
        focusedBorder:  OutlineInputBorder(
          borderRadius: BorderRadius.all(Radius.circular(32.0)),
          borderSide: BorderSide(color: Colors.blueAccent, width: 2.0),
        ),
      ),
    ),
  ],
);

}

A: There may be more elements in one row. you can wrap TextField with Expanded and set flex
code snippet
return Row(
      children: <Widget>[
        Expanded(
          flex: 1,
          child: TextField(    //<=====error en este parentesis no se a que se debe
            decoration: InputDecoration (
              contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0,),
              hintText: inputText,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(32.0)),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(32.0)),
                borderSide: BorderSide(color: Colors.lightBlueAccent, width: 2.0),
              ),
              focusedBorder:  OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(32.0)),
                borderSide: BorderSide(color: Colors.blueAccent, width: 2.0),
              ),
            ),
          ),
        ),
      ],
    );

full code
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Column(
        children: <Widget>[
          txtfield(),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class txtfield extends StatefulWidget {
  @override
  _txtfieldState createState() => _txtfieldState();
}

class _txtfieldState extends State<txtfield> {
  String inputText = 'this is hint';
  @override
  Widget build(BuildContext context) {
    return Row(
      children: <Widget>[
        Expanded(
          flex: 1,
          child: TextField(    //<=====error en este parentesis no se a que se debe
            decoration: InputDecoration (
              contentPadding: EdgeInsets.symmetric(vertical: 10.0, horizontal: 20.0,),
              hintText: inputText,
              border: OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(32.0)),
              ),
              enabledBorder: OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(32.0)),
                borderSide: BorderSide(color: Colors.lightBlueAccent, width: 2.0),
              ),
              focusedBorder:  OutlineInputBorder(
                borderRadius: BorderRadius.all(Radius.circular(32.0)),
                borderSide: BorderSide(color: Colors.blueAccent, width: 2.0),
              ),
            ),
          ),
        ),
      ],
    );
  }
}


text:
Q: Designing a recipe database that needs to include ingredients as well as sub-recipes I am designing a recipe database that needs to be very flexible as it is going to be communicating directly with our back-of-house inventory system.  This is what I have so far in regards to the tables:

*

*Recipe: this table will contain the recipe date: the name, steps needed to cook, etc.

*Ingredients/Inventory: this is our back of house inventory, so this will have the information about each product that will be used in our recipes.

*Recipe Line Item: This is the tricky table, I want to be able link to the ingredients here as well as the quantity needed for the recipe, but I also need to be able to directly include recipes from the recipe table (such as marinara sauce that we make in-house), and that is why I am having trouble figuring out the best way to design this table.

Basically, the recipe line item table needs to be able to link to either the ingredients table or the recipe table depending on which line item is needed and I want to know what would be the most effective way to handle that.
Thank you so much in advance!

A: Looks like you need a database model similar to this:

This model has the following properties:

*

*Essentially, each recipe is a series of steps.

*Each step has its order relative to other steps of the same recipe (STEP_NO), a unit (mass, volume, count...), a quantity in that unit etc.

*A particular step is connected either to an ingredient (when INGREDIENT_ID is non-NULL) or to another recipe (when SUBRECIPE_ID is non-NULL).1

*Other than that, the STEP is a fairly standard junction table implementing many-to-many relationship, which means the same ingredient can be used in multiple recipes (or even multiple steps of the same recipe) and also a recipe can be a "sub-recipe" of multiple other recipes.

*This is essentially a directed graph. The data model itself will not prevent cycles - they should be avoided at the client code level and possibly detected by triggers.

1 If MySQL supported CHECK constraints (which it doesn't), you could ensure that one (but not both) of them is non-NULL like this:
CHECK (
    (INGREDIENT_ID IS NULL AND SUBRECIPE_ID IS NOT NULL)
    OR (INGREDIENT_ID IS NOT NULL AND SUBRECIPE_ID IS NULL)
)

As it stands, you'll need a trigger for that.

A: Ingredients and Recipes are both possible RecipeItems:
CREATE TABLE RecipeItems (
  ItemID       SERIAL,
  Type         ENUM('Ingredient', 'Recipe'),
  Name         VARCHAR(255) NOT NULL,
  Quantity     FLOAT NOT NULL,
  INDEX (ItemID, Type)
);

CREATE TABLE Ingredients (
  IngredientID BIGINT UNSIGNED NOT NULL,
  Type         ENUM('Ingredient'),
  CostPrice    DECIMAL(6,2),
  PRIMARY KEY (IngredientID),
  FOREIGN KEY (IngredientID, Type) REFERENCES RecipeItems (ItemID, Type)
);

CREATE TABLE Recipes (
  RecipeID     BIGINT UNSIGNED NOT NULL,
  Type         ENUM('Recipe'),
  SellPrice    DECIMAL(6,2),
  Date         DATE,
  Instructions TEXT,
  PRIMARY KEY (RecipeID),
  FOREIGN KEY (RecipeID, Type) REFERENCES RecipeItems (ItemID, Type)
);

Then RecipeLineItems:
CREATE TABLE RecipeLineItems (
  RecipeID     BIGINT UNSIGNED NOT NULL,
  ItemID       BIGINT UNSIGNED NOT NULL,
  Quantity     FLOAT NOT NULL,
  PRIMARY KEY (RecipeID, ItemID),
  FOREIGN KEY (RecipeID) REFERENCES Recipes     (RecipeID),
  FOREIGN KEY (ItemID)   REFERENCES RecipeItems (ItemID)
);

With this approach, I recommend that you enable strict SQL mode (or else invalid values will be accepted in the ENUM typed columns with the empty string '' as a special error value): this could break the intended referential integrity of the above model.  An alternative (but slightly more tedious) approach would be to enforce referential integrity manually using triggers.
If only MySQL supported CHECK constraints, huh?

A: This script will create you a database which let you manage recipes, ingredients, the recip composition (ingredients_recipes) and also unities for you inventory and the composition. It also let you manage your inventory history.
Here is the query to get your current recipe, the ingredients needed, the quantity needed and the stock you currently have :
SELECT recipes.id, recipes.name AS recipeName, ingredients.name AS ingredientNeeded, CONCAT(ingredients_recipes.Qty,' ',neededUnities.name) AS neededQuantity, CONCAT(inventories.qty,' ',inventoryUnities.name) AS availableQuantity FROM recipes

LEFT JOIN ingredients_recipes ON recipes.id=ingredients_recipes.recipe_id
LEFT JOIN ingredients ON ingredients_recipes.ingredient_id = ingredients.id
LEFT JOIN inventories ON ingredients.id=inventories.ingredient_id
LEFT JOIN unities AS inventoryUnities ON inventories.unity_id=inventoryUnities.id
LEFT JOIN unities AS neededUnities ON ingredients_recipes.unity_id=neededUnities.id

WHERE inventories.`update` = (SELECT MAX(`update`) FROM inventories AS inv WHERE inv.ingredient_id = inventories.ingredient_id);

the database :
-- --------------------------------------------------------
-- Host:                         127.0.0.1
-- Server version:               5.5.16 - MySQL Community Server (GPL)
-- Server OS:                    Win32
-- HeidiSQL version:             7.0.0.4053
-- Date/time:                    2012-12-14 16:33:22
-- --------------------------------------------------------

/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET NAMES utf8 */;
/*!40014 SET FOREIGN_KEY_CHECKS=0 */;

-- Dumping database structure for database
DROP DATABASE IF EXISTS `database`;
CREATE DATABASE IF NOT EXISTS `database` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `database`;

-- Dumping structure for table database.ingredients
DROP TABLE IF EXISTS `ingredients`;
CREATE TABLE IF NOT EXISTS `ingredients` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(250) NOT NULL,
  `unity_id` int(11) NOT NULL COMMENT 'for the default unity',
  `Created` datetime DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `Unity_id` (`unity_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Dumping data for table database.ingredients: ~0 rows (approximately)
DELETE FROM `ingredients`;
/*!40000 ALTER TABLE `ingredients` DISABLE KEYS */;
/*!40000 ALTER TABLE `ingredients` ENABLE KEYS */;

-- Dumping structure for table database.ingredients_recipes
DROP TABLE IF EXISTS `ingredients_recipes`;
CREATE TABLE IF NOT EXISTS `ingredients_recipes` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `ingredient_id` int(10) NOT NULL,
  `recipe_id` int(10) NOT NULL,
  `Qty` float NOT NULL,
  `Unity_id` int(10) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `ingredient_id_recipe_id` (`ingredient_id`,`recipe_id`),
  KEY `Unity_id` (`Unity_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Dumping data for table database.ingredients_recipes: ~0 rows (approximately)
DELETE FROM `ingredients_recipes`;
/*!40000 ALTER TABLE `ingredients_recipes` DISABLE KEYS */;
/*!40000 ALTER TABLE `ingredients_recipes` ENABLE KEYS */;

-- Dumping structure for table database.inventories
DROP TABLE IF EXISTS `inventories`;
CREATE TABLE IF NOT EXISTS `inventories` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `ingredient_id` int(10) NOT NULL COMMENT 'ingredient',
  `qty` int(10) NOT NULL COMMENT 'quantity',
  `unity_id` int(11) NOT NULL COMMENT 'unity for the ingredient',
  `update` datetime NOT NULL COMMENT 'date of the inventory update',
  UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Dumping data for table database.inventories: ~0 rows (approximately)
DELETE FROM `inventories`;
/*!40000 ALTER TABLE `inventories` DISABLE KEYS */;
/*!40000 ALTER TABLE `inventories` ENABLE KEYS */;

-- Dumping structure for table database.recipes
DROP TABLE IF EXISTS `recipes`;
CREATE TABLE IF NOT EXISTS `recipes` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(250) NOT NULL,
  `cooking` longtext NOT NULL,
  PRIMARY KEY (`id`),
  KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Dumping data for table database.recipes: ~0 rows (approximately)
DELETE FROM `recipes`;
/*!40000 ALTER TABLE `recipes` DISABLE KEYS */;
/*!40000 ALTER TABLE `recipes` ENABLE KEYS */;

-- Dumping structure for table database.unities
DROP TABLE IF EXISTS `unities`;
CREATE TABLE IF NOT EXISTS `unities` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

-- Dumping data for table database.unities: ~0 rows (approximately)
DELETE FROM `unities`;
/*!40000 ALTER TABLE `unities` DISABLE KEYS */;
/*!40000 ALTER TABLE `unities` ENABLE KEYS */;
/*!40014 SET FOREIGN_KEY_CHECKS=1 */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;

A: You'll need three tables: a recipes table, an ingredients table, and a recipe_ingredients table that assigns ingredients to a recipe. You can also store additional information in this table, such as quantities. So for example, if you have a recipe for vegetable soup, you would have multiple entries for vegetables with the corresponding quantities. These entries would then be linked to the relevant recipe and ingredients via a foreign key.
EDIT: Schema at its simplest:
CREATE TABLE `ingredients` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) TYPE=InnoDB;

CREATE TABLE `recipes` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `name` varchar(45) NOT NULL,
  PRIMARY KEY (`id`)
) TYPE=InnoDB;

CREATE TABLE `recipe_ingredients` (
  `recipe_id` int(10) unsigned NOT NULL,
  `ingredient_id` int(10) unsigned NOT NULL,
  `quantity` int(10) unsigned NOT NULL,
  KEY `recipe_id` (`recipe_id`),
  KEY `ingredient_id` (`ingredient_id`)
) TYPE=InnoDB;

ALTER TABLE `recipe_ingredients`
  ADD CONSTRAINT `recipe_ingredients_ibfk_2` FOREIGN KEY (`ingredient_id`) REFERENCES `ingredients` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  ADD CONSTRAINT `recipe_ingredients_ibfk_1` FOREIGN KEY (`recipe_id`) REFERENCES `recipes` (`id`) ON DELETE CASCADE ON UPDATE CASCADE;

A: One way.
Dish
Key ID Name
1   1  Snails in Marinara Sauce
2   2  Marinara Sauce
3   3  Glass of Water

Ingredient
Key DISHID Name
1   NULL   Snail
2   NULL   Tomato
3   NULL   Onion
4   NULL   Evian
5   2      Marinara Sauce

Recipe
DishID IngredientKey Qty UOM
1      1             6   Each
1      5             3   TblSpoon
2      2             2   Each
2      3             1   Each
3      4             275 Millilitres

So if an ingredient is a dish, it has a recipe.
Amended after a question from OP, that pointed to a wee flaw in my potential answer.


text:
Q: Error: expected an identifier while compiling a program of cusp which is opensource library of CUDA The basic idea is to do sparse matrix-vector multiplication(SpMV) with CUSP under Compressed Sparse Row(CSR) Compressed format ,the code is below:
the code of csr.cu
#include <string.h>
#include "fileproc.h"
#include <cusp/csr_matrix.h>
#include <cusp/detail/device/spmv/csr_vector.h>
#define VALUETYPE float
#define INDEXTYPE int
using namespace std;
int main( int argc, char *argv[] )
{
 string file=argv[1];
 INDEXTYPE m;
 INDEXTYPE n;
 INDEXTYPE nnz;
 INDEXTYPE * rowA,*colA;
 VALUETYPE * valA;
 readFile(file,colA,rowA,valA,m,n,nnz);
 //the code will be omitted because of too much of them
 return 0;
}

the code of fileproc.h
#ifndef _FILEPROC_H_
#define _FILEPROC_H_

#include <string>
#include <iostream>
#include <fstream>
/*triples for storing original data from files */

template <class T, class ITYPE>
struct Triple
{
    ITYPE row;  //  row index
    ITYPE col;  //  col index
    T val;      //  value
};

/*counting the nonzeros along the rows*/
template <typename ITYPE>
ITYPE CumulativeSum (ITYPE * arr, ITYPE size)
{
     ITYPE prev;
     ITYPE tempnz = 0 ;
     for (ITYPE i = 0 ; i < size ; ++i)
     {
        prev = arr[i];
        arr[i] = tempnz;
        tempnz += prev ;
     }
     return (tempnz) ;          // return sum
}
/*convert the matrix to triples*/
template <typename T,typename ITYPE>
void Triple_init(std::string fileName,Triple<T,ITYPE> *A)
{
    ITYPE flops;
    //cout <<"reading input matrix in text(ascii).."<<endl;
    int m,n,nnz;
    std::ifstream infile(fileName.c_str());
    char line[256];
    char c=infile.get();
    while(c=='%')
    {
        infile.getline(line,256);
        c=infile.get();
    }
    infile.unget();
    infile>>m>>n>>nnz;
    flops=nnz*2;
    if(infile.is_open())
    {
        ITYPE cnz=0;
        while (!infile.eof() && cnz<nnz)
        {
            infile>>A[cnz].row>>A[cnz].col>>A[cnz].val;
            A[cnz].row--;
            A[cnz].col--;
            //cout<<A[cnz].row<<" "<<A[cnz].col<<" "<<A[cnz].val<<endl;
            ++cnz;
        }
        std::assert(cnz==nnz);
     }
     infile.close();
   }

   /*assigned the value to m(row),n(column) and nnz(the number of non-zeros)*/
   template <typename ITYPE>
   void init_nnz(std::string fileName,ITYPE& m,ITYPE& n,ITYPE& nnz)
   {
       ITYPE flops;
       std::cout <<"reading input matrix in text(ascii).."<<std::endl;
       std::ifstream infile(fileName.c_str());
       char line[256];
       char c=infile.get();
       while(c=='%')
       {
           infile.getline(line,256);
           c=infile.get();
        }
        infile.unget();
        infile>>m>>n>>nnz;
        infile.close();
    }

    /*convert to CSR format*/
    template <class T,class ITYPE>
    void init_csr(Triple<T,ITYPE> * triples,ITYPE *& jc,ITYPE *& ir,T *& num,ITYPE m,ITYPE n,ITYPE size)
    {
        // Constructing empty Csr objects (size = 0) are not allowed.
        assert(size != 0 && n != 0);
        ITYPE * w = new ITYPE[m];   // workspace of size n (# of columns)

        for(ITYPE k = 0; k < m; ++k)
            w[k] = 0;
        for (ITYPE k = 0 ; k < size ; ++k)
        {
            int tmp =  triples[k].row;
            w [ tmp ]++ ;       // column counts (i.e, w holds the "col difference array")
        }
        if(size > 0)
        {
            ir[m] = CumulativeSum (w, m) ;      // cumulative sum of w
            for(ITYPE k = 0; k < m; ++k)
                ir[k] = w[k];
            ITYPE last;
            for (ITYPE k = 0 ; k < size ; ++k)
            {
                jc[ last = w[ triples[k].row ]++ ]  = triples[k].col ;
            num[last] = triples[k].val ;
             }
        }
        delete [] w;
     }

     /*
      ** convert the file into CSR format
      */
     template <class T,class ITYPE>
     void readFile(std::string name,ITYPE *& jc,ITYPE *& ir,T *& num,ITYPE & m,ITYPE & n,ITYPE &nnz)
     {
         init_nnz<ITYPE>(name,m,n,nnz);
         Triple<T,ITYPE> * A=new Triple<T,ITYPE>[nnz];
         Triple_init<T,ITYPE>(name,A);
         init_csr(A,jc,ir,num,m,n,nnz);
     }
#endif

the makefile is below:
NVIDIA = $(HOME)/NVIDIA_CUDA-5.0_Samples
CUDA = /usr/local/cuda-5.0
CUSP = /home/taoyuan/setup_package
NVIDINCADD = -I$(NVIDIA)/common/inc
CUDAINCADD = -I$(CUDA)/include
CC = -L/usr/lib64/ -lstdc++

GCCOPT = -O2 -fno-rtti -fno-exceptions
INTELOPT = -O3 -fno-rtti -xW -restrict -fno-alias
SPMV = $(CUSP)/cusp/detail/device/spmv
#DEB = -g
#NVCC = -G
#ARCH = -arch=sm_20
ARCH = -arch=sm_35

csr:csr.cu
    nvcc $(DEB) $(NVCC)  $(ARCH) $(CC) -lm  $(NVIDINCADD) -I$(CUSP) -I$(SPMV) -I$(THRUST)  -lcusparse -I./ -o $(@) $(<)

the OS is redhat Enterprise Linux Server release 6.2, the software is cuda-5.0 and thrust 1.5.1 which is setup at directory named "/home/taoyuan/setup_package", GPU is k20M.
while compiling the program, I got the error below:
the error is "fileproc.h(60): error: expected an identifier"

A: Use assert instead of std::assert - assert is a macro, so it is not in the std namespace.


text:
Q: How are charges formed in clouds during lightning? How are charges formed in clouds that are responsible for lightning?

A: The conditions needed to produce lightning have been known for some time. However, exactly how lightning forms has never been verified so there is room for debate. Leading theories focus around separation of electric charge and generation of an electric field within a thunderstorm. Recent studies also indicate that ice, hail, and semi-frozen water drops known as graupel are essential to lightning development. Storms that fail to produce large quantities of ice usually fail to produce lightning.

A: Cloud droplets have the unique ability to geometrically sequence, that is, increase in size by coalescence while contemporaneously decreasing their surface area. This inverse relationship allows whatever charges they have collected by solar radiation to increase the surface charge density on the droplets. The few ions present in the neighboring air will be accelerated so strongly more ions are created by cumulative collision allowing the electricity to escape. This sequence is repeated throughout the entire cloud producing a vast electric field strong enough to break down the dielectric (air).


text:
Q: Using laravel Groupby to iterate through collection I am trying to iterate through a collection and store a record per groupby('type'). At the moment it store all individual records line by line, yet the expected behaviour I need is to store group totals.
dd() returns this. So I want all the appointments hours for a group to SUM and then store the group, .i.e Test = 5 hours. Test2 = 3 hours.
Collection {#471 ▼
  #items: array:2 [▼
    "Test" => Collection {#460 ▼
      #items: array:2 [▼
        0 => Appointment {#463 ▶}
        1 => Appointment {#464 ▶}
      ]
    }
    "Test2" => Collection {#450 ▼
      #items: array:2 [▼
        0 => Appointment {#465 ▶}
        1 => Appointment {#466 ▶}
      ]
    }
  ]
}

Here is the controller code.
   foreach($appointments as $appointment)
{
  $duration = [];
  $aType = $appointments->groupBy('type');

  foreach($aType as $type)
  {
    $duration[]         = $date1->diffInMinutes($date2);
  }

$totalhours             = array_sum($duration); //sum the hours

$Item             = new AppItem;
$Item->type           = $aType->type;
$Item->total_hours = $totalhours;
$Item->save();
}

A: Hoping I understand your question here, but I'm not sure you need to group by since the item's are already sorted by "group", i.e. Test, Test2, etc. Would this work:
$collection->each(function($group, $appointments) {
    return [$group => collect($appointments)->sum(function ($appointment) {
        return $appointment->date1->diffInMinutes($appointment->date2);
    });
});

That should return something like
['Test' => 5, 'Test2' => 8]

If this isn't correct can you give more sample data and an example of what a good result would look like?

A: This ended being the working solution. There is  probably a neater way. In the do stuff sections, you then work with the object returned from previous foreach.
    $appointments = Appointment::find($id)
                    ->get();

$aType = $appointments->groupBy('type');
        $invoice_total = [];
    foreach($aType as $key => $value)
        {
            $duration = [];
            foreach($value as $a)
            {

                $date1  = Carbon::parse($a->starts_at);
                $date2  =  Carbon::parse($a->ends_at);
                $duration[] = $date1->diffInMinutes($date2)/60; //divide by 60 to return hours

        }

    $Item             = new AppItem;
    $Item->type           = $aType->type;
    $Item->total_hours = $totalhours;
    $Item->save();
}

//other stuff
}


text:
Q: Views from old fragment remain in content view after the fragment is replaced I have came across a peculiar bug : in my application I have bottom navigation bar that replaces the fragments in FrameLayout view using a following piece of code:
override fun setFragment(frag: Fragment, addToBackStack: Boolean) {
    FirebaseAnalytics.getInstance(this).setCurrentScreen(this, frag::class.java.simpleName, frag::class.java.simpleName)
    val ft = supportFragmentManager.beginTransaction()
            .setCustomAnimations(R.anim.fragment_in, R.anim.fragment_out, R.anim.fragment_in, R.anim.fragment_out)
            .replace(R.id.container, frag)

    if (addToBackStack) {
        viewModel.showNavigation = false
        ft.addToBackStack(null)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    ft.commit()
}

Everything seems to work fine - but for a one fragment in which in onCreateView method I call the following method:
override fun requestPermissions(permissions: Array<String>, requestCode: Int) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        activity.requestPermissions(permissions, requestCode)
}

This causes the view from the previous fragment to remain on screen and new fragment to be added below them, as seen in the screenshot:

What's worse, the views will stay in the screen until the activity is killed. The only workaround I was able to find was adding a 0,5 second delay before asking for permission:
Handler().postDelayed({ requestPermission(android.Manifest.permission.ACCESS_FINE_LOCATION, requestCode = REQUEST_PERMISSION_LOCATION) }, 500L)

My question is - does anyone know what is the cause of this behaviour and if there's a better way to circumvent it?

A: The solution for me was to set the background color in the xml file as suggested in the original question comments by @Yolo.
android:background="@android:color/white"

After I made this change, pieces of this fragment didn't hang around anymore when I switched to new fragments.


text:
Q: jQuery Animation problem using nested tables I have a problem with animations using jQuery on nested tables. I want to make a table that is a bit like a treeview, with a little + / - to expand and get more details about the clicked row.
How can I modify the following code for the animations to work both in Internet Explorer 6.0+ and in Firefox ?
I can change the markup or the javaScript, it doesn't matter as long as it works.
If this is useful to know, this structure is generated using nested repeaters in asp.net.
I have access to the Telerik's radAjax control suite, but I haven't been able to make their radGrid work with nested tables.
Document structure:

        Code
        Title

        -
        WAA-864R
        Code 1 ... some details ... - MODULE 2

                    Extra Info 1
                    Extra Info 2
                    Extra Info 3

                    Some info...
                    Some more info...
                    Yet more Info

Javascript:

A: Are you able to change the output code, to use UL instead of a table?
If you can, then you might want to take a look at jQuery Treeview plugin. That's what I use for all treeviews.
Actually, it's semantically more appropriate to use an UL rather than a table for a treeview, but in your case would depend on having the chance of changing the code at all.
Anyway, in case you can't, I think you can't fade out TR's... I had a similar problem in the past, so I'd suggest fading out the inner table instead, then hiding the TR.
Also, there's no point in calling end() 3 times. It's faster and more readable if you just do $(this) again after you show/hide the inner table:
var innerTable = $(this).parent().parent().next().find("table");
if ($(this).data("visible")) {
  innerTable.fadeOut();
  innerTable.parent().hide();
  $(this)
    .data("visible", false)
    .text("+");
} else {
  innerTable.parent().show();
  innerTable.fadeIn();
  $(this)
    .data("visible", true)
    .text("-");
}


text:
Q: results-per-page doesn't work when execute cf events I would like to search cloud foundry cf events and set more events in each page like:
cf curl /v2/events?order-direction=asc&page=2&q=type:audit.service_binding.create&results-per-page=**100**

But it also report:
root@boshcli:~/bin# cf curl /v2/events?order-direction=asc&page=2&q=type:audit.service_binding.create&results-per-page=50
[1] 12215
[2] 12216
[3] 12217
**results-per-page=50: command not found**
[2]-  Done                    page=2
[3]+  Done                    q=type:audit.service_binding.create

So I can only use 50 per page.
Does anyone know why?
Thanks a lot! :)

A: As you are not including the url in quotes or escaping the ampersand, your shell interprets these symbols and executes the query parameters as separate commands.
Try:

cf curl "/v2/events?order-direction=asc&page=2&q=type:audit.service_binding.create&results-per-page=50"


text:
Q: How can I run arbitrary commands as part of a deb package install? I'm creating a ppa deb package for a python module, replacing a pip package (which I also created), and I would like to run "pip uninstall" as part of the deb installation.
How can I run "pip uninstall" as part of the ppa package install?
I want to do this because the pip install in /usr/local/lib takes priority over the deb install in /usr/lib, so users who previously installed with pip could unintentionally be using the old pip version when they install the deb version.

I tried two things already, neither of which worked and I don't know why (any suggestions for how to troubleshoot this better would be greatly appreciated -- I tried "dpkg --log=log.txt -i " but the log didn't show any pip uninstall error messages):
A. execute pip uninstall in setup.py
from setuptools import setup
from setuptools.command.install import install

import os.path
import subprocess

class CustomInstallCommand(install):
    def run(self):
        if os.path.exists("/usr/local/lib/python2.7/dist-packages/bamliquidatorbatch"):
            print "Old pip bamliquidatorbatch install detected, attempting to remove"
            subprocess.call(["pip", "uninstall", "-y", "BamLiquidatorBatch"])

        install.run(self)

setup(
    ...
    cmdclass={
        'install': CustomInstallCommand,
    }
)

This worked fine when installed with "sudo python setup.py install" but pip uninstall never ran when the package was installed with "dpkg -i".
B. execute pip uninstall in rules makefile
#!/usr/bin/make -f

%:
    dh $@ --with python2 --buildsystem=python_distutils
    if [ -d "/usr/local/lib/python2.7/dist-packages/bamliquidatorbatch" ]; then pip uninstall -y BamLiquidatorBatch; echo; fi

When I ran similar code in a makefile directly, it worked fine, but again pip uninstall never ran when the package was installed with "dpkg -i".

A: Even if it's not really recommended to remove silently a package in /usr/local you could do it in a debian/bamliquidatorbatch.preinst script:
#!/bin/sh
set -e

if [ -d "/usr/local/lib/python2.7/dist-packages/bamliquidatorbatch" ]; then
    pip uninstall -y BamLiquidatorBatch;
fi

Note that bamliquidatorbatch should be the exact name of your debian binary package (to match debian/bamliquidatorbatch.preinst).


text:
Q: Can I run Android apps on Ubuntu? Is it possible to run Android apps on Ubuntu? And I don't mean inside an emulator, but natively, as you would with any other application installed using the Ubuntu Software Center.

A: Seems there are more and more developers entering this domain.
http://www.shashlik.io/,
What is Shashlik

The goal of Shashlik is to provide a way to run Android applications on a standard Linux desktop as easily and simply as possible.

can run android apps, on Ubuntu. It's not stable, and not all apps work, but it seems promising.
P.S. I had to sudo apt-get install libgl1-mesa-dev and sudo apt-get install kde-baseapps-bin

A: No, you can't (other than through an emulator as mentioned by Oli.) However, it looks like the Ubuntu people are working on this, so you might be able to do it in the future. My proof: http://arstechnica.com/open-source/news/2009/05/canonical-developers-aim-to-make-android-apps-run-on-ubuntu.ars

A: It possible to run Android apps on Ubuntu?
Yes
Natively, as you would with any other application installed using the Ubuntu Software Center?
Yes, but through a lot of tinkering:

*

*Using chrome (Beta level tools);

*Anbox (Alpha level software);

*

*Google Chrome can run Android apps as chrome apps but first, you must convert them using by using Arc Welder or the ARChon Custom Runtime.

*Anbox  is not an emulator but a compatibility layer. It aims to run Android applications on any GNU/Linux operating system by putting the Android operating system into a container, abstracting hardware access and integrating core system services into a GNU/Linux system, so Android applications can be integrated with your operating system like any other native application.

A: YOU CAN
And have several options to do it.

*

*Special emulator like those that come with Android SDK. Don't use ARM-based as they are sloooow.

*Generic virtual machine like VirtualBox with Android x86 installed. My recommend.

*Chrome. Recent versions of Google Chrome can run Android apps inside itself (never tried that, but people rate it high).

*Connect android device by USB or Wi-Fi network, and use some sort of Remote Desktop.

A: You can now under Chrome run APKs, using this extension (bearing in mind it is in development for use by developers for testing apps). Here are some steps I did to get it to work

*

*Install from here -  click 'Add to Chrome'
This will take a while as it seems to download a crx installer weighing in at 113Mb, and another one at around 9Mb, so be patient:

N.B. on my Fedora 21 build of Chromium 40 I got the error 'Manifest file is invalid' when trying install the extension, even after clearing data and reloading the extension. I also had issues with Ubuntu 14.04's build of Chromium 41, so I installed Google Chrome :( and that worked.

*Get a APK of the application you want to use - no, it does not seem like you can install from Google Play, you need a APK file of the app, so this is the tricky bit. Most closed source devlopers don't want their stuff freely distributed, so for most apps on Google Play at least you either need to use:

*

*Use a APK for a open-source app - for testing this I tried using the x86 APK for VLC Media PLayer, which resulted in a error screen - I then tried the armv7 arc version and that worked at first and then crashed.

*Get a APK from a Android device - this easily easily be done on some rooted Android devices, on normal devices I think you can copy system app's apks from /system/apps or somewhere - again not recommended due to legal stuff.

*Use a third-party service/repository of APKs - e.g. this article suggest this one, but the issue here is that you may be downloading modified or infected programs/files. Probably should be considered a last resort.

* Use a third-party extension - e.g. this one that pretends to be a device and downloads (not a good idea if you like legal stuff, plus google tracks your every move (mainly when signed in) so may be found out pretty quick...  Dead as out of date on both browser and likely android support. It isn't recommend to install extensions not in browser's extension store anyway!

*Install it
Now we get to the more fun bit of trying it out. Go to the Apps thing in chrome (or type chrome://apps in the URL bar) and launch Arc Welder. Then choose the directory the APK is in and then the APK, then choose 'Launch App' in the window.
If the window shows the app icon as one that looks like this:the app probably won't work so their may not be much point in continuing. This seemed to happen alot with apps for Android 4.4+...

*Use it
I managed to get QuickOffice to run and mostly work under the extension, though I couldn't save any documents as it was not happy about choosing the place to save the file (showing a folder selection box, not a file selection box for saving :P )

After you press 'Launch App', the extension automatically adds a entry to the apps page on Chrome - this you can make into a standalone application launcher to launch the app directly from your app menu/dash/launcher - this is possibly the best feature of this extension as integrates with the desktop and you don't need to launch a emulator etc first.

Overall this is brilliant, considering this probably is still in development and not designed for this it works quite well.
Sources:

*

*Getting Started with ARC

*Android apps to run on Windows, Macs and Linux

*Test Android apps in Chrome OS, Windows, OS X, or Linux using ARC Welder Chrome app

Alternatively you can use a emulator as suggested in other answers - I did have some success using Genymotion (there were some handy instructions here, but this answer may help). Android Emulator can be got as part of the Android Studio SDK, however since Android Nougat apps should be signed.

A: The straight answer is no you can't. Although Android apps are developed in Java and thus should work, the environment is completely different:

*

*Screen size is limited, the concept of a "Windowing System" does not exist in a mobile

*Some of the hardware simply isn't there, SIM card, GPS, etc

There's an emulator that fools the apps by giving them those extra bits they need. But it uses the native OpenJDK on your machine so they will run well. Think of it like a test environment and not an emulator.
Anyway if you idea is running Layar in your laptop, forget it, it doesn't make any sense at all.

A: A more recently available option is Anbox. Unlike most other solutions, it is container based rather than being an emulator. This means that it runs on the host kernel. It also attempts to integrate into your host OS so that apps appear to be native. It is currently alpha but looks promising.

A: The closest you'll get is through an emulator. This answer might not be for you (you might already know all this) but if other people drop into this thread, they might be interested in knowing.
You can run things through the Android emulator, part of the Android SDK (software development kit).
This provides a virtual device which does allow you to run quite a lot of Android applications though it may struggle with some of the more hardware-dependent things (3D, Phone calls, GPS, SMS, etc)
Here's a guide on getting it set up:
How to Run Android Applications on Ubuntu - Softpedia

A: Ubuntu Web
Ubuntu Web is an Ubuntu remix that is designed to be an open source desktop Linux replacement for Chrome OS.
/e/OS is an open-source mobile operating system paired with carefully selected applications. They form a privacy-enabled internal system for your smartphone. And it's not just claims: open-source means auditable privacy. Logging into the /e/ account makes it possible for you to take advantage of a rather nifty trick Ubuntu Web has up its sleeve. This trick is WayDroid, a port of Anbox which allows users to install Android apps from the /e/ store.  source
Visit /e/ Application Checker to check if your favorite Android apps are available in the /e/ store, for example there's YouTube and Instagram which make it possible to view these two apps on your tablet in full screen portrait mode.


text:
Q: Refused to connect when accessing phpmyadmin on docker container I use docker-compose to setup my application with below app.yml:
version: '2'
services:
    hdback-app:
        image: xxxx:0.0.3
        environment:
            - SPRING_PROFILES_ACTIVE=prod,swagger
            - SPRING_DATASOURCE_URL=jdbc:mysql://db:3306/sample?useUnicode=true&characterEncoding=utf8&useSSL=false
            - JHIPSTER_SLEEP=10 # gives time for the database to boot before the application
            - SPRING_DATA_ELASTICSEARCH_CLUSTER_NODES=sample-elasticsearch:9300
        ports:
            - 8080:8080
    db:
        extends:
            file: mysql.yml
            service: db
    nginx:
        extends:
            file: nginx.yml
            service: nginx
    hdback-elasticsearch:
        extends:
            file: elasticsearch.yml
            service: hdback-elasticsearch
    phpmyadmin:
        image: phpmyadmin/phpmyadmin
        depends_on:
            - db
        ports:
            - 8081:8081

The application is installed on Centos 7, the nginx.yml is as below:
services:
    nginx:
        image: nginx:1.14.0
        volumes:
            - ./../www:/usr/share/nginx/html
            - ./nginx/site.conf:/etc/nginx/conf.d/default.conf
        ports:
            - "80:80"

And the site.conf is as below:
server {
    listen 80;
    index index.html;
    server_name localhost;
    error_log  /var/log/nginx/error.log;

    location / {
        root /usr/share/nginx/html;
    }
    location /api {
        proxy_pass http://www.sample.com:8080/api;
    }
    location /management {
        proxy_pass http://www.sample.com:8080/management;
    }
    location /v2 {
       proxy_pass http://www.sample.com:8080/v2;
    }
    location /swagger-ui {
        proxy_pass http://www.sample.com:8080/swagger-ui;
    }
    location /swagger-resources {
        proxy_pass http://www.sample.com:8080/swagger-resources;
    }
}

When I up the application, www.sample.com works, that is, port 80 works, however, when I want to access phpmyadmin, the browser says:
sample.com refused to connect

I disable the firewall, and ensure the port 8081 is listening, below is when I issue:
docker ps
CONTAINER ID        IMAGE                                                    COMMAND                   CREATED             STATUS              PORTS                                            NAMES
5a18390de5e1        phpmyadmin/phpmyadmin                                    "/run.sh supervisord…"    24 hours ago        Up 24 hours         80/tcp, 9000/tcp, 0.0.0.0:8081->8081/tcp         docker_phpmyadmin_1
1de715bb735d        nginx:1.14.0                                             "nginx -g 'daemon of…"    24 hours ago        Up 24 hours         0.0.0.0:80->80/tcp                               docker_nginx_1
6b748cb592ec        elasticsearch:2.4.6                                      "/docker-entrypoint.…"    24 hours ago        Up 24 hours         0.0.0.0:9200->9200/tcp, 0.0.0.0:9300->9300/tcp   docker_hdback-elasticsearch_1
dd3de12c3ff4        mysql:5.7.20                                             "docker-entrypoint.s…"    24 hours ago        Up 24 hours         0.0.0.0:3306->3306/tcp                           docker_db_1
c0ad30aabd3c        xxxx:0.0.3   "/bin/sh -c 'echo \"T…"   24 hours ago        Up 24 hours         0.0.0.0:8080->8080/tcp                           docker_hdback-app_1

I have spent almost half day to find solution but no luck, what is going wrong?

A: It refuses to connect because you connect from port 8081 of the host to port 8081 of the container, while phpmyadmin is served at port 80, as you can see here
So map it this way:
phpmyadmin:
    image: phpmyadmin/phpmyadmin
    depends_on:
        - db
    ports:
        - 8081:80

and it should work


text:
Q: TypeError: this.navigator.element.pushPage is not a function Im using onsen-ui with angular 8 I'm getting error in the below function, I am not sure why this happens, because it is the code from the onsenUI-page.
push(event, value){
        console.log(value);
        this.navigator.element.pushPage(value, {animation: 'slide'});
      }

My code
Sidemenu.html
<ons-page id="menu">
<ons-toolbar>

Menu

  </ons-toolbar>

    <ons-list>
        <ons-list-item (click)="push($event, 'HomeComponent')" tappable>
          Home
        </ons-list-item>
        <ons-list-item (click)="push($event, 'FormComponent')" tappable>
          Form
        </ons-list-item>
      </ons-list>

</ons-page>

sidemenucomponent.html
import { Component, OnInit } from '@angular/core';
import { ViewChild, OnsNavigator} from 'ngx-onsenui';
import { HomeComponent } from './../home/home.component';

@Component({
  selector: 'ons-page[third]',
  templateUrl: './sidemenu.component.html',
  styleUrls: ['./sidemenu.component.scss'],
  providers:[OnsNavigator]
})
export class SidemenuComponent implements OnInit {

  constructor(private navigator: OnsNavigator) { }

  ngOnInit() {
  }
  push(event, value){
    console.log(value);
    this.navigator.element.pushPage(value, {animation: 'slide'});
  }

}

Im getting error
ERROR TypeError: this.navigator.element.pushPage is not a function
    at SidemenuComponent.push (sidemenu.component.ts:20)
    at Object.eval [as handleEvent] (VM5587 SidemenuComponent.ngfactory.js:21)
    at handleEvent (core.js:43993)
    at callWithDebugContext (core.js:45632)
    at Object.debugHandleEvent [as handleEvent] (core.js:45247)
    at dispatchEvent (core.js:29804)
    at core.js:42925
    at HTMLElement.<anonymous> (platform-browser.js:2668)
    at ZoneDelegate.invokeTask (zone-evergreen.js:391)
    at Object.onInvokeTask (core.js:39680)

Below is the app component i added  but still getting same error
app.component.html
<ons-navigator swipeable [page]="sidePage"></ons-navigator>
<ons-page id="apppage">
<ons-splitter #splitter>
  <ons-splitter-side [page]="sidePage" side="left" width="300px" collapse swipeable>
  </ons-splitter-side>

  <ons-splitter-content [page]="contentPage">
  </ons-splitter-content>
</ons-splitter>
</ons-page>
<router-outlet></router-outlet>

app.component.ts
import { Component } from '@angular/core';
import { HomeComponent } from './components/home/home.component';
import { SidemenuComponent } from './components/sidemenu/sidemenu.component';
import { MenuService } from './menu-service.service';

import {
  Injectable,
  ViewChild,
} from 'ngx-onsenui';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  title = 'my-app';

  sidePage = SidemenuComponent;
  contentPage = HomeComponent;
  @ViewChild('splitter',{static: false}) splitter;
  constructor(private menuService: MenuService) {
    this.menuService.menu$.subscribe(() => this.splitter.nativeElement.side.open());
  }
}

Please can anyone help.


text:
Q: Apple Mach O-Linker Error Xcode I have used RevMob as an advertising source for awhile now. They just recently came out with reward video ads so I tried to add their new framework. When I dragged the new framework into my Xcode project (which had the same name as the existing framework: RevMobAds.framework) I immediately got an error. I quickly deleted the framework but still have 8 errors on my project that say: Apple Mach O-Linker Error. I have looked up a lot about this and this is what I have tried:

*

*added $(ARCHS_STANDARD_INCLUDING_64_BIT) to the Architectures build    active architecture only

*set to 'NO' for 'valid architectures'

*set to arm64, armv7 and armv7s

*deleted the DerivedData folder and its contents, cleaned and built
again
Here are what my errors look like: (everything in bold is what is highlighted red for errors)
Undefined symbols for architecture x86_64:   "_AVMediaTypeVideo",
referenced from:
      -[RevMobDeviceInfo cameraPermission] in RevMobAds(RevMobDeviceInfo.o)
      ___99-[RevMobFullscreen proceedLoadWithSuccessHandler:andLoadFailHandler:onClickHandler:onCloseHandler:]_block_invoke106
in RevMobAds(RevMobFullscreen.o)   "_OBJC_CLASS_$_AVCaptureDevice",
referenced from:
      objc-class-ref in RevMobAds(RevMobDeviceInfo.o)   "_OBJC_CLASS_$_AVURLAsset", referenced from:
      objc-class-ref in RevMobAds(RevMobFullscreen.o)   "_OBJC_CLASS_$_CLBeaconRegion", referenced from:
      objc-class-ref in RevMobAds(RevMobBeaconManager.o)   "_OBJC_CLASS_$_CLLocationManager", referenced from:
      objc-class-ref in RevMobAds(RevMobDeviceInfo.o)
      objc-class-ref in RevMobAds(RevMobBeaconManager.o)   "_kCLDistanceFilterNone", referenced from:
      -[RevMobDeviceInfo getUserLocation] in RevMobAds(RevMobDeviceInfo.o)   "_kCLLocationAccuracyBest",
referenced from:
      -[RevMobDeviceInfo getUserLocation] in RevMobAds(RevMobDeviceInfo.o) ld: symbol(s) not found for architecture
x86_64 clang: error: linker command failed with exit code 1 (use -v
to see invocation)

Any help would be greatly appreciated. I am not going to mess around with the video ads anymore I just want my project to be back the way it was with no errors!  Thanks everyone!

A: I faced the same issue before, try adding AVFoundation and CoreLocation frameworks to your project.

A: This also happens if you added CoreLocation to your app, but copied it in instead of doing a relative framework link... so check to make sure you didn't copy CoreLocation.framework into your app by mistake.


text:
Q: drf-yasg - testproj - how to silent all the debug output How can I silent the debug statements for drf-yasg - testproj ?
https://github.com/axnsan12/drf-yasg
This is how I set it up:
$ git clone https://github.com/axnsan12/drf-yasg.git
$ cd drf-yasg
$ virtualenv venv
$ source venv/bin/activate
(venv) $ cd testproj
(venv) $ python -m pip install -U pip setuptools
(venv) $ pip install -U -r requirements.txt
(venv) $ python manage.py migrate
(venv) $ python manage.py runserver
(venv) $ firefox localhost:8000/swagger/

But it keeps producing a lot of debug prints which makes it difficult for me test certain features. How do I silent these debug prints ? Thanks.
Here are the debug prints:
2019-09-14 08:02:10,769 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/coreapi/exceptions.py first seen with mtime 1568447198.368635
2019-09-14 08:02:10,769 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/rest_framework/relations.py first seen with mtime 1568447200.446008
2019-09-14 08:02:10,769 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/requests/certs.py first seen with mtime 1568447203.023515
2019-09-14 08:02:10,769 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/coreapi/compat.py first seen with mtime 1568447198.368073
2019-09-14 08:02:10,770 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/rest_framework/utils/model_meta.py first seen with mtime 1568447200.529353
2019-09-14 08:02:10,770 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/django/contrib/auth/middleware.py first seen with mtime 1568447201.356465
2019-09-14 08:02:10,770 | DEBUG | django.utils.autoreload | File /Users/axil/Documents/project/unrealpower/unrealpower_upgrade_v2/testdrf/drvenv/lib/python3.6/site-packages/rest_framework/renderers.py first seen with mtime 1568447200.446478

A: Logging settings are configured for this test project in testproj/testproj/settings/base.py file. Change log level to INFO for drf_yasg  and django package there. like this
   'drf_yasg': {
        'handlers': ['console_log'],
        'level': 'INFO',
        'propagate': False,
    },

    'django': {
        'handlers': ['console_log'],
        'level': 'INFO',
        'propagate': False,
    }


text:
Q: Triggering a command line run with Java based Native Messaging Host for chrome extension I am trying to build a chrome extension which can run a command on the user desktop. For this I am trying to use native messaging to send the trigger from extension to a native messaging host which can then run the command.
Chrome extension's manifest.json
{
    "manifest_version": 3,
    "name": "chrome extension",
    "description": "Initial base version",
    "version": "1.0",
    "content_scripts": [
        {
          "matches": ["http://*/*", "https://*/*"],
          "js": ["contentscript.js"]
        }
      ],
    "background": {
        "service_worker": "background.js"
    },
    "action": {
        "default_popup": "hello.html"
    },
    "permissions": [
        "nativeMessaging"
    ]
}

native-messaging-host manifest
{
    "name" : "com.xx.xx.xx.xx.nativemessaginghost",
    "description" : "POC",
    "path" : "chrome-extension.bat",
    "type" : "stdio",
    "allowed_origins" : [
        "chrome-extension://kfnopggaelngaopgpiogficbbdhmlpia/"
    ]
}

chrome-extension.bat
@echo OFF

java -jar "%~dp0/native-messaging-host-java-1.0-SNAPSHOT.jar" %*

I am launching a java application which is responding to the extension.( Followed the example code from chrome-native-messaging-java )

final Application app = new Application();
ConnectableObservable<String> obs = app.getObservable();
obs.observeOn(Schedulers.computation()).subscribe(new Observer<String>() {
            public void onCompleted() {
            }

            public void onError(Throwable throwable) {
            }

            public void onNext(String s) {

                log("Host received " + s);

                JSONObject obj = new JSONObject(s);
//                executeCommand();
                log("Message is " + obj.getString("text"));

                String sl = "{\"success\":true," + "\"message\":\"" + "response from app" + "\"}";
                try {
                    app.sendMessage(sl);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
obs.connect();
while (!app.interrompe.get()) {
     try {
           Thread.sleep(1000)
         } catch (InterruptedException e) {
           break;
         }
    }
System.exit(0);

Before responding back to extension I am trying to make the host execute a command using ProcessBuilder class the following way. I am redirecting all the output of the ProcessBuilder to a file so that it doesn't overload the extension which is listening to the stdout.
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.redirectErrorStream(true);
File log1 = new File("command-output.log");
processBuilder.redirectOutput(log1);
builderList.add("cmd.exe");
builderList.add("/C");
builderList.add("tasklist | findstr chrome");
processBuilder.command(builderList);
Process process = processBuilder.start();

the connection to the extension is broken with the following error
Error: Native application tried to send a message of 1734439797 bytes
Am I missing anything while making the call with ProcessBuilder in native messaging host ?
The only solution I can think of is to run another local server and make an Asynchronous rest call to this server from the native messaging host. The server can then execute the command and its stdout won't affect the extension.


text:
Q: jQuery Promise not waiting until resolved I have a function that returns a promise as follows:
var loadLimits = function (url, arr, carrier) {
    var rdata = {
        carrierId: carrier
    };

    var deferred = new $.Deferred();
    var xhr = $.get(apiHost + url, rdata);
    xhr.done(function (data) {
        arr.removeAll();
        for (var i = 0; i < data.length; i++) {
            var newItem = new LimitItem(data[i].Id, data[i].LimitText,  data[i].ILF, data[i].ApprovalRequired);
            arr().push(newItem);
        };
        deferred.resolve();
    });
    xhr.fail(function () {
        deferred.reject();
    });

    return deferred.promise();
};

I'm calling that function from within another function as follows:
  var promise = loadLimits(url, limitsArray, carrierId);
  promise.done(self.nextFunction());

Why is my code firing self.nextFunction before the promise resolves?  Eventually the promise DOES resolve successfully, so its not an ajax fail event. I'm using jQuery 1.9.1 and I'm testing with Chrome.
Thanks for any help

A: Use either
promise.done(self.nextFunction);

or
promise.done(function(){ self.nextFunction(); });

Your code immediately executes that function, instead of passing it as a reference/callback to be executed later.


text:
Q: sharepoint 2013 global search center and different zones I have sharepoint 2013 server farm with alternate access mapping.
I have two zones with URLs:

*

*http://portal (Default)

*https://portal.domain.com (Internet)

I have a global search center site collection with url http:// portal/sites/search.
I want users from default zone when searching to redirect to http://portal/sites/search, while users from internet zone redirect to https://portal.domain.com/sites/search.
But I can only enter one full URL of search center in search options.
How can I achieve this?
Thank you!

A: Just figured that i can enter relative link as global search URL. Now all works just fine.
I'm entered /sites/search/pages as my URL and now in all zones users redirects to right URL.


text:
Q: Unexpected token React-Redux I REALLY don't know why i am getting this syntax error:

30 |   })
   31 |   */
  32 |   function mapStateToProps(state) {
      | //////////////////           ^
   33 |     return {
   34 |       count: state.count
   35 |     }

**Here is my code: **
import React from 'react';
import { connect } from 'react-redux';

class Counter extends React.Component {

  increment = () => {

  }

  decrement = () => {

  }

  render() {
    return (

Counter

          <button onClick={this.decrement}>-</button>
          {this.props.count}
          <button onClick={this.increment}>+</button>

    )
  }

  /* This try is showing me the same error in the same place
  const mapStateToProps = state => ({
    count: state.count
  })
  */
  function mapStateToProps(state) { //This is the line. Right in the "m"
    return {
      count: state.count
    }
  }

}

export default connect(mapStateToProps)(Counter);

I am trying this guide: https://daveceddia.com/how-does-redux-work/

A: Your issue here is using the function keyword. Classes can only contain prototypal methods and a constructor (as of ECMAScript 2015). Normally if you declaring a method within a class you'd have:
  mapStateToProps(state) { //This is the line. Right in the "m"
    return {
        count: state.count
    }
}

or use an arrow function
 mapStateToProps = (state)=> { //This is the line. Right in the "m"
        return {
            count: state.count
        }
    }

EDIT
As mentioned in later answers you need to move your map to state declaration from within the class.
Then you can have
const mapStateToProps = (state)=> { //This is the line. Right in the "m"
            return {
                count: state.count
            }
        }

should you decide to go with an arrow function.

A: You are declaring a function within a class:
class Counter extends React.Component {

  // ...

  function mapStateToProps(state) {
    // ...
  }

}

which is invalid JS syntax. Move the function declaration outside the class:
class Counter extends React.Component {

  // ...

}

function mapStateToProps(state) {
  // ...
}

A: Move the following code outside the definition of the class "Counter":
function mapStateToProps(state) { //This is the line. Right in the "m"
    return {
        count: state.count
    }
}

This solves both the problem of the invalid function keyword inside a class and the second problem, which you would encounter soon after, that the mapStateToProps function isn't directly accessible if you put it inside the class "Counter".
Write it like that and it should work:
class Counter extends React.Component {
    ...
}

function mapStateToProps(state) { //This is the line. Right in the "m"
    return {
        count: state.count
   }
}

export default connect(mapStateToProps)(Counter);

A: You need to put mapStateToProps outside class Counter. As mapStateToProps is another separated function not belonged to Counter.


text:
Q: Why does R interpreter segfault on an underscore? This is more out of curiosity than anything else, but why does an _ cause the R interpreter to segfault? More generally, is there a list somewhere of input characters that will cause the R interpreter to die?
When the following script is sourced, it causes the R interpreter to segfault.
for  (_ in 1:50) {
}

This is reproducible by running R on the command line and then typing
source("Foo.r")

I am running 3.0.2. I am curious because it took me some time to isolate this bug.

A: This is a known bug in R 3.0.2 that has already been fixed and will be available in the next release, as documented in the read me file for the latest patched sources. The R development team determined that this bug is not OS-specific and that it only affects R 3.0.2.
Read the bug report above and the source code for more details.

A: Not an answer, but more test data:
OSX 3.0.2,  if I do <\cmd>E on a text file,
Rgames> source("/var/folders/+N/+NUwiD8-Fse2oprSglHTd++++TM/-Tmp-//RtmphWNc9F/file17f8f461ba1ed")
Error in source("/var/folders/+N/+NUwiD8-Fse2oprSglHTd++++TM/-Tmp-//RtmphWNc9F/file17f8f461ba1ed") :
  /var/folders/+N/+NUwiD8-Fse2oprSglHTd++++TM/-Tmp-//RtmphWNc9F/file17f8f461ba1ed:1:7: unexpected input
1: for  (_
         ^
Rgames> unlink("/var/folders/+N/+NUwiD8-Fse2oprSglHTd++++TM/-Tmp-
//RtmphWNc9F/file17f8f461ba1ed")

Similarly, if I save the text file,
Rgames> source('foo.r')
Error in source("foo.r") : foo.r:1:7: unexpected input
1: for  (_
         ^

So this clearly is not a bug on all operating systems.
Further, I tried doing  "source(textConnection("for (_ in 1:50) { }") )" like DWin posted in comments, and got no segfault in R.app GUI.
ETA: No segfault under Win7x64, R3.0.2x64, either from cygwin command line or rgui.exe.


text:
Q: Can someone explain to me why pyautogui TypeError: cannot unpack non-iterable NoneType object I'm trying to create a bot that recognizes an image on screen and to be able to click on that image. However, when prompting the bot to click on the image, I am prompted with TypeError: cannot unpack non-iterable NoneType object.
import pyautogui as pg
import keyboard
import time
import pytesseract as tess
from PIL import Image

if pg.locateOnScreen('follow1.png', confidence=0.5) != None:
    pg.click('follow1.png')

However, the bot can recognize the image on screen but fails to click on it.
import pyautogui as pg
import keyboard
import time
import pytesseract as tess
from PIL import Image

if pg.locateOnScreen('follow1.png', confidence=0.5) != None:
    pg.print('found it!')

How can the script recognize the image on screen but fail to click on it?

A: I ran into this issue, too. I finally found out the reason was that the icon on the screen has changed due to software update. So I used a new snapshot to repalce the old one. And it worked!
pyautogui.click('D:/pp/video/3/edit.png')

Traceback (most recent call last):
File "", line 1, in
File "D:\Users\cordiero\PycharmProjects\untitled\video\lib\site-packages\pyautogui_init_.py", line 598, in wrapper
returnVal = wrappedFunction(*args, **kwargs)
File "D:\Users\cordiero\PycharmProjects\untitled\video\lib\site-packages\pyautogui_init_.py", line 980, in click
x, y = _normalizeXYArgs(x, y)
TypeError: cannot unpack non-iterable NoneType object
pyautogui.click('D:/pp/video/3/edit.png')

A: I am pretty new, so this might not work, but what I did was change this in the code:
From: pyautogui.click('Image.png')
To: pyautogui.click(pyautogui.locateOnScreen('Image.png'))
And it worked for me, hope it also does for you!