text:
Q: Django: is there a generic handler to insert a POST object directly into the database? Django: is there a generic handler to insert a POST object directly into the database?  I find myself writing a lot of handlers that look like this.
def ajax_storeObject(request):
    if request.method == 'POST':
         Object(
                field1 = request.POST["field1"],
                field2 = request.POST["field2"],
                field3 = request.POST["field3"],
                field4 = request.POST["field4"],
          ).save()
          return HttpResponse(json.dumps({"status":"Success"}), mimetype="application/json")
    return HttpResponse(json.dumps({"status":"Failed"}), mimetype="application/json")

It seems like there could be a one-line generic view to take care of this kind of thing.  Does such a view exist?
Edit: BTW, I'm comfortable with model forms, but the use case I'm looking at here is more narrow: RESTful AJAX calls that aren't based on standard forms (e.g. the user manipulates an object on the page, and a REST call is sent to notify the server.).

A: have you looked at model forms?

A: There is nothing about forms that requires you to actually draw a form.  ModelForms are the right thing to use if you're not going to go with piston or tastypie or something like that.
Put this in your page:
https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax
class ObjectAjaxForm(forms.ModelForm):
  class Meta:
     model = Object
     fields = ("field1", "field2", "field3", "field4")

#or, if you don't want the "free" csrf protection
#@csrf_exempt
def ajax_store_object(request):
    #request.POST can be substituted with any dictionary/dictionary like object
    form = ObjectAjaxForm(request.POST)
    if form.is_valid():
      form.save()
      return HttpResponse(json.dumps({"status":"Success"}), mimetype="application/json")
    else:
      return HttpResponse(json.dumps({"status":"Failed"}), mimetype="application/json")

A: As far as I know, there is no generic Ajax view, but perhaps you are looking for this?
Object(**request.POST).create()

Of course, you need to make sure request.POST doesn't contain anything you don't want to put in the model (like a "submit" field).


text:
Q: Error with flush, try catch and object It is throwing an error

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'complete' cannot be null

How do I "tell" the Entity Manager not to consider the fruit object since it is throwing an error?
I have an object like:
class Fruit {
    /**
     * @Id @Column(type="integer")
     * @GeneratedValue(strategy="AUTO")
     */
    private $id;
    /** @Column(type="string", length=10, nullable=true) */
    private $name;

    /** @Column(type="boolean") */
    private $complete;

    /* Omitted to make it simple */
}

And a method like:
public function uploadAction(){
    try{
       /* Omitted to make it simple */
       while ($data = fgetcsv($fic, 1024, $delimiter)) {
           try {
               $fruit = $fruitManager->createFruit($data);
               $outcome_fruit = $fruit->id;
           } catch (\Exception $e) {
               $outcome_details[] = $e->getMessage();
           }
       }

       fclose($fic);
       @unlink($file_path);

       $csv_data = $this->view->io->build_csv_file($outcome_details);
       $csv_import->output_csv = base64_encode(gzencode($csv_data));
       $this->em->persist($csv_import);

       // error here
       $this->em->flush();
       //

    } catch (\Exception $e) {
       print $e->getMessage();
       exit;
    }
}

My fruitManager
class FruitManager{
   public function createFruit($name){
      $fruit = new \Entities\Fruit;
      $fruit->name = $name;

      throw new Exception("Exception.");

      $fruit->complete = 1;
      $this->em->persist($fruit);
      $this->em->flush();
   }
}

A: You have few options:

*

*update your entity allowing null values using ORM to allow null values for this field ie /** @Column(type="boolean", nullable=true) */

*update your entity with default value using ORM ie /** @ORM\Column(type="boolean", nullable=false, options={"default" : false}) */

*assign default value in the entity constructor

*assign default value using private $complete = false; like Freelancer said

I'd prefer one of the first 2 options depending on logic needs.
Thanks.

A: try by setting  private $complete = false; or true as you want.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pressing enter in modal closes the modal but does not submit the data I'm using asp.net webforms, and bootstrap 3
The problem I'm having is when pressing enter, having the password field focused dismisses the modal, but no data is submitted.
Seeing others had a similar problem but different elements in their modal, I for an example have asp:button in my code while others who could make it work had input type="submit" instead.

                        ×

You are about to review document:
                            <asp:Label ID="lblReviewSignDocName" runat="server" Text=""></asp:Label>
                            <asp:Label ID="lblReviewSignDocNr" runat="server" Text=""></asp:Label>

Enter credentials and press "Ok" to review

                                    Username:

                                        <asp:TextBox ID="txtUserForReview" Class="form-control" Placeholder="Login Credentials" runat="server"></asp:TextBox>

                                    Password:

                                        <asp:TextBox ID="txtPasswordForReview" Class="form-control" Placeholder="Password" TextMode="Password" runat="server"></asp:TextBox>

                            <asp:Label ID="LNoteReviewSign" ForeColor="Red" runat="server"></asp:Label>

                        <asp:Button runat="server" CssClass="btn btn-primary" Text="Ok" ID="btnReviewSign" OnClick="btnReviewSign_Click" />
                        Cancel

What is expected is that pressing enter while the password field is focused would have the same effect as pressing the sign button. the other input field is set to readonly from the code behind so it can't be focused.
alternatively if submitting by pressing enter can't be achieved I would prefer nothing happening when pressing enter.

A: As suggested by @AlexKudryashev suggested, wrapping all inputs and buttons in an asp:Panel and setting DefaultButton="btnReviewSign" solved this issue.
keep in mind this will only solve this problem if you're coding your website in .net webforms.


text:
Q: How to kill windows zombie tcp connections? I'm running beyondtv link on xp, connecting to beyondtv a vista host. The Link program hangs after about 20 min, and I have no fix for this. When this happens, using tcpview, I see that the host has about 200 zombie tcp connections left over from the Link connection. I can't clear them, they are from the same non-existent process. The connections hang around until I reboot the host. Rebooting is the only way I have found to reconnect beyondtv Link. I think there is a bug in beyondtv that is causing this, but I can't get any answers on their forums. But at any rate, I would like to know if there is a way to kill all those connections.
Edit: it's actually about 3000 WAIT_CLOSE connections accumulating after about 40 min, and about then the client dies. If I close the server app, all these sockets now show as owned by a -non-existent- process in tcpview. Understandable. But isn't there a way to close them without re-booting?

A: CLOSE_WAIT means that the connection was closed on the other end.
Evidently, beyondtv doesn't detect this condition and continues to send data to the application on the other end. The other end can't send anything back over this connection, since
it has closed its end of the connection.
The solution is to set the TcpTimedWaitDelay entry in

HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\tcpip\Parameters
This entry determines the time that
  must elapse before TCP can release a
  closed connection and reuse its
  resources. This interval between
  closure and release is known as the
  TIME_WAIT state or 2MSL state. During
  this time, the connection can be
  reopened at much less cost to the
  client and server than establishing a
  new connection.

By default on my machine, this contains the value of -1, which I take to mean that closed connections are never released, which is exactly the behavior that you're observing.
I suggest that you set the value of this entry in the allowed range of 30–300 seconds. I suppose that 300 seconds = 5 minutes is entirely sufficient for your case, where it takes 40 minutes to freeze out your computer.

A: You can use Nirsoft's Currports to monitor and kill connections.
You can automate killing of a connection pattern using AutoHotKey.

A: You may be able to force Windows to force-close all TCP connections by 1) disabling, then 2) re-enabling your network interface.  If that works, you can batch-script the steps to execute when needed.
I've poked around for some way to do this via commandline, from the netsh utility (or similar), but I've had no luck so far.
Of course, the best way to fix this is to fix the broken application.  Make sure you're trying the latest version of the application; keep bugging the developers; if you're at the latest version already, try locating an older version of the program.

A: You are probably getting these CLOSE_WAIT sessions because of the program hanging -- I can't tell if you suspect them as the cause, so just wanted to make that clear.
My guess is that they won't hang around forever; probably only for 2 hours and 5 seconds.  Can seem like forever, I know.  You can try tuning the KeepAliveTime (probably requires one final reboot) for your network connection down to something small, like 5 minutes.  That might help them to disappear faster, after your program hangs.
Or if you know you can run the program reliably for, say, 10 minutes at a time, you could just restart it periodically.  Don't know if any of those solutions are useful for your particular situation; I agree with ~quack that you should ditch the problematic app version as soon as possible.

A: See if beyondtv is spawning another process that is holding the connections open. Process Explorer will show you if this is happening.

A: Is it possible that there is a firewall issue? It might be an incomplete connection being tried and retried.
I would disable all firewalls on both machines, and if there's a router also its internal firewall.

A: Try WinSock XP fix.
http://www.snapfiles.com/get/winsockxpfix.html
It trashes your connection and resets it back to default. I always keep this on a thumb drive when all else fails.


text:
Q: How to organize CSS,JS and other files into ASP MVC 4 I am totally new to ASP.NET MVC 4 as I was developing into PHP (Laravel) and the way to organize things is usually something like a "public" folder which would then be separated into css, img, js, lib, and so on.... which is the way I prefer to organize my files...Trying to follow this into ASP MVC 4, and I found and read this question that is similar to what I want achieve.  organizing custom javascripts in asp.net mvc 4I did it the way they said and added my custom JS files and added them in the Bundle, it compile and also run fine but the problem I have is that inside the Solution Explorer all the files that I moved are showing with an exclamation mark and also my newly created folders (directly in file explorer, not doing it through VS) are not showing by default, they are for some reason hidden, which I can see with Show All Files. I made sure that they exist inside the Bundle but then my Solution Explorer does not get refreshed. I am trying to make a structure that looks the following:
Contents
    img
        ui-icons.png
    css
        bootstrap
            bootstrap.css
            bootstrap.min.css
Scripts
    lib
        bootstrap
            bootstrap.min.js
            bootstrap.js
        jquery
            jquery.js
            jquery.min.js
            jquery.ui.js
            jquery.ui.min.js
        modernizr
            modernizr.js
    custom
        mycustom.js
        mycustom2.js

I am not crazy about dumping everything inside the same folders (Content & Scripts), including my custom files in between some official libraries. I know using directly the File Explorer is probably not the best way to go, but then what would be the official way of configuring these... and actually does my structure make sense into ASP MVC4?

EDITMy question is more related to why after creating and moving the files like jquery and others into a Scripts/lib folder, my Solution Explorer is still showin these files under Scripts but with an exclamation marks as saying file not found (of course since I moved them). Why it doesn't reflect exactly what I see in File Explorer? Apart from editing the Bundles is there anything else I'm suppose to do so that my Solution Explorer is up to date with reality??? and why are my created folders not showing in Solution Explorer, why do I have to click on Show All Files to see them? The commmand Create New Folder is not even enable as an available command, that's why I have done these folders directly in File Explorer...but why?

A: Frankly, you can organize your MVC project however you see fit.  If there's anything close to an "official" way to organize your web files, it would be how the default Visual Studio MVC4 template organizes them:

*

*Content (CSS files and related image files)

*Images (general image files)

*Scripts (JavaScript files)

If you're more familiar with another sort of organization or are part of a team that would prefer another organization, then go for it.  (Though in that team scenario, make sure all the team members follow the same organization rules!).
Edit:
To alter the folder structure that the MVC template provides using the Solution Explorer, right-click on the folder in which you want to add a subfolder (this includes the project name, for project-level folders), and then select Add and then Add Folder from the pop-up menu that appears.
If you want to move around files that are already in your solution to another location within the solution, you should move them around using the Solution Explorer, not Windows Explorer, as you'll otherwise get the behavior you are experiencing, where Visual Studio does not know where you moved them.  You can click and drag files around, right-click and copy and paste, etc.
If you need to add pre-existing files to your solution (say, to include a set of custom scripts), you can copy the files to the appropriate project folder using Windows Explorer.  Then, in Visual Studio, highlight the project that corresponds to where you moved them, and press the Show All Files button in the Solution Explorer toolbar - this will show the files you copied in Windows Explorer, which otherwise won't be listed in Solution Explorer tab.  Lastly, highlight the new files, right-click, and select the Include in Project option from the pop-up menu.
One final pointer: if you need to add a specific JavaScript library to your project, the easiest way to do so would be to use the NuGet package manager, rather than to download and add the files in Windows Explorer.  This option is found in Visual Studio in the Tools menu, under Library Project Manager --> Manage NuGet Packages for Solution.  Not all JavaScript libraries will be available this way, but the most popular ones are.


text:
Q: Why do we need IIS Express? Today I notice my team having to apply a registry patch to switch to IIS Express x64 so that ImageMagikc would work.
The patch is executed via a .bat file as below.
My question is why do we need to use IIS Express while IIS is already available in Windows 7/8?
p.s.
How would we find the similar name for IIS Express for Apache web server?
reg add HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\12.0\WebProjects /v Use64BitIISExpress /t REG_DWORD /d 1

A: IIS Express runs as a normal program under your own user account and so no special privileges are required to debug when using it. IIS runs as a service under a separate account and admin (or admin-like) permissions are required to debug with it.
As part of the "encourage everyone not to run everything as admin 100% of the time" effort, it makes sense to have the former available.


text:
Q: Do I need to standardize or normalize my data? I have the results of EPL season football stats with around 300 matches played.
Some data is the averaged results of past matches and some are different types of data such as odds.
It looks something like this (there are a lot more columns but this gives the idea):

Team
Odds
Win %
Goal Avg
Concede Avg
Last 6 Goal Av
Last 3 Goal Av
Strength

Arsenal
1.20
78
2.5
0.5
2.1
1.9
??

Liverpool
7.50
23
0.9
1.8
1.7
1.9
??

Man. City
4.10
60
1.1
1.2
1.5
1.6
??

The Strength column in each row will simply add the rows results together and divide by the total number of columns. (I plan on simply making the odds a negative number). The Strength basically just needs to be the sum of numbers in that particular row, divided by the amount of numbers. So basically 1.2 + 2.5 + 1.1 / 3 (as an example).
The question though is regarding how I normalise the data 'types', specifically the averages.
When normalizing averages, do I use the min/max of the averaged data or do I use the actual min/max values.
I've done some reading but it is going well over my head - I'm a web developer not a mathematician :)
And any type of pseudo code would be extremely helpful.
Thanks


text:
Q: Numeric.AD and typing problem I'm trying to work with Numeric.AD and a custom Expr type. I wish to calculate
the symbolic gradient of user inputted expression.  The first trial with a constant
expression works nicely:
calcGrad0 :: [Expr Double]
calcGrad0 = grad df vars
  where
   df [x,y] = eval (env [x,y]) (EVar "x"*EVar "y")
   env vs = zip varNames vs
   varNames = ["x","y"]
   vars = map EVar varNames

This works:
>calcGrad0
[Const 0.0 :+ (Const 0.0 :+ (EVar "y" :* Const 1.0)),Const 0.0 :+ (Const 0.0 :+ (EVar "x" :* Const 1.0))]

However, if I pull the expression out as a parameter:
calcGrad1 :: [Expr Double]
calcGrad1 = calcGrad1' (EVar "x"*EVar "y")
calcGrad1' e = grad df vars
  where
   df [x,y] = eval (env [x,y]) e
   env vs = zip varNames vs
   varNames = ["x","y"]
   vars = map EVar varNames

I get
Could not deduce (a ~ AD s (Expr a1))
from the context (Num a1, Floating a)
  bound by the inferred type of
           calcGrad1' :: (Num a1, Floating a) => Expr a -> [Expr a1]
  at Symbolics.hs:(60,1)-(65,29)
or from (Mode s)
  bound by a type expected by the context:
             Mode s => [AD s (Expr a1)] -> AD s (Expr a1)
  at Symbolics.hs:60:16-27
  `a' is a rigid type variable bound by
      the inferred type of
      calcGrad1' :: (Num a1, Floating a) => Expr a -> [Expr a1]
      at Symbolics.hs:60:1
Expected type: [AD s (Expr a1)] -> AD s (Expr a1)
  Actual type: [a] -> a
In the first argument of `grad', namely `df'
In the expression: grad df vars

How do I get ghc to accept this?

A: My guess is you are forgetting to apply lift to convert an Expr to an AD s Expr.
If you are interested in using the ad package for symbolic differentiation. Lennart Augustsson's traced package works well.

A: When GHC cannot deduce a type equality signature for a valid function, as in your case, the solution is to give the function a type signature.  I do not know the interface to this library.  However, my guess is that the correct signature is calcGrad1 :: (Num a, Floating a) => Expr a -> [Expr a].


text:
Q: System.AsyncException: The Apex job named "Name of the Job" is already scheduled for execution I have batch class and a scheduler as follows ,I am facing following error while executing Test Class.

System.AsyncException: The Apex job named "Name of the Job" is
  already scheduled for execution.

Batch Class:
global class BatchUpdateLegalEntityQ1 implements Database.Batchable<sObject> {
String query;
global BatchUpdateLegalEntityQ1() {
query = 'SELECT Id,Financial_Quarter__c,Legal_Entity__c From Legal_Entity_Contact__c ' +
'WHERE (CSAT_Respondent__c = \'Yes\') ' + 'AND (Financial_Quarter__c != \'Q1\') ' + 'LIMIT 400';
}

//Start the batch
global Database.QueryLocator start(Database.BatchableContext BC) {
return Database.getQueryLocator(query);
}

//Execute the batch
global void execute(Database.BatchableContext BC, List<Legal_Entity_Contact__c> lecList) {
System.debug('*****lecList '+lecList);

for(integer i=0;i<lecList.size();i++) {
lecList[i].Financial_Quarter__c = 'Q1';
lecList[i].Feedback_Request_Type__c = 'Automatic';
}
if(lecList.size()>0) {
update lecList;
}
}

//Finish the batch
global void finish(Database.BatchableContext BC) {
List<Legal_Entity_Contact__c> legalEntityId =  new List<Legal_Entity_Contact__c>();
legalEntityId = [SELECT Id From Legal_Entity_Contact__c WHERE CSAT_Respondent__c = 'Yes' AND Financial_Quarter__c != 'Q1' LIMIT 1];

if (!legalEntityId.isEmpty()) {
//CAST mails will be triggered for Q1 quarter via Schedular
Integer daynow = system.now().day()+1;
String myString = String.valueOf(date.today()+1);
String day = string.valueOf(daynow);
String month = string.valueOf(system.now().month());
String year = string.valueOf(system.now().year());
String strSchedule = '0 15 00'+ ' ' + day + ' ' + month + ' ?' + ' ' + year;
System.schedule('CSAT for Q1_' + myString, strSchedule, new ScheduleBatchUpdateLegalEntityQ1());

} else {
//New Apex schedular will be scheduled for Q1 quarter of next year
Integer yearNow = system.now().year()+1;
String year = string.valueOf(yearNow);
String strSchedule = '0 15 00 10 02 ? ' + year;
System.schedule('CSAT for Q1_' + year, strSchedule, new ScheduleBatchUpdateLegalEntityQ1());
System.debug('*****strSchedule ' + strSchedule);

}
}
}

Test Class:
@isTest
public class TestBatchUpdateLegalEntityQ1{
    static testMethod void BatchUpdateLegalEntityQ1(){

        Account oppaccount = new Account(Name = 'Account');
        oppaccount.Customer_Type__c = 'Carriers';
        System.debug(Schema.SObjectType.Account.getRecordTypeInfosByName().get('Customer - Verified').getRecordTypeId());
        oppaccount.RecordTypeId =  Schema.SObjectType.Account.getRecordTypeInfosByName().get('Customer - Verified').getRecordTypeId();
        oppaccount.Industry ='Agriculture';
        insert oppaccount;

        Legal_Entity__c legent = new Legal_Entity__c();
        system.debug('The Chosen Id is ' + oppaccount.Id);
        legent.Account__c = oppaccount.Id;
        legent.Name = 'test';
        legent.Credit_Rating__c = 'Green';
        legent.Industry__c = 'Education';
        legent.Sub_Industry__c = 'Board/University';
        legent.Registered_Address_Country__c='United Kingdom';
        legent.Website_address__c = 'test1';
        legent.Registration_Number__c = '12233445';
        legent.Registered_Address_Zip_Postal_Code__c='411028';
        legent.Legal_Entity_Owner__c = UserInfo.getUserId();
        legent.PO_Required__c='No';
        insert legent;

        Contact c = new Contact();
        c.FirstName='Contact';
        c.LastName='Test Contact';
        c.AccountId=oppaccount.Id;
        c.CSAT_Respondent_Type__c='Account Manager';
        c.Q_CSAT_Respondent__c = 'Yes';
        c.Role__c='Employee';
        c.Email='abc@gmail.com';
        c.Legal_Entity__c = legent.Id;
        insert c;

        Legal_Entity_Contact__c lec = new Legal_Entity_Contact__c();
        lec.Legal_Entity__c=legent.id;
        lec.Contact__c = c.Id;
        lec.Financial_Quarter__c ='Q2';
        insert lec;

        Test.startTest();
        Database.executeBatch(new BatchUpdateLegalEntityQ1());
        ScheduleBatchUpdateLegalEntityQ1 schUpdateLegal1 = new ScheduleBatchUpdateLegalEntityQ1();
        String sch = '0 0 23 * * ?';
        system.schedule('schUpdateLegalone', sch, schUpdateLegal1);
        Test.stopTest();
    }
}

A: If you have the scheduled class already running in the real system, that clashes with the one you are trying to run from your test. An example of where test-isolation is a bit leaky in SF.
In general, it's worth sticking the current time in milliseconds on the end of your scheduled job names. That solves this problem and also another problem where sandboxes don't always start their scheduled jobs properly. On the sandbox, you can end up with the scheduled job not running but still existing, so stopping you from manually restarting it.
System.schedule('CSAT for Q1_' + myString + '-' + System.currentTimeMillis(), strSchedule, new ScheduleBatchUpdateLegalEntityQ1());

You'll notice various managed packages (e.g. the Pardot connector) doing the same thing.

A: Aidan's answer solves the problem, but in my case I had a single job running every 2 hours. For that we can change the name for test execution:
String jobName = 'Job name';
// changing job name from test execution as same job is running in salesforce
if(Test.isRunningTest()) {
    jobName += ' - from test';
}
System.schedule(jobName, '0 0 0/2 1/1 * ? *', new ScheduleClass());

A: You can try run schedule in other test method.


text:
Q: I attempted to install cuda drivers, and now almost everything is broken I tried to install CUDA tookit 5.0 on ubuntu 12.04 and the installation proceeded OK.
After rebooting however, all I get is a terminal login. I've attempted to start the display manager with sudo start lightdm and it says all OK, but just hangs the prompt when it finishes loading without ever starting any display manager. sudo start gdm just flickers and goes back to the prompt.
There is no network connection on the machine either. It usually connects to a wireless network with remembered credentials.
What can I do to recover the machine?


text:
Q: Parse.com, Javascript, Tables I have a javascript table that is displaying data that is store in a parse.com server, i also have a iOS App that is also getting the same data from the same place on the iOS App it is every for row that has been selected in the table to store the object id in an NSString to be used in other like adding it a favourite column etc however on the javascript side i have not been very successful at this can one help?
iOS
    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{[tableView deselectRowAtIndexPath:indexPath animated:YES];
    PFObject *tempObject = [HomeArray objectAtIndex:indexPath.row];
    NSLog(@"%@", tempObject.objectId);
    _NameOfGame.text = [tempObject objectForKey:@"NameGame"];
    _Items.text = [tempObject objectForKey:@"item"];
    _Des.text = [tempObject objectForKey:@"des"];
    userFirstname = [tempObject objectForKey:@"FirstName"];
    group = [tempObject objectForKey:@"group"];
    device = [tempObject objectForKey:@"Device"];
    together = [NSString stringWithFormat:@"Uploaded by %@ from %@ on a %@", userFirstname, group, device];
    PFFile *video = [tempObject objectForKey:@"Video"];
    _videoUrl = video.url;
    NSLog(@"got a video %@", _videoUrl);
    _deleteObjectID = [HomeArray objectAtIndex:indexPath.row];
    NSLog(@"%@", _deleteObjectID);
    [self animateDetailView];}

Javascript
    var GameScore = Parse.Object.extend("games");
var query = new Parse.Query(GameScore);
query.equalTo("group", strUser)
query.find(
{
    success: function(results)
    {
        for (var i = 0; i < results.length; i++)
        {
            var object = results[i];

            (function($) {
                $("#first-team-results-table").append("
"
                +"<input type='checkbox' data-id='" + object.id + "'/>" $(checkBox).appendTo("#modifiersDiv")
                + "	"
                    + object.get("NameGame")
                    + "	"
                    + object.get("item")
                    + "	"
                    + object.get("des")
                    + "
");
            })(jQuery);
       }
    error: function(error) {
        alert("Error: " + error.code + " " + error.message);
    }
})
});

I have try with checkboxes in javascript but no luck

A: In which way aren't you successful? What doesn't work?
Do you get the correct result at all? If not change this line
query.equalTo("group", strUser) && query.equalTo("month", res);

to
query.equalTo("group", strUser);
query.equalTo("month", res);

------------------------------------ EDIT -------------------------
I would rewrite it like this:
var GameScore = Parse.Object.extend("games"),
    query = new Parse.Query(GameScore),
    $table = $("#first-team-results-table"),
    tableString;

appendToTable = function (object) {
    tableString = "
<input type='checkbox' data-id='"+object.id+"'	"+object.get("NameGame")+"	"+object.get("item")+"	"+object.get("des")+"
";
    $table.append(tableString);
    $(checkBox).appendTo("#modifiersDiv"); // I don't know what the checkbox-variable represents... anyway use this line to do something with it ;)
};

query.equalTo("group", strUser)
query.find({
    success: function(results){
        var object;
        for (var i = results.length - 1; i >= 0; i--) {
            object = results[i];
            appendToTable(object);
        };
    },
    error: function (error) {
        alert("Error: " + error.code + " " + error.message);
    }
});

I'm not sure what you are doing here
$(checkBox).appendTo("#modifiersDiv")

but I hope it gets you in the right direction...
------------------------------------ EDIT -------------------------
okay retry, still not sure if I get what you're trying to do. The following will first display the table after fetching stuff from Parse.com and putting it to the #objectBox-div when clicking the 'more'-button
HTML

 <input type="submit" id="uploadPaid" value="More"/><input type="text" id="gotObject" class="textFields"/>

JS
(function() {
    var GameScore = Parse.Object.extend("games"),
        query = new Parse.Query(GameScore),
        $table = $("#first-team-results-table"),
        $objectBox = $('#objectBox'),
        tableString,
        divString,
        ParseGames;

    appendToTable = function (object) {
        tableString = "
<input class='check' type='checkbox' data-id='"+object.id+"'	"+object.get('NameGame')+"	"+object.get('item')+"	"+object.get('des')+"
";
        $table.prepend(tableString);
    };
    appendToDiv = function (object) {
        divString = "
"+object.get('NameGame')+" "+object.get('item')+" "+object.get('des')+"
";
        $objectBox.append(divString);
    };

    query.equalTo("group", strUser)
    query.find({
        success: function(results){
            ParseGames = results;
            for (var i = results.length - 1; i >= 0; i--) {
                appendToTable(results[i]);
            };
        },
        error: function (error) {
            alert("Error: " + error.code + " " + error.message);
        }
    });

    $("#uploadPaid").on('click', function (e) {
        e.preventDefault();
        $objectBox.html('');
        $('.check').each(function(index) {
            console.log($(this).is(':checked'));
            if ($(this).is(':checked')) {
                appendToDiv(ParseGames[index]);
            };
        });
    });
})();

good luck ;)

A: After a couple of days look through website and trying lots of code i have finally got an answer to my question.

        <col width="80">
        <col width="80">
        <col width="5">
        <col width="300">
        <col width="100">

                Name Of Game
                Item
                Video
                Description
                Group

    <input type="button" class="btnGetAll" value="More"/>
    <input type="text" id="gotObject" class="textFields"/>


text:
Q: Conditional Formatting based on sum of the 6 cells below I was Hoping to be fever along before i had to ask for help but.
using Google sheets i am trying to have a range of cells(a row specificity) change there background colour based on the Sum of the 6 cells directly below it in the
I know I am happy using the basic conditional forming and i have a formula witch will return true if the Sum = what i am looking for
=IF(SUM(D6:D11)=6,true,FALSE())

and this works if i copy and past it along but if i try to put it in the Custom formula is box i get told

There was a problem while
Cannot save the rule with invalid formula.
so i take it that i am not using the box right

any help would be greatly appreciated

A: Conditional formatting is ... conditional. There is not normally any need for IF(). Your formula should work as:
=Sum(D6:D11)=6

but over what range and what cells to format (other then D5) I can't help you, if required, without further details.
Please though do read the [google-spreadsheet] tag wiki.


text:
Q: IE 8: JS call to new Image() fails when the code is run in a popup window I've run into a strange Internet Explorer 8 issue.
I have the following Javascript:
var img = new Image();
img.src = "http://something.com/images/something.gif";

It works just fine when I'm running it in its own window but when it's run in a pop up window it fails saying 'Image is not defined'. This only happens in Internet Explorer. I'm curious to know if anyone has encountered this and how I might work around it.
Thanks!

A: If you don't get it working, you can resort to creating the img tag with createElement instead.
var img = document.createElement("img");
img.src = "http://something.com/images/something.gif";


text:
Q: differentiability and continuity I have a question which is quite "candid" and for which I can hardly formalize properly every concepts but nonetheless, I was wondering if there were some topoligical and/or algebraic structure properties over spaces (to be defined) that make the set of continuous functions and the set of differentiable functions the same.
Maybe this is simply impossible or only for trivial examples.
Best regards
PS : Motivation is simple curiosity

A: I seem to recall that this works for p-adic-valued functions of a p-adic variable: they're differentiable if they're continuous.

A: Lie groups almost provide another example.
A continuous homomorphism between Lie groups is automatically smooth.  Of course, one needs to assume it's a homomorphism which is very strong condition (hence, the "almost" above).
The idea of the proof is in two big steps.  First one proves that any closed subgroup of a Lie group is automatically smooth (known as Cartan's theorem).  The idea of this proof is that one can identify what the tangent space to the identity should be using the group exponential map and show this tangent space is actually closed under addition using closedness.
The second step is a bit easier:  given $f:G\mapsto H$, consider the map $g:G\mapsto G\times H$ given by $g(x) = (x,f(x))$.  Using hypothesis on $f$, one proves that the image of $g$ is a closed subgroup, hence smooth by step 1.  This implies the two projection maps, when restricted to the image of $g$, are smooth.  With a bit more work, one shows $f$ can be written as a composition of projection maps and their inverses, so is smooth.


text:
Q: JButton Unwanted Text Size Change I have JButtons which I set the text on when they are required, on occasion the text changes size on the button, either larger or smaller. I have added examples below.

If I roll the mouse over the button the text returns to the set size. 2000 and 2013 are the set size.
The buttons are created and set as below:
//create buttons
 Buttons.add( Btn1 = newImageButton(Picture.Button.getImageIcon(), "Btn1", Color.WHITE));
 x = (int)(0.5f + (0) * getScreenWorking().width);
 y = (int)(0.5f + (yBtnStep + yBtnMargin) * getScreenWorking().height);
 buildConstraintsFF(Btn1, x, y, -1);

  Btn1.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent evt) {
        ButtonAction(evt);
     }
  });
  Btn1.setVisible(false);

 Buttons.add( Btn2 = newImageButton(Picture.Button.getImageIcon(), "Btn2", Color.WHITE));
 x = (int)(0.5f + (xBtnStep) * getScreenWorking().width);
 y = (int)(0.5f + (yBtnStep + yBtnMargin) * getScreenWorking().height);
 buildConstraintsFF(Btn2, x, y, -1);

  Btn2.addActionListener(new ActionListener() {
     public void actionPerformed(ActionEvent evt) {
        ButtonAction(evt);
     }
  });
  Btn2.setVisible(false);

   public JButton newImageButton(ImageIcon ii, String str, Color col) {
      JButton btn = new JButton(ii);
      Dimension dim = new Dimension(ii.getIconWidth(),
      ii.getIconHeight());
      btn.setPreferredSize(dim);
      btn.setMaximumSize(dim);
      btn.setMinimumSize(dim);
      btn.setText(str);
      btn.setForeground(col);
      btn.setHorizontalTextPosition(SwingConstants.CENTER);
      btn.setFont(new Font("GothamNarrow-Book", Font.BOLD, 24));

      btn.setBorderPainted(false);
      btn.setContentAreaFilled(false);
      btn.setFocusPainted(false);
      btn.setOpaque(false);
      return(btn);
   }

   //Button text set from list and made visible to size of list
   for(int i=0; i < List.size(); i++){
         btn1 = Buttons.get(i);
         setBtnText(List.get(i), i);
         btn1.setVisible(true);
    }

   //set button text
   public void setBtnText(String str, int i){
     JButton btn = autosButtons.get(i);
     String str2 = "" + str + "";
     btn.setText(str2);
     btn.setMargin(new Insets(20,0,20,0));
     btn.setVerticalAlignment(SwingConstants.CENTER);
     btn.setHorizontalAlignment(SwingConstants.CENTER);
     btn.repaint();
   }

   private JButton Btn1;
   private JButton Btn2;
   public ArrayList<JButton> Buttons = new ArrayList<JButton>();
   private List<String> List = new ArrayList<String>();

Can someone explain to me why the text is changing size as in the pictures?
Is it a text setting issue or a Swing issue?


text:
Q: Show product prices in Prestashop Wishlist Module Currently the wishlist module in my Prestashop store only displays the product image and title. There are two wishlist views, the customer account view and the shared link view. I would like to display the price in both of these views. I've tried adding
$price = Product::getPriceStatic($productid);

to different parts of managewishlist.php and adding
{convertPrice price=$productPrice}

to the managewishlist tpl file but nothing shows up. I'm running version 1.5.6.2.
EDIT: I also tried adding
{if !$priceDisplay || $priceDisplay == 2}
{assign var='productPrice' value=$product->getPrice(true, $smarty.const.NULL, $priceDisplayPrecision)}
{assign var='productPriceWithoutReduction' value=$product->getPriceWithoutReduct(false, $smarty.const.NULL)}
{elseif $priceDisplay == 1}
{assign var='productPrice' value=$product->getPrice(false, $smarty.const.NULL, $priceDisplayPrecision)}
{assign var='productPriceWithoutReduction' value=$product->getPriceWithoutReduct(true, $smarty.const.NULL)}
{/if}

to managewishlist.tpl but it made the wishlist disappear

A: Not sure about the actual files you need to edit but this should be right for PS 1.5.x
in blockwishlist/view.php add the commented line:
for ($i = 0; $i < sizeof($products); ++$i)
    {
        $obj = new Product($products[$i]['id_product'], false, $context->language->id);
        if (!Validate::isLoadedObject($obj))
            continue;
        else
        {
            if ($products[$i]['id_product_attribute'] != 0 && isset($combination_imgs[$products[$i]['id_product_attribute']][0]))
            {
                $combination_imgs = $obj->getCombinationImages($context->language->id);
                $products[$i]['cover'] = $obj->id.'-'.$combination_imgs[$products[$i]['id_product_attribute']][0]['id_image'];
            }
            else
            {
                $images = $obj->getImages($context->language->id);
                foreach ($images AS $k => $image)
                {
                    if ($image['cover'])
                    {
                        $products[$i]['cover'] = $obj->id.'-'.$image['id_image'];
                        break;
                    }
                }
                if (!isset($products[$i]['cover']))
                    $products[$i]['cover'] = $context->language->iso_code.'-default';
            }
            // ADD THIS LINE!
            $products[$i]['price'] = Product::getPriceStatic($obj->id);
        }
    }

then in view.tpl (not sure if PS 1.5.x uses the /templates/view/ dir or not try both) you can just use {convertPrice price=$product.price} wherever you need.
Haven't actually tested this but it should give you a good starting point at least.
EDIT Also please be aware that that editing module files directly is not recommended. However, since there is no option to override modules in PS 1.5.x your only options are:
a) editing module directly - meaning it will break if / when you update said module
b) copying the module and renaming it - which is messy but imho preferable to the downside of a)


text:
Q: Can I static_assert without providing a real template parameter? template<typename T>
class MyClass
{
......
private:
    union u_
    {
        struct m_
        {
            int i1;
            int i2;
            int i3;
        } m;
        char data[SIZE]; // convenience buffer for serialization/deserialization;
    } u;
    T container;
......
};

To be able to serialize / deserialize an object of MyClass, I use a union to combine my data fields and use the data buffer to do it wholesale. I want to make sure that data is big enough for the collection of data members in case someone expand them in the future, so I added this static assert.
static_assert(sizeof(MyClass<int>::u_::data) >= sizeof(MyClass<int>::u_::m_));

There are two problems with this approach. First, the compiler complains that the union is not public. Secondly this should hold true for any container type T, so I don't want to be specific, but giving int as a dummy type won't work, but I don't want to introduce another type just for the sake of static assert, is there a way to use a dummy type here?
Is there a more elegant solution?
EDIT: James, thanks for bringing up portability issues. Endianness and alignment are legit concerns, but in my case, serialization/deserialization happens locally, so it's OK.

A:
Is there a more elegant solution?

Why not just reinterpret the struct as an array of char?
struct m_
{
    int i1;
    int i2;
    int i3;
};

// ...
m_ m;
char* data = static_cast<char*>(static_cast<void*>(&m));

Any object can safely be reinterpreted as an array of char.  Of course, you still have to worry about alignment, padding, the sizes of your data types, and potential endianness and other representation issues, but presumably you know that since you're writing the serialization implementation.

A: char data[SIZE];

Instead of this, you can do this:
char data[sizeof(m_)];

It'll always satisfy the condition in this static_assert:
static_assert(sizeof(MyClass<int>::u_::data) >= sizeof(MyClass<int>::u_::m_));

Since it'll always satisfy, no matter what, you would not even need to write the static_assert!

A: To solve the private issue you can consider putting static_assert somewhere inside the class, like a constructor or a static method for example.


text:
Q: Write data in file using python I'm working on a python project and I want to write some data in a file text.txt but I have this error : UnboundLocalError: local variable 'data' referenced before assignment
This is my code :
from flask import Flask, request, jsonify

app = Flask(__name__)

@app.route('/', methods=['POST','GET'])
def createapp():
    if request.method == 'POST':
        data = request.json
        print(data)

    with open('text.txt', 'a') as file:
        file.write(data)

if __name__ =='__main__':
    app.run()

A: if request.method == 'POST':
    data = request.json
    print(data)

with open('text.txt', 'a') as file:
    file.write(data)

And what if request.method != 'POST'? You won't have defined data.

If you want to add something new (maybe a 0 or a []) when data is null, you may want to add this before the if statement:
data = ''

A: Set data to empty string before the condition. Otherwise it's undefined if the condition is false
data=''
if request.method == 'POST':
    data = request.json
    print(data)

with open('text.txt', 'a') as file:
    file.write(data)


text:
Q: Flex4.6 Add element to top of List I've got a spark list that gets dynamically filled.
So far the new items appear at the bottom of the list. What I'd like to do is to add them at the top.
The items in the list have a unique ID so some kind of sorting mechanism would probably do the trick as the new items have a greater ID than the old ones.
What I'd like to avoid is some complex method behind this as I'm working on a mobile platform and the list can get quite big so I need this to be as efficient as possible.
The list's data provider is an ArrayList that gets updated using binding.
How can that be done?
Thanks in advance!

A: u can Add the items at the starting index of the datagrid. Flex datagrid automatically renew all the indexes and add 1 to all existing element indexes. So
YourDataGridId.dataprovider.addItemAt(item,0) will do.


text:
Q: Is there a Python function that can filter and assign binary value to a column in the dataset based on a condition? Having issue filtering my result dataframe. I have a column in my dataset called PaymentAmount which has numerical data and want to perform an operation to assign a value of

*

*1 if data['PaymentAmount'] > 25000 and

*0 if data['PaymentAmount'] <= 25000
I tried using the below
1 if data['PaymentAmount'] >= 25000 else 0

but getting the following error:
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-176-e368653724d0> in <module>
----> 1 1 if data['PaymentAmount'] >= 25000 else 0

~\AppData\Local\Continuum\anaconda3\lib\site-packages\pandas\core\generic.py in __nonzero__(self)
   1574         raise ValueError("The truth value of a {0} is ambiguous. "
   1575                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
-> 1576                          .format(self.__class__.__name__))
   1577
   1578     __bool__ = __nonzero__

ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

A: Here is better use vectorized solutions - convert boolean mask to integer for True/False to 1/0 mapping:
data['new'] = (data['PaymentAmount'] > 25000).astype(int)

Or use numpy.where:
data['new'] = np.where(data['PaymentAmount'] > 25000, 1, 0)

Your solution should working with lambda function and apply, but it is slow, because loops under the hood:
data['new'] = data['PaymentAmount'].apply(lambda x: 1 if  x >= 25000 else 0)


text:
Q: How to use XPSDocument to open a XPS file that is contained in a WPF application as a binary resource? Basically I have embedded a xps file in a WPF application containing a XPSDocument Viewer as a resource.
On loading the application, I just want the document viewer to display that embedded resource.
public Page1()
{
  InitializeComponent();
  XpsDocument doc = new XpsDocument(SmartsysBrowser.Properties.Resources.test1, FileAccess.Read);
  docViewer.Document = doc.GetFixedDocumentSequence();
  docViewer.Focus();
}

however this command does not pass muster
  XpsDocument doc = new XpsDocument(SmartsysBrowser.Properties.Resources.test1, FileAccess.Read);

I do know that I need to type the filepath of the XPS document but since it is embedded as a resource, how to?
Thanks very much all.
Background:
I am supposed to make a application that will display a confidential document and since it is also important to restrict copies of it being made/printed/circulated, I have decided a ClickOnce WPF XBAP application is the way to go. My reasoning, all copies of a ClickOnce application can be rendered useless once I remove the application from the webserver. Furthermore, it seems to be the cheapest and most viable way to protect a confidential document. Please do feel free to suggest alternatives. I am always keen to learn from you all.

A: As you're using embedded resources (i.e. non-WPF resource), you could use Assembly.GetManifestResourceStream to get a Stream from your resource name, then use the static Package.Open to get a Package instance, then you can use the other XpsDocument constructor that accepts a Package as parameter.


text:
Q: Get byte array of image from gallery by imagepath in xamarin.forms currently I am saving image from camera in gallery and its path in sq lite table.
I need byte array of this saved image in during API call.
so can I get byte array of image by its name?
please help me to.

A: If you have the file path you should just be able to get it by File.ReadAllBytes(imagePath);.
However, this is not available in a generic matter within Xamarin.Forms. You will need to use the DependencyService for it.
It could look like this:
Define an interface in your shared code
public interface ILocalFileProvider
{
    byte[] GetFileBytes(string filePath);
}

Then implement it in the platform projects, like this
public class LocalFileProvider_iOS : ILocalFileProvider
{
    public byte[] GetFileBytes(string filePath)
    {
        return File.ReadAllBytes(filePath);
    }
}

It will look pretty much the same in Android, but of course you should handle errors, exceptions etc. Also don't forget to add the [assembly: Dependency(typeof(LocalFileProvider_iOS))] above the namespace.
You can now use it in your shared code like this: var bytes = DependencyService.Get<ILocalFileProvider>().GetFileBytes(file.Path);
Also, here it needs some finetuning.
What you are doing now is calling upon generic interface from your shared code. Runtime it is determined which implementation the interface gets and that way the platform specific code is implemented as the interface.


text:
Q: My Hard disk is crashed. How to find the win 8 key which was activated in my laptop? I had purchased  vaio VPC YA 17GG Laptop with win 7 pro. I have upgraded that 7 to win 8 with upgradation scheme. Now today my HDD crashed. I have changed the hard disk. But I don't know the windows 8 key. How to get it?

A: http://windows.microsoft.com/en-us/windows-8/upgrade-product-key-only

Have your product key handy. You can find it in your online order
  information, in the confirmation email for your purchase, or on the
  packaging.

A: You could connect the crashed drive to another computer and try copying over the config file located in C:\Windows\System32\config . After that you could use any one of the product key locators that are out there on the internet.


text:
Q: Getting "app.firestore is not a function" when getting data from Firestore in SSR app I have currently followed a video on youtube on SSR with firebase functions. And that seems to work perfect. Now i am trying to add some additional functionality to my ssr boilerplate app. I want to add Firebase firestore support so i can get data from firebase firestore. I am getting this error ERROR { Error: Uncaught (in promise): TypeError: app.firestore is not a function and this only happens in the function (server). Data is retrieved in the frontend but the SSR part is not working because of the function (server) error. I cant seem to find any solution for this. My code can be viewed here: Github_Repository
I cant see what i am missing here and hope posting this question will help.
thanks.

A: Use externalDependencies = [
"@firebase/app",
"@firebase/firestore"
] in angular.json file
Below is the code.
"server": {
      "builder": "@angular-devkit/build-angular:server",
      "options": {
        "outputPath": "dist/market-web/server",
        "main": "server.ts",
        "tsConfig": "tsconfig.server.json",
        "externalDependencies": [
          "@firebase/app",
          "@firebase/firestore"
        ]
      },
  .....


text:
Q: Is event sourcing an overkill for simple incremental form updates? I am working in a web app which implements backend in event sourcing. Event sourcing has given us great power to go back in time, run projections to get different types of reports. Also, we can potentially build our database from scratch by replaying the projections if we need to.
We have certain modules which do not give much analytical value by implementing event sourcing in it. For example, a questionnaire creation, which is nothing but a simple form CRUD. We have event sourcing in it, but the only advantage we potentially have from that is to rebuild the forms database from the stored domain events. Or to get values like how much time a user took to make the questionnaire etc.
But still those analytics do not give us much info because the state change in a form is not as valuable as other parts of the system. Like e.g. changing state of a bank account through domain events give us much more information as compared to a changing state of a form CRUD.
How do you guys approach such situations and know if a certain part of the app is good for event sourcing or if it is an overkill?

A: Whether or not it's overkill is a matter of opinion, but CRUD (or really CUD, since a read isn't a meaningful event) events (e.g. WidgetCreated, WidgetUpdated, WidgetDeleted; especially the WidgetUpdated) can be a sign of an anemic domain.
Assuming that each update is atomic in your DB, you can likely get the same results (a stream of events for other components to consume) by using change data capture (e.g. Debezium for many SQL DBs to put a change feed into a Kafka topic, or some DBs like Azure Cosmos offer a native change feed) to capture changes to records in the DB.
Event sourcing now with CRUD events does give you the flexibility to flesh out the domain model later if requirements change.  That requires a sense of how likely (and when...) the requirements are to change in a way that makes richer domain events handy vs. how much effort you're expending in event-sourcing now.


text:
Q: PredicateBuilder and n+1 query I use PredicateBuilder to pass a Dynamic Expression to a method in my repository that uses it within Where clause. Here is the relevant repository code:
        var results = context.Set<T>().AsExpandable.Where(where);

        foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
        {
            results = results.Include(includeProperty);
        }
        return results.ToList();

In my controller I have this:
var predicate = PredicateBuilder.True<Account>();
if (amount> 0)
    predicate = predicate.And(d => d.Amount <= amount);

var model = AccountRepository.Get(predicate, "Owner").ToList();
return PartialView(model);

When I make a reference to a property of "Owner" it makes another roundtrip to the database, causing an n+1 query problem. Is there any workaround to avoid this?

A: Do the includes before the AsExpandable like so:
var results = context.Set<T>()

foreach (var includeProperty in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
{
    results = results.Include(includeProperty);
}

return results.AsExpandable.Where(where).ToList();


text:
Q: Algorith to remove elements from array one by one based on index This is a simplification to the purest case of a problem in a embedded system with arbitrary limits that i cannot control
Let there be an array of anything, for example words:
["apple", "pear", "banana", "orange"]
Let there be an array of indexes (starting at one) to remove items from:
[1,3]
We need a function that returns the result of removing those indexes from the starting array, in this example the result should be:
["pear", "orange"]
as it removed indexes 1 and 3
However, the only accepted operation to achieve that is a function that removes one item by index from the array, and mutates it, for example:
We have the original array ["apple", "pear", "banana", "orange"]
We want to remove items [1,3]
We removeItem(1)
The result is ["pear", "banana", "orange"]
The next item we want to remove is the item at index 3 of the original array, which is "banana", however, the item at current index 3 is "orange", thus, the naive approach to remove items does not work, as it will result in removing "orange" instead, with a final result of:
["pear", "banana"] instead of ["pear", "orange"]

A: If the indices are sorted, then you simply need to decrease the index by one each time you remove an element:
for i = 1 .. len(indices)
    elements.removeItem(indices[i] - i + 1)

Alternatively, delete the items backwards. This is probably also more efficient depending on the implementation of the removal process:
for i = len(indices) .. 1
    elements.removeItem(indices[i])


text:
Q: Rails Devises Gem redirect on sign in redirect loop I'm having huge trouble trying to get Devise to redirect to the user's previous page after signing in.
I have tried to follow the guide on the Wiki but when I implement this code it suggests:
def after_sign_in_path_for(resource)
  sign_in_url = url_for(:action => 'new', :controller => 'sessions', :only_path => false, :protocol => 'http')
  if request.referer == sign_in_url
    super
  else
    request.referer || "/"
  end
end

It just always redirects to the root, and never to the previous page.
I've found previous questions with the same issue but the solutions in them have not worked.
I then thought I would simplify it and just return the user to the previous URL by getting just the path of the referal URL, as I thought that might help, however I get the same error with this:
def after_sign_in_path_for(resource)
  URI(request.referer).path
end

It does work if I simply put a static path in:
def after_sign_in_path_for(resource)
  "/somepath"
end

That works absolutely fine. I'm sure I am missing something obvious here!

A: Look at this answer: https://stackoverflow.com/a/3104799/1657142.
As explained in the link, request.referer returns the HTTP_REFERER value set in the HTTP header. This value might be missing.


text:
Q: Disabling tabbing for dom elements not within a modal and overlay I have a modal that pops up with tab-able elements. Is there something like jQuery's :focusable or pointer-events: none that would allow me use CSS to disallow focusing on items underneath the overlay?
edit: The problem with a JS based approach (and selectors), is that each rerender with React, the query selector would have to be run through again. I don't have control over the component rendering this modal.

A: You want to do something along the lines of:
const inputs = [...document.getElementsByTagName('input')];
inputs.forEach((input) => input.setAttribute('tabindex', '-1'));

const modalInputs = [...document.querySelectorAll('.my-modal input')];
modalInputs.forEach((input, index) => input.setAttribute('tabindex', index));

Full Example https://codepen.io/bradevans/pen/GGYxrg
Edit: I hadn't seen the reactjs tag until OP commented... I'd utilize the Modals componentDidMount lifecycle method to change the underlying DOM inputs tab indexes and change the modals at the same time or using internal state....
You may also want to store the old tab indexes and reapply them on componentWillUnmount();


text:
Q: How to EXTRAPOLATE missing data with R in panel data? In a Panel Data, I have some NA values that I would like to extrapolate at the end or start of my years of interest. Most solutions to similar questions deal with interpolation. Please note that this is not the case.
A similar sample of my data called "data" looks like this:
> data
   REGION YEAR  VALUE
1       A 2011     NA
2       A 2012     NA
3       A 2013     NA
4       A 2014  20.00
5       A 2015  25.00
6       A 2016  30.00
7       A 2017  35.00
8       A 2018  40.00
9       B 2011     NA
10      B 2012   0.30
11      B 2013   0.50
12      B 2014   0.70
13      B 2015   0.90
14      B 2016   0.11
15      B 2017   0.13
16      B 2018   0.15
17      C 2011 100.00
18      C 2012 101.00
19      C 2013 102.00
20      C 2014 103.00
21      C 2015 104.00
22      C 2016 105.00
23      C 2017 106.00
24      C 2018     NA

Some solutions that I found to similar questions:
I have try with na_interpolate but it just repeats the last values. I also tried with mutate combined with na.spline, but it creates values that are obviously wrong for a linear regression
I am sure that there must be a simple way to estimate these values.
The expected result should look like this:
> data
   REGION YEAR  VALUE
1       A 2011   5.00
2       A 2012  10.00
3       A 2013  15.00
4       A 2014  20.00
5       A 2015  25.00
6       A 2016  30.00
7       A 2017  35.00
8       A 2018  40.00
9       B 2011   0.10
10      B 2012   0.30
11      B 2013   0.50
12      B 2014   0.70
13      B 2015   0.90
14      B 2016   0.11
15      B 2017   0.13
16      B 2018   0.15
17      C 2011 100.00
18      C 2012 101.00
19      C 2013 102.00
20      C 2014 103.00
21      C 2015 104.00
22      C 2016 105.00
23      C 2017 106.00
24      C 2018 107.00

Thank you for your help

A: You can just do:
predictions <- round(predict(lm(VALUE ~ REGION * YEAR, df), newdata = df), 2)
predictions
#>      1      2      3      4      5      6      7      8      9     10
#>   5.00  10.00  15.00  20.00  25.00  30.00  35.00  40.00   0.65   0.59
#>     11     12     13     14     15     16     17     18     19     20
#>   0.53   0.46   0.40   0.34   0.27   0.21 100.00 101.00 102.00 103.00
#>     21     22     23     24
#> 104.00 105.00 106.00 107.00

df$VALUE[is.na(df$VALUE)] <- predictions[is.na(df$VALUE)]

Which gives the desired result:
df
#>    REGION YEAR  VALUE
#> 1       A 2011   5.00
#> 2       A 2012  10.00
#> 3       A 2013  15.00
#> 4       A 2014  20.00
#> 5       A 2015  25.00
#> 6       A 2016  30.00
#> 7       A 2017  35.00
#> 8       A 2018  40.00
#> 9       B 2011   0.65
#> 10      B 2012   0.30
#> 11      B 2013   0.50
#> 12      B 2014   0.70
#> 13      B 2015   0.90
#> 14      B 2016   0.11
#> 15      B 2017   0.13
#> 16      B 2018   0.15
#> 17      C 2011 100.00
#> 18      C 2012 101.00
#> 19      C 2013 102.00
#> 20      C 2014 103.00
#> 21      C 2015 104.00
#> 22      C 2016 105.00
#> 23      C 2017 106.00
#> 24      C 2018 107.00

A: For linear extrapolation, you can fit a linear model and then use predict.
data$VALUE[is.na(data$VALUE)] <- unlist(lapply(split(data, data$REGION),
FUN=function(x) predict(lm(VALUE~YEAR, data=x), newdata=subset(x, subset=is.na(VALUE)))))

And I think you made a typo for REGION B.

Data:
data <- structure(list(REGION = c("A", "A", "A", "A", "A", "A", "A",
"A", "B", "B", "B", "B", "B", "B", "B", "B", "C", "C", "C", "C",
"C", "C", "C", "C"), YEAR = c(2011L, 2012L, 2013L, 2014L, 2015L,
2016L, 2017L, 2018L, 2011L, 2012L, 2013L, 2014L, 2015L, 2016L,
2017L, 2018L, 2011L, 2012L, 2013L, 2014L, 2015L, 2016L, 2017L,
2018L), VALUE = c(NA, NA, NA,
20, 25, 30, 35, 40, NA, 0.3, 0.5, 0.7, 0.9, 1.1,
1.3, 1.5, 100, 101, 102, 103, 104, 105, 106, NA)), row.names = c("1",
"2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13",
"14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24"
), class = "data.frame")


text:
Q: What is the most idiomatic way to paginate through the results of a search performed using zend_form I've implemented an action + view that lists all the rows in a database and allows you to paginate through them using zend_paginator. I've also written an action + view that takes a form post (or get), constructs a Solr query and returns a zend_paginator adapter to page through the results.
The problem I've got is working out how to paginate through my query after the postback, it's a relatively complex search form (8 fields to search on).
The options as far as I can see are:

*

*Move the parameters that are posted
to a new url and redirect

*Write my
own paginator that preserve query
string parameters

*Serialize the
results of the form post into a
session and get it from there when
paginating

Which of these is the most zend/php way of doing it - and, more importantly, quickest to implement?
HELP!!!!!
Thanks.

A: I'm not going to accept this answer until I'm convince no one has a better one but I've come to a decision. I've gone for the PRG pattern (post-redirect-get).
    if ($request->isPost()) {
        if ($form->isValid($request->getPost())) {
            return $this->_helper->redirector('index','contact',NULL,array_filter($form->getValues()));
        }
    }

This redirects to a url with the contents of the form as parameters - www.url.com/form/param1/val/param2/val
The array_filter command strips all empty parameters and this means you end up with a nice clean, bookmarkable, seo friendly url that the zend_paginator works with out the box.


text:
Q: Cyclops Visor Material and beam color This question has several parts, so it may need to be split into a few questions. I know that Cyclops visor aperture is made of a mixture of powdered ruby-quartz.   Has he ever tried using a different material for the visor, and if so did (or would) that change the color and EM wavelength of his optic blasts?

A: Cyclop's optic blast is not electromagnetic energy so its signature color has never changed. Nothing is known about the dimension from which the red kinetic energy is released. It is the same color even when he does not wear his visor.

*

*Ruby quartz crystals resonate at the same frequency as the psionic field that protects both Cyclops and Havok from their own powers.

*The beam is a kinetic energy coming from an other-dimensional aperture focused over his eyes. A traumatic brain injury prevents him from controlling the aperture so he needs the visor to compensate.

*As to whether other materials are more or less effective, I suspect Professor X tried many things before settling down with the ruby quartz he uses today. Unfortunately for Cyclops, ruby quartz is rather rare, so it is fortunate he does not need much. On Marvel Earth-616 there is sufficient supply for it to be used in a variety of technologies used by agencies such as SHIELD.

*While ruby quartz was selected, there is little reason another variety of quartz could not function in a similar fashion since the difference in coloration is merely the addition of trace elements within the quartz crystals.


text:
Q: Preventing notification sounds from interfering with sound app I'm making a synth kind of app for the iPad. Problem is - whenever I'm playing and someone messages me, the sound lowers the synth app's sound. It is kind of disruptive.
How do I prevent this? Maybe you can see the notifications but the sounds doesn't automatically lower the volume in the synth.
I can't imagine performing with my app and getting it interrupted by all the iMessages!
Thanks.

A: I don't believe there's any way to control that stuff.  It's part of iOS and no app is allowed to interfere with it.  Perhaps in a later version of iOS, they allow an app to grab exclusive access to the sound output, and it'll bring up a warning like "SynthApp would like full control of sound.  Allow or Disallow?"  But for now, there's nothing like that...
I'd recommend telling people in the documentation to turn off those sounds in the Settings app if they're using it in a live setting or whatever.  Also, if your app supports recording the sounds that it generates, the other sounds shouldn't interfere with that, as your recording algorithm wouldn't have access to the final mixed product anyway, it would only see the sounds that your app specifically is generating.


text:
Q: Rails - Editing item from list by bootstrap modal I'm new in Rails. I try to make a list of groups (/groups) where I want to have edit and delete option in each row. Editing should be implemented by modal because Group has only one attribute - name. So I don't want to open /groups/number/edit.
My problem is: I don't know how to bind chosen group with form_for. Maybe it isn't good approach indeed.
Modal is displayed, but the name field is blank. When I used debug for @group is blank too. I don't know why.
Here is my code(single group row):
<li id="group-<%= group.id %>" class="list-group-item">
<%= group.name %>

<%= link_to edit_group_path(group.id), "data-toggle" => "modal", "data-target" => "#myModal", :class => "edit-option btn" do %>

<% end %>
<%= link_to group, method: :delete, data: { confirm: "Na pewno chcesz usunąć tę grupę?" }, :class => "delete-option btn btn-danger" do %>
     usuń
<% end %>

                <button type="button" class="close" data-dismiss="modal" aria-label="Close">×</button>

Zmień nazwę grupy

            <%= form_for(@group) do |f| %>

                    <%= debug @group %>

                        <%= f.label :name, "Nazwa" %>
                        <%= f.text_field :name, class: 'form-control'%>

                    <button type="button" class="btn btn-default" data-dismiss="modal">Anuluj</button>
                    <%= f.submit "Zapisz zmiany", class: "btn btn-primary" %>

            <% end %>

Controller
def edit
@group = current_user.groups.find_by(id: params[:id])
end

def update
 @group = current_user.groups.find_by(id: params[:id])
 if @group.update_attributes(group_params)
   flash[:success] = "Nazwa grupy została zmieniona"
   redirect_to groups_path
 else
   redirect_to groups_path
 end
end

A: I will assume that the answer to my question above is a yes, and so, I'll just continue to answer.
First thing: You don't want to be repeating different Modals for each group, you want only a single Modal to be used by all the groups.
Second thing: You are very correct with the idea of wanting to send the group.id to the edit method in your controller, for it to return that group back into your Modal
However, what is wrong is how you are trying to achieve this.
<%= link_to edit_group_path(group.id), "data-toggle" => "modal", "data-target" => "#myModal", :class => "edit-option btn" do %>

You are telling your link to do two things when clicked: (1) go to edit path (2) open modal. Which one will take more importance? Right now, it is the modal that is opening, and not the edit path working, which means that you are not getting to the controller at all, so accounting for why your @group is blank.
To achieve this, you will have to tell your link to do only one thing, and when that is successful, do the other.
What I'll advice is to use Ajax (by setting remote: true) on your link to go to the controller, and then open the modal on response.
Here is a breakdown of the steps:
1.Set remote: true to make the call with Ajax
<%= link_to edit_group_path(group.id), remote: true %>

2.Tell controller action (in this case, the edit action) to respond to js
def edit
  @group = current_user.groups.find_by(id: params[:id])
  format.js
end

*Prepare an edit.js.erb file to handle the response (this will be in the same directory which your other view files are)

*Populate the form with the @group from inside the response

*Put the populated form in the modal

*Use Javascript to show the modal
$('.modal-title').html("Edit Group")
$('.modal-body').html("<%= escape_javascript( render partial: 'form', locals: {group: @group} ) %>")

$('#myModal').modal()

As simple and as direct as that. Hope this helps a lot.


text:
Q: Expression to Change Background colour if twice the 10 day average I've got this expression in a report:
=iif(
SUM(Fields!Amount.Value) >
    (
    SUM(iif
        (
        Fields!Date.Value >= DateAdd("d",-10,TODAY())
        ,Fields!Amount.Value
        ,CDbl(0)
        )) / 10
    )*2.0,
"Gold",
"Transparent"
)

It is controlling a table's text box background colour.
I was hoping it would change the cell to gold if the amount in the cell is twice, or more, than the 10 day average for that specific row.
The table shows 10 days of data and the dataset it uses has 60 days of data in it, so 10 day averages should be available.
Is the expression incorrect?
This is what it is currently creating - the two rows that are completely orange are obviously not what I want.

A: The issue is with the sum you are doing to create your average. It is really only summing the first number it encounters and then dividing by 10 and multiplying by 2.  You need to change the scope of your sum to the entire dataset.  Here's how I proved this out.
I took the second row of numbers in your table above as my example.  Here's my query.
SELECT        '1/15/14' AS dt, 1 AS value
UNION
SELECT        '1/16/14' AS dt, 7 AS value
UNION
SELECT        '1/17/14' AS dt, 5 AS value
UNION
SELECT        '1/18/14' AS dt, 6 AS value
UNION
SELECT        '1/19/14' AS dt, 4 AS value
UNION
SELECT        '1/20/14' AS dt, 5 AS value
UNION
SELECT        '1/21/14' AS dt, 5 AS value
UNION
SELECT        '1/22/14' AS dt, 5 AS value
UNION
SELECT        '1/23/14' AS dt, 6 AS value
UNION
SELECT        '1/24/14' AS dt, 6 AS value

I created a tablix with dt in the columns value in the data. If I take your average calculation and put it in a row below, it will return 9.8 for every column.
I first used your fill expression to make sure I got the same results as you.  Then I altered it to get the correct answer:
=iif(Sum(Fields!value.Value) >
(Sum(iif(Fields!dt.Value >= Dateadd("d",-10, today()), Fields!value.Value, CDbl(0)), "DataSet1")/10) * 2,
"Gold","White")

With the data I had, none of the cells should turn gold, and that is the result I got.  If I change the value for 1/15 to 20 and then preview my table, that cell turns gold because 69/10*2 = 13.8 and 20 > 13.8.


text:
Q: Cross compiling OpenCV on Ubuntu - zlib.h missing I try to cross compile OpenCV for my Raspberry Pi with Qt on Ubuntu with the following setup:

*

*/opt/Toolchain/RaspberryPi/sysroot : Sysroot from the Raspberry Pi. Downloaded with rsync from the device

*/opt/Toolchain/RaspberryPi/tools : Raspberry Pi toolchain from GitHub

I have downloaded the opencv and opencv_contrib folder from GitHub and place a custom arm-raspberrypi.cmake in opencv/platforms/linux
arm-raspberrypi.cmake
set( CMAKE_SYSTEM_NAME Raspberry Pi )
set( CMAKE_SYSTEM_PROCESSOR arm )
set( SYSROOT /opt/Toolchain/RaspberryPi/sysroot )
set( CMAKE_C_COMPILER /opt/Toolchain/RaspberryPi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-gcc )
set( CMAKE_CXX_COMPILER /opt/Toolchain/RaspberryPi/tools/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/bin/arm-linux-gnueabihf-g++ )
set( CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --sysroot=${SYSROOT} -fdata-sections -Wa,--noexecstack -fsigned-char -Wno-psabi -march=armv6 -mfloat-abi=hard -mfpu=vfp" )
set( CMAKE_C_FLAGS "${CMAKE_C_FLAGS} --sysroot=${SYSROOT} -fdata-sections -Wa,--noexecstack -fsigned-char -Wno-psabi -march=armv6 -mfloat-abi=hard -mfpu=vfp" )

My cmake command looks like this:
cmake \
-D CMAKE_TOOLCHAIN_FILE=/home/daniel/Schreibtisch/Test/opencv/platforms/linux/arm-raspberrypi.cmake \
-D CMAKE_BUILD_TYPE=RELEASE \
-D CMAKE_INSTALL_PREFIX=/home/daniel/Schreibtisch/OpenCVTest \
-D INSTALL_C_EXAMPLES=OFF \
-D INSTALL_PYTHON_EXAMPLES=OFF \
-D OPENCV_EXTRA_MODULES_PATH=../../opencv_contrib/modules \
-D WITH_V4L=ON \
-D WITH_QT=ON \
-D Qt5Core_DIR=/opt/Toolchain/RaspberryPi/sysroot/usr/local/RaspberryQt/lib/cmake/Qt5Core \
-D Qt5Gui_DIR=/opt/Toolchain/RaspberryPi/sysroot/usr/local/RaspberryQt/lib/cmake/Qt5Gui \
-D Qt5OpenGL_DIR=/opt/Toolchain/RaspberryPi/sysroot/usr/local/RaspberryQt/lib/cmake/Qt5OpenGL \
-D Qt5Widgets_DIR=/opt/Toolchain/RaspberryPi/sysroot/usr/local/RaspberryQt/lib/cmake/Qt5Widgets \
-D Qt5Test_DIR=/opt/Toolchain/RaspberryPi/sysroot/usr/local/RaspberryQt/lib/cmake/Qt5Test \
-D Qt5Concurrent_DIR=/opt/Toolchain/RaspberryPi/sysroot/usr/local/RaspberryQt/lib/cmake/Qt5Concurrent \
-D QT_QMAKE_EXECUTABLE=/opt/Toolchain/RaspberryPi/sysroot/usr/local/RaspberryQt/bin \
-D WITH_OPENGL=ON \
-D ENABLE_NEON=ON \
-D ENABLE_VFPV3=ON \
-D WITH_TBB=OFF \
-D BUILD_EXAMPLES=OFF ..

But I´ve got this error during make
Scanning dependencies of target libpng
[ 13%] Building C object 3rdparty/libpng/CMakeFiles/libpng.dir/pngwutil.c.o
In file included from /home/daniel/Schreibtisch/Test/opencv/3rdparty/libpng/pngpriv.h:913:0,
                 from /home/daniel/Schreibtisch/Test/opencv/3rdparty/libpng/pngwutil.c:14:
/home/daniel/Schreibtisch/Test/opencv/3rdparty/libpng/pngstruct.h:30:18: fatal error: zlib.h: No such file or directory
 #include "zlib.h"
                  ^
compilation terminated.

But the file is available at /opt/Toolchain/RaspberryPi/sysroot/usr/include/. What is going on here?


text:
Q: Why does file:///android_asset stop working? I have an app that uses some HTML and images for an informational activity. I programmed it a few years ago and it worked fine:
WebView wvManual = (WebView)findViewById(R.id.wvManual);
wvManual.loadUrl("file:///android_asset/info.html");

However, when I open it now, I get a "Webpage not available" error, saying "file:///android_asset/info.html" is not available.
The files are there in the assets/ directory. And according to the documentation, it should work this way:

Assets and resources are still accessible using file:///android_asset and file:///android_res.

A: Found it.
I am using a library for most of the code (I have two apps based on the same source code tree, with minor changes) and the assets/ dir was in the library. I moved it to the "actual" app's assets/ dir and it works now.


text:
Q: No such module 'Cocoa' in UiTabBarController I created a new file in xcode 6 with the UiTabBarController template.
It generated this code:
import Cocoa

class BottomBarController: UiTabBarController {

}

This is giving me the error: No such module 'Cocoa'
Whats wrong here? I haven't changed anything from what Xcode generated.

A: When you created the file you had OS X selected, not iOS. Changing Cocoa to UIKit should fix it. If that doesn't work, delete the file & create it again but be sure you are creating an iOS Cocoa Touch class not Cocoa class.


text:
Q: tracing sources of queries in Hibernate In Hibernate is there a way to trace which line of source code does each of the generated queries come from? I have been using debugging tools to print out nicely formatted HQL queries in the server log, but I would like to know how I can trace where in the source code such queries were generated.

A: I also use Criteria API and I think I know why you are asking this. The problem is that it is very difficult to inspect the Criteria instance before calling the list() method. For example, this question deals with inspecting a hibernate Criteria instance to see which aliases have been defined on it.
How do I determine whether a Criteria instance already has a Subcriteria?
Perhaps there is a clue in this for you, because one suggestion was to use Hibernate's CriteriaImpl class, even though it is a non-standard approach.
Does JPA2 Criteria address this problem?


text:
Q: How to make Android Studio use my build.gradle template for a new project? I make a build.gradle to increment prod version code on release build and some other config that I want for all my futur projects, is there a way to tell Android Studio (or intelliJ) to use my build.gradle for all new project I create ?
Or maybe is there a template use by IDE for gradle file I can modify?

A: I have found that android studio does not use the templates from the sdk directory. I have found the template in :
<android-studio>/plugins/android/lib/templates/gradle-projects/NewAndroidProject/root/build.gradle.ftl

you could try putting your gradle functions in here and android studio should pick them up for every new Android application project

A: → ~/../../sdk/tools/android create project
--activity MainActivity
--package com.example.android
--target 3
--path ~/AndroidStudioProjects/Example
--gradle YOUR_GRADLE_TEMLATE_PATH

to see details:
→ ~/../../sdk/tools/android -h


text:
Q: What is temporal difference learning While reading about reinforcement learning, I saw that this is a prediction method, somewhat similar to Monte Carlo.
What is an example of it?

A: Information on Temporal Difference (TD) learning is widely available on the internet, although David Silver's lectures are (IMO) one of the best ways to get comfortable with the material.
In TD learning, the Q-values are updated after each iteration throughout an epoch, instead of only updating the values at the end of the epoch, as happens in Monte Carlo learning. A more intermediate solution is TD($\lambda$), which updates every $\lambda$ fraction of the total number of iterations per epoch. Therefore, pure TD can be seen as TD(0) and Monte Carlo as TD(1).
An informative example of TD learning is explained here, by the means of simplified BlackJack robot.


text:
Q: why MUI datepicker not working in production? I'm using MUI datepicker along with React hook form, I'm using @mui/lab/AdapterMoment as date adaptor.
In local environment, datepicker's onChange is working fine. But when it is built and deployed in production, onChange is not working so if I click on a date nothing is happening. I tested react hook and it seems to be working fine. Can anyone help me figure out this issue?
<LocalizationProvider dateAdapter={DateAdapter}>
              <Controller
                name="reminderFromDate"
                control={control}
                rules={{
                  required: true,
                }}
                render={({ field: { onChange, value } }) => (

                    <DatePicker
                      className="login_input remeberFieldInput ip-field w-100 "
                      label="Date"
                      mask="___ __ ___, ____"
                      inputFormat={"ddd D MMM, YYYY"}
                      value={value}
                      disablePast
                      readOnly
                      onChange={(e) => onChange(e)}
                      renderInput={(params) => (
                        <TextField
                          {...params}
                          onClick={(e) => setStartDate(true)}
                        />
                      )}
                      open={isStartDate}
                      onClose={() => setStartDate(false)}
                    />
                    {errors.reminderFromDate && (

                        {"This field is required"}

                    )}

                )}
              />
            </LocalizationProvider>


text:
Q: Combination of two dataframes without duplicate and reversion in efficient way | python I have two dataframes with thousands of rows, I need to combine both into one dataframe without duplicate and reversion. for example:
Dataframe 1
drug1
drug2
drug3

Dataframe 2
disease1
disease2
disease3

So, the output dataframe will be:
output-dataframe
drug1 disease1
drug1 disease2
drug1 disease3
drug2 disease1
drug2 disease2
drug2 disease3
drug3 disease1
drug3 disease2
drug3 disease3

I don't want the output combination containing something like:
disease1 drug1
drug1 drug1
disease1 disease1

I actually try it using pd.merge but it return duplicate and reversion and also took long time because I have thousands in Dataframes 1 and 2
Any help please ?

A: One way purely in pandas would be to create a MultiIndex from product, then convert it to a dataframe:
>>> df1
       0
0  drug1
1  drug2
2  drug3
>>> df2
          0
0  disease1
1  disease2
2  disease3

df3 = (pd.MultiIndex.from_product([df1[0],df2[0]])
       .to_frame()
       .reset_index(drop=True))

>>> df3
       0         1
0  drug1  disease1
1  drug1  disease2
2  drug1  disease3
3  drug2  disease1
4  drug2  disease2
5  drug2  disease3
6  drug3  disease1
7  drug3  disease2
8  drug3  disease3

A: Setup
df1 = pd.DataFrame(dict(col1=[f"drug{i}" for i in range(1, 4)]))
df2 = pd.DataFrame(dict(col2=[f"disease{i}" for i in range(1, 4)]))

merge on assigned column
df1.assign(A=1).merge(df2.assign(A=1)).drop('A', 1)

    col1      col2
0  drug1  disease1
1  drug1  disease2
2  drug1  disease3
3  drug2  disease1
4  drug2  disease2
5  drug2  disease3
6  drug3  disease1
7  drug3  disease2
8  drug3  disease3

comprehension
pd.DataFrame([
    (i, j) for i in df1.col1
           for j in df2.col2
], columns=['col1', 'col2'])

pandas.concat
generalized for the cross product of any two dataframes
i = df1.index.repeat(len(df2))
j = np.tile(df2.index, len(df1))

pd.concat([
    df1.loc[i].reset_index(drop=True),
    df2.loc[j].reset_index(drop=True)
], sort=True, axis=1)

A: Try this solution:
from pandas import DataFrame, merge

df1['key'] = 1
df2['key'] = 1

result = df1.merge(df2, on='key').drop('key', axis=1)


text:
Q: Prevent route change on refresh with Vue navigation guards I have navigation guards working perfectly based on a userTp value, however whenever the user reloads a page it redirects them to name: 'login'.
I would like to prevent a route change on refresh. Is there a simple way to do this within navigation guards?
router.beforeEach(async (to, from, next) => {
  if (to.meta.requireAuth) {
    if (!store.state.auth.user) {
      await store.dispatch(AUTH_REFRESH)
    }
    if (to.meta.userTp === store.state.auth.user.userTp) {
      next()
      window.scrollTo(0, 0)
    } else {
      next({ name: 'login' })
      window.scrollTo(0, 0)
    }
  } else {
    next()
    window.scrollTo(0, 0)
  }
})

EDIT:
I found a semi-workaround for this, but it's not perfect. It allows users to access pages if they know the correct page url path, but since my setup has a server-side userTp check before sending data it just shows the page template but without any data in it.
My temp solution:
(Added as the first if statement)
router.beforeEach(async (to, from, next) => {
      if (to = from) {
        if (!store.state.auth.user) {
          await store.dispatch(AUTH_REFRESH)
          to()
        }
      }


text:
Q: Как подписать оси на графике в Matplotlib Pyplot Подскажите пожалуйста как подписать оси на графике построенном в библиотеке Matplotlib pyplot если оси выровнены по центру. Вот мой код:
import matplotlib.pyplot as plt
import numpy as np

a = 0.04
y = lambda x: a * np.sin(x)

fig = plt.subplots()
plt.title("First graphic: 0.04 * sin(x)")
x = np.linspace(-10, 10, 100)
plt.plot(x, y(x), "r-")

ax = plt.gca()
ax.spines['left'].set_position("center")
ax.spines['bottom'].set_position('center')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

ax.set_xlabel("X", fontsize=15, color='blue')
ax.set_ylabel("Y", fontsize=15, color='orange')

plt.show()

A: Попробуйте добавить labelpad
import matplotlib.pyplot as plt
import numpy as np

a = 0.04
y = lambda x: a * np.sin(x)

fig = plt.subplots()
plt.title("First graphic: 0.04 * sin(x)")
x = np.linspace(-10, 10, 100)
plt.plot(x, y(x), "r-")

ax = plt.gca()
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

ax.set_xlabel("X", fontsize=15, color='blue', labelpad=120)    # +
ax.set_ylabel("Y", fontsize=15, color='orange', labelpad=140)  # +

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

plt.show()

А случайно не знаете, игрек можно перевернуть или тут уже всё?

Попробуйте добавить rotation
import matplotlib.pyplot as plt
import numpy as np

a = 0.04
y = lambda x: a * np.sin(x)

fig = plt.subplots()
plt.title("First graphic: 0.04 * sin(x)")
x = np.linspace(-10, 10, 100)
plt.plot(x, y(x), "r-")

ax = plt.gca()
ax.spines['left'].set_position('center')
ax.spines['bottom'].set_position('center')
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)

ax.set_xlabel("X", fontsize=15, color='blue', labelpad=120)    # +
ax.set_ylabel("Y", fontsize=15, color='orange', labelpad=140, rotation=0)  # +

ax.xaxis.set_ticks_position('bottom')
ax.yaxis.set_ticks_position('left')

plt.show()

A: Вы можете вручную располагать маркеры осей, принимая во внимание, что для маркеров начало координат находится в левом нижнем углу и позиция измеряется в долях от единицы:
ax.xaxis.set_label_coords(1.005, 0.495)
ax.yaxis.set_label_coords(0.495, 1.005)


text:
Q: No consigo que me funcione conda en windows Estoy tratando de instalar miniconda3 y no sé el motivo por el que no se me instala.
Para empezar, al ejecutar anaconda prompt (miniconda3) no me aparece con el icono de consola.
Posteriormente al ejecutar conda --ver me dice que no lo reconoce.
He instalado y desinstalado en diferentes carpetas. Con y sin PATH. Retocando yo los PATH.
Códigos de ERROR que me aparecen:
En Anaconda Powershell Prompt
'C:\Users\alfon\miniconda3\shell\condabin\conda-hook.ps1' no se reconoce como nombre de un cmdlet

Al instalar MINCONDA:
CustomValidationError: Parameter ssl_verify = 'C:\\Users\\alfon\\miniconda3\\.crt' declared in <<merged>> is invalid.
ssl_verify value 'C:\Users\alfon\miniconda3\.crt' must be a boolean, a path to a certificate bundle file, or a path to a directory containing certificates of trusted CAs.

En Anaconda Prompt (Miniconda)
C:\Users\alfon>conda
"conda" no se reconoce como un comando interno o externo,
programa o archivo por lotes ejecutable.

Si alguien me pudiera ayudar estaría agradecido.


text:
Q: QtQml conversion for Non-QObject types Since QtScript is deprecated in Qt5.5, I have to migrate to QtQml JS engine. I can't find any articles, how to migrate painless.
In old code for value-based types (not derived from QObject) was a possibility to create wrapper, by deriving from QScriptable. In QtQml there are no QScriptable. but I know, that they have similar conversion qml basic types, like
Point     <-> QPoint
Rectangle <-> QRect

I think, it should be possible to register value-type with some conversion functions to wrapper and vice-verse.
Do you know how to achieve it?


text:
Q: Virtual or Soft Keyboard slows down speed of OS I am working on soft keyboard where I am successfully replacing the
current default device keyboard with my soft keyboard.
But the problem is, that after a couple of utilization's the full keyboard became blank and the phone Operating System started to run very slow. I had to shut down the keyboard app to make the phone work properly again.
As I had used KeyboardView and in keyboardview I had used paint, canvas, bitmap which is called frequently by OS.
public void onDraw(Canvas canvas) {
rect = new RectF(x2+4, y2+4, ((width-4)+(x2+4)), ((height-10)+(y2+4)));
canvas.drawRoundRect(rect, 3, 3, paint2);
canvas.drawText(key.label.toString(), x2 + (float)(width * 0.40), y2 + (float)(height * 0.7), paint);
canvas.drawText(smallAlphaText[index], x2 + (float)(width * 0.15), y2 + (float)(height * 0.30), paint3);
canvas.drawText(smallBetaText[index], x2 + (float)(width * 0.80), y2 + (float)(height * 0.30), paint4);
}

This is the small code snippet showing what actually i have used.
Basically onDraw() is called again and again by OS, so although i replaced my soft  keyboard with default keyboard it running at
  background and slows down the speed of device
I think this is the issue which slows down speed of my phone.  So
  how can I use paint, canvas, bitmap efficiently so that it doesn't
  slow down my device?

A:
Hi I found problem due to which my device is lagging.
I am calling my service from activity class. As if this is working on
  newer version devices.
But my device is lagging when I try to change my soft keyboard device
  default keyboard.
Earlier I tried below code I written this code in my activity class,

    Intent intent = new Intent(v.getContext(),SoftKeyboard.class);
    startService(intent);
    finish();

As we can see in above code I am trying to start service.
Now I just skipped first two lines, so now it's systems responsibility
  to call service.


text:
Q: APEX 5.1 - Navigation menu gets reset to the top-level menu With Oracle Apex 5.1, I use the side navigation menu as the main menu.
I have 3 levels of navigation :
1st level
|
+- 2nd level
|
+---- 3rd level

When clicking on the 3rd level navigation menu, it renders the pages and also reset the navigation menu to the 1st level only (hiding sub-menus of 2nd and 3rd levels)
I want to keep the 3 levels of navigation collapsed when clicking on the 3rd level navigation menu.
Can anyone tell me what are the relevant settings to achieve this?

A: Have a look at what John Snyders suggests, here; shortly, create a JavaScript page load dynamic action
$("#t_TreeNav").treeView("option", "autoCollapse", false).treeView("expandAll")

which

*

*turns off the auto collapse feature (this lets only one node be open per level at a time) and then

*expands all the nodes.

All credits go to John, I'm just a copy machine.