text:
Q: Triggering change on input I have written some code that changes an input quantity on a magento 1.9 ecommerce website.
jQuery("input.qty").val("10");

The problem is the javascript that triggers the total to update doesn't fire.  I have found the code responsible and it looks like this:
(function() {
  var qtyFields = $('super-product-list').select('input.qty');
  qtyFields.each(function(el) {
    el.observe("change", updateGroupedPrice);

  });

  Event.observe(window, "load", updateGroupedPrice);

  function updateGroupedPrice() {
    //do stuff
  }
})();

I think this is using prototype.js but I tried to isolate it in a codepen but couldn't get it working.
I have tried to trigger the change event like so:
jQuery("input.qty").trigger("change")

But it does not work.  I also ran through a load of other events but in the dev tools it shows the code listening on "change".
Does anyone know why I can't trigger the change?

A: Since the page is using Prototype.js, you ought to keep using that to trigger your change. If you introduce jQuery into this, you're a) loading another complete duplicate of what Prototype already does, and b) asking for a lot of trouble isolating the fact that $() is a method in both libraries.
Your jQuery is a little fishy to me, too. You're setting the value of one picker (I imagine) and yet you are addressing it with a classname, so potentially there is more than one select.qty in the page, and all of them will change to value 10, firing off (potentially) multiple callback functions.
The Prototype code you see here is setting up a "listener" for changes on what you would address in jQuery as$(#super-product-list input.qty) inputs.
jQuery always treats $() as returning an array of objects, and thus all of its methods act on the array, even if it only contains one member. Prototype has two different methods for accessing elements in the DOM: $('some_id'), which always returns one element (or none, if no match), and $$('some css selector'), which always returns an array (of zero or more matching elements). You would write (or use native) callback methods differently, depending on which accessor you used to gather the element(s).
If you want to change one of these inputs, you will need to isolate it before you set its value.
Let's say there are three select pickers with the classname qty in your #super-product-list element. You want to change the third one to 10:
$('super-product-list').select('input.qty').last().setValue('10');

Or, much smarter than this, you add an ID to the third one, and then your code is much shorter:
$('quantity_3').setValue('10');

In either case, this will send the "change" event from your select, and the updateGroupedPrice method will observe that and do whatever you have coded it to do.
You won't need to (and should not ever) trigger the change event -- that's a "native" event, and the browser owns it. jQuery's trigger() (which is fire() in Prototype, is used exclusively for "synthetic events", like you see in Bootstrap: show.bs.modal, hide.bs.modal, etc. You can spot these by the punctuation in their names; usually dots or colons to namespace the events and avoid collisions with other code.
Finally, if you really, really, really wanted to change every single #super-product-list select.qty element on the whole page to '10', you would do this in Prototype.js:
$$('#super-product-list select.qty').invoke('setValue', 10);


text:
Q: How to schedule LocalNotifications to fire on Every 2 Days or Every 3 Days. I am having an app in which I have to schedule Local Notifications. Consider a user enters the time 7 AM, then the Notification has to be fired on 7 AM every day (or, ever 2 days, or every 3 days) based on the settings he set. This Notification has to be fired on regular basis until the user turns of the Notification.
My doubt is how to schedule the Notification to fire on every 2 days or every 3 days or every 2 weeks like that? Sorry if this is a very basic question. I am new to Local Notifications.

A: What you need you need to make a date list from a start date to end date then need to enter a gap in days for alarms and according to that gap you need to set alarms.
date with time is required for alarms.
see this function this return an array of dates with gap in days
-(NSMutableArray *)getDatesArrayBetweenDates:(NSString *)minDate toDate:(NSString *)maxDate freqDays:(NSInteger )dayfreq
{
    // minDate and maxDate represent your date range
    NSMutableArray *resultArray=[NSMutableArray array];
    NSCalendar *gregorianCalendar = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
    NSDateComponents *days = [[NSDateComponents alloc] init];
    NSDate *minDateObject;
    NSDate *maxDateObject;
    NSDateFormatter *df=[[NSDateFormatter alloc] init];
    [df setDateFormat:@"MM/dd/yyyy"];
    minDateObject=[df dateFromString:minDate];
    maxDateObject=[df dateFromString:maxDate];
    NSInteger dayCount = 0;
    while ( TRUE ) {

        NSDate *date = [gregorianCalendar dateByAddingComponents: days toDate: minDateObject options: 0];
        [days setDay: ++dayCount];
        if ( [date compare: maxDateObject] == NSOrderedDescending )
            break;
        // Do something with date like add it to an array, etc.
        NSString *dateForAdd=[df stringFromDate:date];
        //if(![self.dateListArray containsObject:dateForAdd])
            [resultArray addObject:dateForAdd];
    }
    [df release];
    [days release];
    [gregorianCalendar release];

    NSMutableArray *returnableArray=[NSMutableArray array];
    NSInteger day=0;
    for(int i=0;i<[resultArray count];i++)
    {
       if(day==0)
       {
           [returnableArray addObject:[resultArray objectAtIndex:i]];
       }

        if(day==dayfreq)
            day=0;
        else {
            ++day;
        }

    }
    return returnableArray;
}

what you need to pass a start date and end date  in string and the days gap for alarm and this function returns you a array of dates in strings.Now you need to use these date and append your time then make date object by NSDateFormatter then set it for fireDate of local notification.
see this link for more info

A: UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.fireDate = [put a NSDate object here];
localNotification.repeatInterval = NSDayCalendarUnit;

This creates a local notification that repeats daily.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Allow Roles does not work I have a web application with 2 folders. Administrator and Trainer which contain their respective pages. I have a web.config in each folder as below. When i login using these configuration settings, the user is denied access to his home page and if I remove deny users everybody can login. I have created roles and added user to the roles using WSAT.
Web.Config For Administrator
<?xml version="1.0"?>
<configuration>
<system.web>
    <authorization>
      <allow roles="Administrator" />
      <deny users="?"/>
    </authorization>
</system.web>
</configuration>

Web.Config For Trainer
<?xml version="1.0"?>
<configuration>
<system.web>
    <authorization>
      <allow roles="Trainer" />
      <deny users="?"/>
    </authorization>
</system.web>
</configuration>

Root Folder Web.Config File
<?xml version="1.0"?>

<configuration>
<connectionStrings>
<add name="TSS" connectionString="Data Source = VC-SQL2008; Integrated
    Security=True;   database = aspnetdb" providerName="System.Data.SqlClient"/>
</connectionStrings>

<system.web>
<compilation debug="true" targetFramework="4.0"/>
<authentication mode="Forms">
  <forms loginUrl="Login.aspx" timeout="2880" />
</authentication>
</system.web>

<system.web>
<membership>
  <providers>
    <clear/>
    <add name="AspNetSqlMembershipProvider"
 type="System.Web.Security.SqlMembershipProvider" connectionStringName="TSS"
 requiresQuestionAndAnswer="false" requiresUniqueEmail="false"
 enablePasswordRetrieval="false" enablePasswordReset="false"
 maxInvalidPasswordAttempts="5" minRequiredPasswordLength="1"
 minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10"
 applicationName="/"/>

  </providers>
  </membership>

  <profile>
  <providers>
    <clear/>
    <add name="AspNetSqlProfileProvider"
  type="System.Web.Profile.SqlProfileProvider"
   connectionStringName="TSS" applicationName="/"/>
  </providers>
 </profile>

 <roleManager enabled="true">
  <providers>
    <clear />
    <add connectionStringName="TSS" applicationName="/" name="AspNetSqlRoleProvider"
   type="System.Web.Security.SqlRoleProvider" />

  </providers>
</roleManager>

<pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"/>
</system.web>

<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>

web.sitemap example on how I have added roles
enter<siteMapNode url="Administrator/Admin_Home.aspx" title="Home"  description=""
roles="Administrator">

Login.aspx.cs
    namespace TSS
    {
        public partial class Login2 : System.Web.UI.Page
        {
              protected void Page_Load(object sender, EventArgs e)
               {
                   dbConnection dbConn = new dbConnection();
               }
  protected void submit_Click(object sender, EventArgs e)
  {
       // var a = Session["username"];
       string password = tb_password.Text;
       // Membership.CreateUser("s.g@visiblechanges.com", "9000");

       bool x = Membership.ValidateUser(tb_email.Text, password);
       string f_name;
       string l_name;
       string trainer="";
       DataTable dt = new DataTable();
       dt = TSS_WebService.getEmployeeByEmail(tb_email.Text);

       foreach (DataRow row in dt.Rows)
       {
            f_name = row["First_Name"].ToString();
            l_name = row["Last_Name"].ToString();
             trainer = row["First_Name"].ToString() + " " +
           row["Last_Name"].ToString();
       }

   if (x == true)
  {

    Session["username"] = tb_email.Text;
    Session["trainer"] = trainer;

    if (Roles.IsUserInRole(tb_email.Text, "Administrator"))
    {
         Response.Redirect("~/Administrator/Admin_Home.aspx");
    }

  if (Roles.IsUserInRole(tb_email.Text, "Trainer"))
  {

   Response.Redirect("~/Trainer/Trainer_Home.aspx");
  }

   if (Roles.IsUserInRole(tb_email.Text, "Salon Manager"))
   {

    Response.Redirect("~/Salon/Salon_Home.aspx");
   }

   if (Roles.IsUserInRole(tb_email.Text, "IT"))
    {

     Response.Redirect("Home.aspx");
     }
   }

   else
   {
        FormsAuthentication.RedirectToLoginPage();
   }
  }

  }
  }

***Login.aspx***
    <%@ Page Title="" Language="C#" MasterPageFile="~/Master/Master.Master"
    AutoEventWireup="true" CodeBehind="Login.aspx.cs" Inherits="TSS.Login2" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="BreadCrumbs" runat="server">
    <asp:SiteMapPath ID="SiteMapPath1" runat="server">
    </asp:SiteMapPath>
    </asp:Content>
    <asp:Content ID="Content3" ContentPlaceHolderID="MainArea" runat="server">

 LOGIN

    <asp:TextBox ID="tb_email" runat="server" class = "ipBox_large"></asp:TextBox>

    <asp:TextBox ID="tb_password" runat="server" class = "ipBox_large"></asp:TextBox>

     <asp:ImageButton ID= "btn" ImageUrl = "../Images/btnLogin.gif" OnClick =
     "submit_Click"
     runat="server" />
     <asp:CheckBox id="NotPublicCheckBox" runat="server" />

    </asp:Content>

I've been stuck with this for 2 days now and have researched everything I possibly could.Any help or advice is much appreciated thanks.

A: Use <deny users="?"/>
rather than <deny users="*"/>

A: Try the following code instead of your if(x==true){...} Part if (x == true)
    {
        if (Request.QueryString["ReturnUrl"] != null)
        {
            //redirect to the return url
            FormsAuthentication.RedirectFromLoginPage(userName.Text, NotPublicCheckBox.Checked);
        }
    /* create authentication cookie */
    FormsAuthentication.SetAuthCookie(tb_email.Text, NotPublicCheckBox.Checked)
    Session["username"] = tb_email.Text;
    Session["trainer"] = trainer;

    /*redirect depending on roles*/
    if (Roles.IsUserInRole(tb_email.Text, "Administrator"))
    {
        Response.Redirect("~/Administrator/Admin_Home.aspx");
    }

    if (Roles.IsUserInRole(tb_email.Text, "Trainer"))
    {
        Response.Redirect("~/Trainer/Trainer_Home.aspx");
    }

    if (Roles.IsUserInRole(tb_email.Text, "Salon Manager"))
    {
        Response.Redirect("~/Salon/Salon_Home.aspx");
    }

    if (Roles.IsUserInRole(tb_email.Text, "IT"))
    {
        Response.Redirect("Home.aspx");
    }
}
else
{
    /*Login error*/
    FormsAuthentication.RedirectToLoginPage();
}

Hope It works. Good Luck.


text:
Q: wordpress conditional statement for home page I am developing a wordpress blog theme, which shows the posts on the homepage. I am trying to show some text ONLY on the homepage, and not on page 2,3 ,4 and so on of the blog posts. The code below shows the text on all blog pages:
<?php
    if (is_front_page()) {
    ?>
TEST FRONT PAGE

    <?php
} ?>

How do I show this ONLY on the front home page (page 1, not pages after 1)?
ANSWER FOUND IN COMMENT BELOW

A: Instead of declaring an additional variable and checking it you can access the global in wp_query with is_paged.
<?php if (is_home() && !is_paged()) : ?>
Your front page content.
<?php endif; ?>

Or if you have a static post as the front page with its own sub pages you can use:
<?php if (is_front_page() && !is_paged()) : ?>
Your static front page content.
<?php endif; ?>

To target just the first page of the static post.


text:
Q: Constructor parameter access member field of object under construction I have the following structure that has a member function pointer. My question is, is there a way for the lambda that I pass to it to refer to its own member variable? i.e.
struct Foo
{
   int aVar{1};
   int (*funcPtr)(int);

   Foo(int (*func)(int)) : funcPtr(func) {};
};

auto bar1 = Foo([](int a) {std::cout << a;}) // ok
auto bar2 = Foo([](int a) {std::cout << a + bar2.aVar;}) // Not ok but is there a way to access the member variable of the object currently being defined?

Can I achieve something to this effect?
What I would like to achieve here is a process to automatically generate objects based on the lambda you pass in. e.g: bar2 above is an object that can return anything plus its stored value. i.e. I would like bar2.funcPtr(5) == 5 + bar2.aVar to be an invariant of the class. In the future I might need another object that can return anything minus its stored value, and I only need to pass the corresponding lambda to do that (if the lambda can access the member fields), without defining a new class or method.

A: Foo( /* ... */ )

As used in the shown code this is a constructor call. This is constructing a new object, right there.
Before the new object can be created and its constructor get invoked, the parameters to the constructor must be evaluated. This is how C++ works. There are no alternatives, or workarounds, that end up constructing the object first and only then evaluate its constructor's parameters afterwards.
For this reason it is logically impossible for a lambda, that gets passed as parameter to the constructor, "refer to its own member variable". There is nothing in existence that has "its own member variable" at this point. The object's construction has not began, and you cannot refer to an object or a member of an object that does not exist. The object cannot be constructed until the constructor's parameters get evaluated, first. C++ does not work this way.
You will need to come up with some alternative mechanism for your class. At which point you will discover another fatal design flaw that dooms the shown approach:
int (*funcPtr)(int);

This is a plain function pointer. In order for lambda to reference an object that it's related to, in some form or fashion, it must capture the object (by reference, most likely). However lambdas that capture (by value or reference), cannot be converted to a plain function pointer. Only capture-less lambdas can be converted to a plain pointer.
At the bare minimum this must be a std::function, instead.
And now that it's a std::function, you can capture its object, by reference, in the lambda, and assign it to the std::function.
But this is not all, there is another problem that you must deal with: in order for all of this to work it is no longer possible for the object to be moved or copied in any way. This is because the lambda captured a reference to the original object that was constructed, full stop.
And the fact that the constructed object gets copied or moved does not, in some form or fashion, modify the lambda so it now magically captures the reference to the copy or the moved instance of the original object.
None of these are insurmountable problems, but they will require quite a bit of work to address, in order to have a well-formed C++ program as a result.

A: The lambda must have the signature int(int) but your lambda has the signature void(int) so that's the first problem.
The other is that the lambda must capture bar2. You could use std::function for that.
#include <iostream>
#include <functional>

struct Foo {
   int aVar{1};

   std::function<int(int)> funcPtr;

   Foo(std::function<int(int)> func) : funcPtr(func) {};

   int call(int x) { return funcPtr(x); }
};

int main() {
    Foo bar2([&](int a) { return a + bar2.aVar; });

    std::cout << bar2.call(2);   // prints 3
}

A more practical solution would be to not tie the lambda to the instance for which it was originally created but to let it take a Foo& as an argument (and not to capture it). Moving it around doesn't become such a hassle with this approach.
Example:
struct Foo {
   int aVar;

   int(*funcPtr)(Foo&, int); // takes a Foo& as an argument

   Foo(int x, int(*func)(Foo&, int)) : aVar(x), funcPtr(func) {};

   int call(int x) { return funcPtr(*this, x); }
};

int main() {
    Foo bar2(10, [](Foo& f, int a) { return a + f.aVar; });

    std::cout << (bar2.call(5) == bar2.aVar + 5) << '\n';    // true

    Foo bar3(20, [](Foo& f, int a) { return a * f.aVar; });

    std::cout << bar2.call(2) << '\n'; // 10 + 2 = 12
    std::cout << bar3.call(2) << '\n'; // 20 * 2 = 40

    std::swap(bar2, bar3);

    std::cout << bar2.call(2) << '\n'; // swapped, now 40
    std::cout << bar3.call(2) << '\n'; // swapped, now 12
}


text:
Q: How to include a file from any folder's file including include function in php I have a folder named class. Here I have a lot of class.
And a folder, named include. Here I have added  header.php and footer.php
Then I have a fille called index.php in my project root directory.
I have added header.php and footer.php in my index.php using include_once.
And I have included all classes in my header.php. So I get access all class from index.php.
Now I have created another folder called product. Here I have a file named add.php.
The problem is, when I want to access all class by including header.php it sayes No such file or directory.
So how I can get access all class by including header.php.

A: I am not sure about your application folder structure but you can do certain things to get going-

*

*add all folder paths in php.ini include_path variable where your classes are present

*create a function called autoload then write the code of lazy loading in there. (search for autoload concept if you are not aware of this)

*register the function using spl_autoload_register(autoload)

now you don't have to worry about loading all the classes itself. they will be included automatically whenever needed.
This is the best practice too.


text:
Q: Python requests web scraping API I have some experience with web scraping and API, however I'm not able to search the proper API do to do so in this website:
https://www.giga.com.vc/Bebida
obs: /Bebida is just a category like "/Drinks"
The issue is, I found several APIs but they are for one product only, or they even are for some products, but I can't seem to find the right rules to paginate it with proper categories or pages and iterate through category products getting prices, EANS etc.
import requests
import pandas as pd
from bs4 import BeautifulSoup

Ex: This works, but the format is horrible:
print(requests.get('https://www.giga.com.vc/padaria?initialMap=c&initialQuery=padaria&map=category-1&page=1').content)

or
urlx = 'https://www.giga.com.vc/_v/segment/graphql/v1?workspace=master&maxAge=short&appsEtag=remove&domain=store&locale=pt-BR&operationName=Products&variables=%7B%7D&extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%2249a77e3e2082563773aff56ad9c0432d59302e86fd1baaad9ca0f4bca2630d46%22%2C%22sender%22%3A%22vtex.store-resources%400.x%22%2C%22provider%22%3A%22vtex.search-graphql%400.x%22%7D%2C%22variables%22%3A%22eyJoaWRlVW5hdmFpbGFibGVJdGVtcyI6ZmFsc2UsInNrdXNGaWx0ZXIiOiJBTExfQVZBSUxBQkxFIiwiaW5zdGFsbG1lbnRDcml0ZXJpYSI6Ik1BWF9XSVRIT1VUX0lOVEVSRVNUIiwiY2F0ZWdvcnkiOiIiLCJjb2xsZWN0aW9uIjoiMTYvIiwic3BlY2lmaWNhdGlvbkZpbHRlcnMiOltdLCJvcmRlckJ5IjoiIiwiZnJvbSI6MCwidG8iOjExfQ%3D%3D%22%7D'
r = requests.get(urlx)
for x in r.json()['data']['products']:
    print(x)

As well this also works:
url2 = 'https://www.giga.com.vc/_v/segment/graphql/v1?workspace=master&maxAge=short&appsEtag=remove&domain=store&locale=pt-BR&__bindingId=3f6e91e6-44f2-4fb0-a2d9-e238b53082e0&operationName=ProductRecommendations&variables=%7B%7D&extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%22e5782bd9e8bc64d337a7d7f96b9c280b462cdb0754d15b415192dac2755ad280%22%2C%22sender%22%3A%22vtex.shelf%401.x%22%2C%22provider%22%3A%22vtex.search-graphql%400.x%22%7D%2C%22variables%22%3A%22eyJpZGVudGlmaWVyIjp7ImZpZWxkIjoiaWQiLCJ2YWx1ZSI6IjE0NzUyMyJ9LCJ0eXBlIjoidmlldyJ9%22%7D'

requests.get(url2).json()['data']['productRecommendations']

Expected output something like this:
r = requests.get(urlx)
for items in r.json()['data']['products']:
    prd_dict = {
        'product_id': items['productId'],
        'price': items['priceRange']['sellingPrice']['highPrice'],
        'product_name': items['productName'],
        'category_id': items['categoryId'],
        'ean': items['items'][0]['ean'],
        'box_qty': items['specificationGroups'][0]['specifications'][0]['values']
        }
    print(prd_dict)

raw output:
{'product_id': '141917', 'price': 20.54, 'product_name': 'Banana Nanica Kg', 'category_id': '433', 'ean': '4511', 'box_qty': ['0']}
{'product_id': '148077', 'price': 1.45, 'product_name': 'Água de Coco Tradicional Quadrado 200Ml', 'category_id': '148', 'ean': '0751320333650', 'box_qty': ['27']}

A: It sends variables as base64 which after decoding have
'{"hideUnavailableItems":false,"skusFilter":"ALL","simulationBehavior":"default","installmentCriteria":"MAX_WITHOUT_INTEREST","productOriginVtex":false,"map":"c","query":"bebida","orderBy":"OrderByScoreDESC","from":40,"to":59,"selectedFacets":[{"key":"c","value":"bebida"}],"operator":"and","fuzzy":"0","searchState":null,"facetsBehavior":"Static","categoryTreeBehavior":"default","withFacets":false}'

If I parse URL, convert all to dictiorany, replace with 'from': 0
'to': 99 then I get 100 products
But it doesn't work if U use value bigger then 99. Maybe it would need some other changes in URL.
import base64
import urllib.parse
import urllib.request
import json

url1 = 'https://www.giga.com.vc/_v/segment/graphql/v1?workspace=master&maxAge=short&appsEtag=remove&domain=store&locale=pt-BR&__bindingId=3f6e91e6-44f2-4fb0-a2d9-e238b53082e0&operationName=productSearchV3&variables=%7B%7D&extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%226869499be99f20964918e2fe0d1166fdf6c006b1766085db9e5a6bc7c4b957e5%22%2C%22sender%22%3A%22vtex.store-resources%400.x%22%2C%22provider%22%3A%22vtex.search-graphql%400.x%22%7D%2C%22variables%22%3A%22eyJoaWRlVW5hdmFpbGFibGVJdGVtcyI6ZmFsc2UsInNrdXNGaWx0ZXIiOiJBTEwiLCJzaW11bGF0aW9uQmVoYXZpb3IiOiJkZWZhdWx0IiwiaW5zdGFsbG1lbnRDcml0ZXJpYSI6Ik1BWF9XSVRIT1VUX0lOVEVSRVNUIiwicHJvZHVjdE9yaWdpblZ0ZXgiOmZhbHNlLCJtYXAiOiJjIiwicXVlcnkiOiJiZWJpZGEiLCJvcmRlckJ5IjoiT3JkZXJCeVNjb3JlREVTQyIsImZyb20iOjIwLCJ0byI6MzksInNlbGVjdGVkRmFjZXRzIjpbeyJrZXkiOiJjIiwidmFsdWUiOiJiZWJpZGEifV0sIm9wZXJhdG9yIjoiYW5kIiwiZnV6enkiOiIwIiwic2VhcmNoU3RhdGUiOm51bGwsImZhY2V0c0JlaGF2aW9yIjoiU3RhdGljIiwiY2F0ZWdvcnlUcmVlQmVoYXZpb3IiOiJkZWZhdWx0Iiwid2l0aEZhY2V0cyI6ZmFsc2V9%22%7D'
url2 = 'https://www.giga.com.vc/_v/segment/graphql/v1?workspace=master&maxAge=short&appsEtag=remove&domain=store&locale=pt-BR&__bindingId=3f6e91e6-44f2-4fb0-a2d9-e238b53082e0&operationName=productSearchV3&variables=%7B%7D&extensions=%7B%22persistedQuery%22%3A%7B%22version%22%3A1%2C%22sha256Hash%22%3A%226869499be99f20964918e2fe0d1166fdf6c006b1766085db9e5a6bc7c4b957e5%22%2C%22sender%22%3A%22vtex.store-resources%400.x%22%2C%22provider%22%3A%22vtex.search-graphql%400.x%22%7D%2C%22variables%22%3A%22eyJoaWRlVW5hdmFpbGFibGVJdGVtcyI6ZmFsc2UsInNrdXNGaWx0ZXIiOiJBTEwiLCJzaW11bGF0aW9uQmVoYXZpb3IiOiJkZWZhdWx0IiwiaW5zdGFsbG1lbnRDcml0ZXJpYSI6Ik1BWF9XSVRIT1VUX0lOVEVSRVNUIiwicHJvZHVjdE9yaWdpblZ0ZXgiOmZhbHNlLCJtYXAiOiJjIiwicXVlcnkiOiJiZWJpZGEiLCJvcmRlckJ5IjoiT3JkZXJCeVNjb3JlREVTQyIsImZyb20iOjQwLCJ0byI6NTksInNlbGVjdGVkRmFjZXRzIjpbeyJrZXkiOiJjIiwidmFsdWUiOiJiZWJpZGEifV0sIm9wZXJhdG9yIjoiYW5kIiwiZnV6enkiOiIwIiwic2VhcmNoU3RhdGUiOm51bGwsImZhY2V0c0JlaGF2aW9yIjoiU3RhdGljIiwiY2F0ZWdvcnlUcmVlQmVoYXZpb3IiOiJkZWZhdWx0Iiwid2l0aEZhY2V0cyI6ZmFsc2V9%22%7D'

#print('--- url ---')
#print(url)

parts = urllib.parse.urlparse(url1)
#print(parts)

query = urllib.parse.parse_qs(parts.query)
#print(query)

data = json.loads(query['extensions'][0])
variables = data['variables']
#print(variables)

q = base64.b64decode(variables.encode()).decode()
q = json.loads(q)

print('--- replace values ---')

print(q)

q['from'] = 0
q['to'] = 99

print(q)

print('---')

q = json.dumps(q)
variables = base64.b64encode(q.encode()).decode()
#print(variables)

data['variables'] = variables
query['extensions'][0] = json.dumps(data)
#print(query)

parts = parts._replace(query=urllib.parse.urlencode(query, doseq=True))
#print(parts)

url = urllib.parse.urlunparse(parts)
#print('--- url ---')
#print(url)

req = urllib.request.urlopen(url)
data = json.loads(req.read())
for number, item in enumerate(data['data']['productSearch']['products'], 1):
    print(number, '|', item['productName'])

Result:
1 | Água de Coco Tradicional Quadrado 200Ml
2 | Leite Longa Vida Integral com Tampa Italac 1L
3 | Leite Longa Vida Quatá  Integral 1L
4 | Água Mineral sem Gás Minalba 1,5L
5 | Água Mineral Sem Gás Minalba 510Ml
6 | Refrigerante Coca-Cola200Ml
7 | Leite Longa Vida Integral Shefa Garrafa 1L
8 | Refrigerante Coca-Cola sem Açúcar 1L
9 | Cerveja Heineken Lata 350Ml
10 | Leite Integral Longa Vida com Tampa Ninho 1L
11 | Leite Longa Vida Semidesnatado Com Tampa Italac 1L
12 | Cerveja Heineken Long Neck 330Ml
13 | Cerveja Amstel Lata 269Ml
14 | Água Mineral Minalba Com Gás 510Ml
15 | Água Mineral Pureza Vital Sem Gás Nestlé Pet 510Ml
16 | Água Mineral Sem Gás Bonafont 500Ml
17 | Refrigerante Coca-Cola sem Açúcar 200ml
18 | Água de Coco Kero Coco 1L
19 | Refrigerante Coca-Cola 2,5L
20 | Leite Longa Vida Desnatado com Tampa Italac 1L
21 | Refrigerante Coca-Cola Lata 350Ml
22 | Leite Longa Vida Integral Tirol 1L
23 | Água Mineral com Gás Pureza Vital 510ML
24 | Suco de Uva Integral Tinto Aurora 1,5L
25 | Achocolatado Toddynho 200Ml
26 | Refrigerante Coca-Cola sem Açúcar Lata 220ml
27 | Energético Red Bull Energy Drink 250Ml
28 | Água Mineral Sem Gás Pureza Vital Nestlé 1,5 L
29 | Suco Natural One Laranja 2L
30 | Refrigerante Coca-Cola 2L
31 | Cerveja Skol Lata 350Ml
32 | Refrigerante Coca-Cola 1L
33 | Suco De Maçã Yakult 200Ml
34 | Cerveja Império Puro Malte Lata 269Ml
35 | Refrigerante Guaraná Antarctica 2L
36 | Refrigerante Coca-Cola Lata 220Ml
37 | Leite Em Pó Integral Italac Sachê 400G
38 | Água Coco Puro Coco 200Ml
39 | Água Mineral Com Gás Crystal Pet 1,5 L
40 | Achocolatado sabor Chocolate Italakinho  200Ml
41 | Cerveja Duplo Malte Brahma Lata 350Ml
42 | Água Mineral Indaiá sem Gás 500Ml
43 | Refresco em Pó Sabor Laranja Tang 25G
44 | Água De Coco Puro Coco 1L
45 | Cerveja Budweiser Lata 269Ml
46 | Cerveja Skol Lata 269Ml
47 | Refresco em Pó Sabor Uva Tang 25G
48 | Refrigerante Guaraná Antarctica Lata 350Ml
49 | Cerveja Eisenbahn Pilsen Lata 350Ml
50 | Cerveja Itaipava Lata 350Ml
51 | Cerveja Itaipava Lata 269Ml
52 | Refrigerante Coca-Cola 600Ml
53 | Refrigerante Guaraná Antarctica 1,5L
54 | Cerveja Stella Artois Lata 269Ml
55 | Whisky Escocês Johnnie Walker Red Label 1L
56 | Refrigerante Coca-Cola sem Açúcar 2L
57 | Água Mineral sem Gás Crystal Pet 1,5 L
58 | Cerveja Amstel Lata 350Ml
59 | Cerveja Corona Extra Long Neck 330Ml
60 | Cerveja Stella Artois Long Neck 330Ml
61 | Água Mineral Sem Gás Bonafont 1,5 L
62 | Cerveja Puro Malte Petra Lata 350Ml
63 | Água de Coco Kero Coco 200Ml
64 | Cerveja Heineken Garrafa 600Ml
65 | Refrigerante de Laranja Sukita 2L
66 | Chopp De Vinho Draft 600Ml
67 | Refrigerante De Limão H2Oh! 500Ml
68 | Suco Natural de Uva e Maca One Ambiente 2L
69 | Refrigerante Dolly Guaraná 2L
70 | Energético Energy Monster Lata 473Ml
71 | Refresco em Pó Sabor Limão Tang 25g
72 | Suco De Laranja Integral Prat's 4 Ls
73 | Energético Red Bull Tropical Energy Drink  250Ml
74 | Refrigerante Limoneto H2Oh! Pet 500Ml
75 | Água Tônica Antarctica Zero 350Ml
76 | Água Mineral Sem Gás Minalba 10 Ls
77 | Vodka Red Smirnoff 998Ml
78 | Suco De Laranja Natural Xandô Garrafa 900Ml
79 | Energético Red Bull Melancia Energy Drink 250Ml
80 | Bebida Láctea de Proteína Zero Lactose sabor Chocolate YoPro 15G
81 | Água Verão Sense Lindoya 510ml
82 | Vodka Nacional Smirnoff Ice Red 269ml
83 | Whisky Escocês White Horse 8 Anos 1L
84 | Refrigerante Coca-Cola sem Açúcar 2,5L
85 | Refresco em Pó Sabor Maracujá Tang 25g
86 | Cerveja Império Puro Malte Lata 350Ml
87 | Vodka Ice Smirnoff 275Ml
88 | Cerveja Eisenbahn Pilsen Long Neck 355Ml
89 | Guaraná Com Açaí Natural Guaraviton Pet 500Ml
90 | Cerveja Budweiser Long Neck 330Ml
91 | Água Mineral Com Gás Pet Crystal 500Ml
92 | Água Tônica Antarctica Lata 350Ml
93 | Refrigerante Sabor Guaraná Mini Dolly Pet 350Ml
94 | Água Tônica Schweppes lata 350ml
95 | Cachaça 51 965Ml
96 | Cerveja Skol Lata 550Ml
97 | Refresco em Pó Sabor Abacaxi Tang 25g
98 | Cerveja Puro Malte Petra Lata 269Ml
99 | Cachaça Velho Barreiro 910Ml
100 | Refrigerante Fanta Laranja 2L


text:
Q: What is going on under the hood for Backbone's extend? I tried to look through the docs but couldn't find the source for Backbone's extend. Reading how underscore's extend works, it seems like when you do extend, you are returned the destination object with added properties -

extend_.extend(destination, *sources)  Copy all of the properties in
  the source objects over to the destination object, and return the
  destination object. It's in-order, so the last source will override
  properties of the same name in previous arguments.
_.extend({name: 'moe'}, {age: 50});
  => {name: 'moe', age: 50}

So, if Backbone is using this #extend method under the hood for Model#extend, then in the below, does that mean that Backbone's Model object just got more properties?
var Note = Backbone.Model.extend({

  initialize: function() { ... },

  author: function() { ... },

  coordinates: function() { ... },

  allowedToEdit: function(account) {
    return true;   }

});

If after making Note, I make a Book -
var Book = Backbone.Model.extend({

  initialize: function() { ... },

  coordinates: function() { ... },

  allowedToEdit: function(account) {
    return true;   }

});

Will book also have a author property that is left over from the make of the Note since that extend added the author property to the Backbone's Model object?


text:
Q: Scale DOWN to fit older iphones Here is a tricky question: I have developed an app in HTML 5 that uses, I know it is foolish and wrong, HARD-CODED values for image sizes and positions.  I sized it to work well on a fairly low resolution Android. All my images are 540X300.  This fits on an older droid and has room to spare on a more recent HTC and on a tablet it sits in the corner.
Attempting to publish this on the iPhone presents a challenge, because I find that only the newest iPhone 5 displays my app nicely.  The older phones (at least the simulators!) crop my app (well it is html!).
So I am wondering: Can I 'scale' my app DOWN to fit on an older iphone simply by applying some magic to the xib that I don't currently understand?  Is there another way?  Or should I just thank my stars that I can run on the iphone5?
Oh yeah. I am using Cordova/Phonegap.


text:
Q: Why does the browser change the value of the option in a  element? I have a  where the options are generated in php. The some of values include HTML special chars like & or like in this case Ø (danish Ø).
For some reason the browser changes value of the option, making it difficult to compare it to the same value passed to a simple compare function.
With option 1 selected ("Østrig") and passing "Østrig" to below countryFilter function, it will return false ??? And deugging it I can see that e.value is equal to "Østrig" and not the value I set it to in the HTML??
HTML:
<form>
  <select id='country' onchange='filter(false);'>
    <option value=''>* Alle *</option>
    <option value='Østrig'>Østrig</option>
    <option value='Argentina'>Argentina</option>
    <option value='Australien'>Australien</option>
...

JavaScript:
  function countryFilter(country)
  {
    var e = document.getElementById('country');
    if (e.value=='') return true;
    return e.value.localeCompare(country)==0;
  }

It makes sense that the displayed text is translated into & and Ø but the data in the value option should remain untouched.
If I change the options to be added dynamically in JavaScript iso php, then it works again, but then the displayed value is not translated :-/
1) Why does the browser (tested both Chrome and IE) mess with my data?
2) Is there a way to avoid this?

A: the content of value-attributes is defined as CDATA(http://www.w3.org/TR/html401/interact/forms.html#adef-value-OPTION).
For CDATA the documentation says:

CDATA is a sequence of characters from the document character set and
  may include character entities. User agents should interpret attribute
  values as follows:

*

*Replace character entities with characters,

*Ignore line feeds,

*Replace each carriage return or tab with a single space

That's what the browser does, he replaces the entities with characters.
You may e.g. use Østrig for the comparison, or when you want to use the string with entities parse the string before the comparision:
  function countryFilter(country){
    var e = document.getElementById('country'),
        n = document.createElement('span');
        n.innerHTML=country;
    if (e.value=='') return true;
    return e.value.localeCompare(n.textContent)==0;
  }


text:
Q: What are solutions and tradeoffs to maintain search result consistency in a web application Consider a web application with a custom search function that must display the results in a paged manner (twenty per page with up to hundreds of thousands of total results) and the ability to drill down to individual results that maintain next/previous links to navigate through the results.
Re-executing the search on each page request to get the appropriate results for that page of data can be too expensive (up to 15s per search).  Also, since the underlying data can change frequently (e.g. addition of new results), re-executing could cause the next/previous functionality to result in inconsistent behavior (e.g. the same results reappearing on a later page after having been viewed on an earlier page).
What options exist to ensure the search results can be viewed across multiple pages in a consistent manner, and what tradeoffs does each option have in terms of network, CPU, memory, and storage requirements?
EDIT: I thought caching the query search results was an obvious necessity.  The question is really asking about where to cache the result set and what tradeoffs might exist to each.  For example, storing the ids of the entities in the result set on the client, or storing the IDs of the entities themselves in the users session on the web server, or in a temporary table in the database.  I'm not looking specifically for a single solution as different scenarios may result in different approaches (and such a question would be more suited for stackoverflow.com rather than here), but more of a design comparison between the possible approaches.

A: It's very common for search engines to just redo searches to get to your 'page 2'.
Storing search results per user can quickly become a memory/data hoarding disaster. Pulling all results out of your search index and storing it can quickly ends up being slower then just re-querying to search per 'page'/view.
If you can delay indexing to a nightly job you might get around the problem of misalignment.
Some indexing components may also support 'index generations' when you can re-query a search specifying which generation of index to use. The output would be consistently the same and align.

A: Not sure what your underlying search engine store is, but 15s search results? Meh.
Not to minimize your concerns, but using packages such as Lucene and Solr can take most of these headaches away for you. Heck, even something like MongoDB could address these issues. They're built to handle these scenarios in a much more efficient manner.

A: One way you could accomplish this, depending on how much traffic you receive, would be to setup (if you don't already have it) Edge Side Includes with the query keyword and paging parameters being part of the URL.  That way additional queries on the same keywords won't even hit your application server.
You can configure the expiration time on the includes to determine how long you would want to cache your results for.  Another option would be to add a parameter to the URL that you can change in-application each time that you want to update your cache.

A: Make your searches immutable
Most of the potential problems you cite can be rendered immaterial by simply caching the results of a particular search.  In other words, do not re-run the search each time you display the next results page.
In a typical web application, a search function takes the form of a query result, where each page is delivered as it is needed, using some helper functions.  When you perform the search, you need to cache the results of the search somewhere, and deliver each page of the search as it is requested.
In the Microsoft .NET world, this would be done using Skip() and Take() functions on a Linq query.  The code might look something like this:
var searchResults = from tableToSearch
                    where myConditions
                    select someFieldsToDisplay;

var pageResults = searchResults.Skip((requestedPageNumber- 1) * resultsPerPage)
                               .Take(resultsPerPage)

So searchResults becomes the record set containing the results of your search, and pageResults contains the requested records from that search results for that particular page.
In most applications, the freshness of the search results is a non-issue, provided you make it clear to the user that, if they want results that are newer than two or three minutes old, they can simply perform a brand new search.

A: Trying alternative methods of searching or indexing to improve the search performance would be the first thing to try in such a situation.  But, since that doesn't directly answer the question, and it's been months with no complete answer, I'm going to do my best to answer this myself (making it community wiki since I'm sure this answer can still be improved).
We require the results of a query to be presented to the user over a span of multiple web pages and that the entire result set is consistent across pages.  As the original question implied and the edited question confirms, we know that the results of the initial search must be cached to ensure this consistency (freshness is less important than consistency). There are three main places in a web application where the results could be cached.
The first option is to cache the results in server memory.  In this case, the query is executed and the identifiers for all of the results is saved usually in a user-specific memory area like an ASP.NET's HttpSessionState or Java's HttpSession{1}.  The subset of identifiers for the required page of data is then pulled from this result set and used to load the actual data for return to the user's web browser.  As each new pages are requested, the same set of identifiers are used to pull the data for those additional pages.
The next option is to cache the results in the database or other persistent storage.  The resulting identifiers from executing the query are written back to the database into a temporary holding table that can be re-queried for each requested page to determine the identifiers of the entities that should be returned to the user's browser, followed by loads of the actual data.
The final option would be to package up the full list of search result identifiers and store them on the client.  When requesting additional pages, the client could send the entire list back to the server for processing to determine which result records to load and display.  With a slightly more heavy weight client (e.g. javascript, flash, etc.), the client itself could determine which result records are needed from their identifiers, request those from the server and update the display appropriately without needing to send the full list back to the server.
The tradeoffs here are mostly intuitive.  Storing in memory requires enough memory to store all active user's search results. There could be some challenges with multiple-concurrent searches by the same user (e.g. two browser windows open), but that could be resolved with a unique search identifier as a key to the results within memory (rather than keying just on the user identifier or using a fixed key in the user-specific session data store).  While probably the easiest to implement, this could be quickly problematic if there is no easy way to identify when a user is no longer active and their results can be removed from memory, or if the number of results the number of users could combine to exceed the available server memory.
Storing the results in the database adds some extra overhead in order to persist the results and re-query for the right identifiers, but that should be minimal.  Some sort of cleanup job would be required to purge outdated search results when users are no longer active and their results are no longer required.
Storing the results on the client eliminates much of the application infrastructure overhead inherent with the other options (memory and storage), but instead requires more bandwidth which may impact page load times to an unacceptable level (especially on the initial load of all the identifiers).  The server may still need to perform some additional work to ensure that the data requested by the client is valid and not a rogue client requesting arbitrary data it shouldn't have access to (this could likely be accomplished with encryption of the keys or cryptographically strong hashes to ensure data remains unmodified by the client)

{1} User sessions usually can be configured to be stored in a database instead of in server memory.  The first option is really dealing only with situations where the server's memory is used to store the results.  Otherwise, you're looking at the second option where the user's session is a more friendly layer on top of storing the data in the database (i.e. the second option.


text:
Q: select from two different table and display i have 2 different table named productlist and rsales
the ff data in productlist are
id|pcode|
1 |1220 |

and the ff data in rsales are

id|total|total_discount|
3 |500  |      50      |

my problem is that i want to select data from two different table which is productlist and rsales and display it horizontally. i tried everything but it display vertically. the result must be something like this
id|pcode|total|total_discount|
1 |1220 |500  |   50         |

this is my code so far but it only display data from single table
<?php
$con = mysql_connect("localhost","root","");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("inventory", $con);

$result = mysql_query("SELECT * FROM productlist");

while($row = mysql_fetch_array($result))
  {
echo '
';
echo ''.$row['pcode'].'	';
echo '
';
  }

mysql_close($con);
?>

A: Is the id difference between them offset by 2?If so,you can use Fluffeh answer like this:
select
 ffdata.pcode,
 rsales.total,
 rsales.total_discount
from
 ffdata
    join rsales
        on ffdata.id=rsales.id+2

A: You need to use a join in your SQL so that the data comes out in a single row in the results and is matched on the correct fields.
I wrote a lengthy Q&A about it a while back for just this sort of question which you will really do well to read, but in short, your query should look something like this:
select
    ffdata.pcode,
    rsales.total,
    rsales.total_discount
from
    ffdata
        join rsales
            on ffdata.id=rsales.id

This is assuming that you have a common key on the two tables that links the records.

A: there is no link between rsales and produclist but you can try like this, you will get all fileds from both the tables using this
$result = mysql_query("SELECT * FROM productlist,rsales");


text:
Q: pytest fixture yield list of dict throws "yield_fixture function has more than one 'yield':" I have defined a fixture like :
    @pytest.fixture
    def mock_yield_data(self):
        for data in [
            {
                1: 2, 2: 3
            },
            {
                2: 4, 4: 5
            },
        ]:
            yield data

and a test method like :
    def test_fixture(self, mock_yield_data):
        for data in mock_yield_data:
            assert data

The assert is successful but the teardown throws, yield_fixture function has more than one 'yield':.
==================================================================================================== ERRORS ====================================================================================================
_________________________________________________________________________ ERROR at teardown of TestClass.test_fixture _________________________________________________________________________
yield_fixture function has more than one 'yield':

A: Your fixture may only have one yield. However, you may pass in parameters to the fixture, which will run the fixture for each parameter.
all_data = [
    {
        1: 2, 2: 3
    },
    {
        2: 4, 4: 5
    }
]

@pytest.fixture(params=all_data)
def mock_yield_data(self, request):
    yield request.param

A: In the last section of the pytest.yieldfixture documentation:

*

*usually yield is used for producing multiple values. But fixture functions can only yield exactly one value. Yielding a second fixture value will get you an error. It's possible we can evolve pytest to allow for producing multiple values as an alternative to current parametrization. For now, you can just use the normal fixture parametrization mechanisms together with yield-style fixtures.

With a memory footprint that small, you should just return the entire thing:
@pytest.fixture
def mock_yield_data(self):
    return [
        {
            1: 2, 2: 3
        },
        {
            2: 4, 4: 5
        },
    ]


text:
Q: css width interval Ok, here's a problem I've never run into before. I would like to use CSS to specify that an elements width should always be in 10 pixel intervals. So, for example, if the width of an element is 11, it would get bumped up to 20, 56 => 60, 138 => 140, etc...
I doubt CSS has a way to do this but thought I'd ask anyway. Something like this would be nice:
div { width-interval: 10px; }

A: The problem with this is that block-level elements are always the size of the window unless you specify otherwise. Once you specify a more specific width, you don't need a width inverval.
The two cases this would be different are;

*

*If the block level element is shrink wrapped (in the case of floats and inline-blocks)

*If the element has a relative width, ie a percentage.
But if you are setting it to be relative, you wouldn't need intervals, because it's supposed to be relative to other things on the page, so that would get complicated when other things had to be adjusted to compensate. For instance, if I had two divs:

and a rule:
#one {
width: 50%;
width-interval: 25px;
}

#two {
width: 50%;
width-interval: 27px;
}

Which one wins? If it's important for lining up pictures or text, you probably don't want either to trump the other, but it can't ignore both.
I think the idea is good, but would probably be better handled by javascript, since you are requiring it to be both dynamic and based on the "nearest" interval. This could work:
$(function () {

$(div).each(function() {
    var cur_width = $(this).width();
    var inverval_diff = cur_width % 10;
    $(this).width(cur_width + inverval_diff);
});

});

The above is in jquery, in case you don't use that as your js framework.

A: css doesn't have such property, but you are able to style width of elements with additional JavaScript such as:

Hope it helps.


text:
Q: I have a data type problem in the text classification problem I want to build deep learning classifiers for Kickstarter campaign prediction. I have a problem with the part of the model but I can not solve this.
My code:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from keras.models import Sequential
from keras import layers

df = pd.read_csv('../input/kickstarter-campaigns-dataset/kickstarter_data_full.csv')

df_X = [] # for x class
df_y = [] # for labels

for i in range(len(df)):
    tmp = str(df['blurb'][i]) + " " + str(df['goal'][i]) + " " + str(df['pledged'][i]) + " " + str(df['country'][i]) + " " + str(df['currency'][i]) + " " + str(df['category'][i]) + " " + str(df['spotlight'][i])
    df_X.append(tmp)
    df_y.append(str(df['SuccessfulBool'][i]))

X_train, X_test, y_train, y_test = train_test_split(df_X, df_y, test_size=0.25, random_state=1000)
vectorizer = CountVectorizer()
vectorizer.fit(X_train)

X_train = vectorizer.transform(X_train)
X_test  = vectorizer.transform(X_test)

input_dim = X_train.shape[1]

model = Sequential()
model.add(layers.Dense(10, input_dim=input_dim, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy'])
model.summary()

history = model.fit(X_train, y_train,
                     epochs=100,
                     verbose=False,
                     validation_data=(X_test, y_test),
                     batch_size=10)

In this point, I am getting ValueError: Failed to find data adapter that can handle input: <class 'scipy.sparse.csr.csr_matrix'>, (<class 'list'> containing values of types {"<class 'str'>"})
I try np.asarray for solving
X_train = np.asarray(X_train)
y_train = np.asarray(y_train)
X_test = np.asarray(X_test)
y_test = np.asarray(y_test)

I get this ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type csr_matrix).
Therefore, I use this:
np.asarray(X_train).astype(np.float32)
np.asarray(y_train).astype(np.float32)
np.asarray(X_test).astype(np.float32)
np.asarray(y_test).astype(np.float32)

But I get ValueError: setting an array element with a sequence.
I try this:
X_train = np.expand_dims(X_train, -1)
y_train   = np.expand_dims(y_train, -1)
X_test = np.expand_dims(X_test, -1)
y_test   = np.expand_dims(y_test, -1)

But I keep getting the same error in the part of history. ValueError: Failed to convert a NumPy array to a Tensor (Unsupported object type csr_matrix).
I study with Kickstarter Campaigns Dataset at the Kaggle.
https://www.kaggle.com/sripaadsrinivasan/kickstarter-campaigns-dataset
I don't have enough NLP information. I search and try solvings but I can not solve. This is my homework. Can you help me for this problem?
df_X and df_y are equal sizes and their output is as follows:
x
y

A: you need to add an embedding layer at the top of your NN to kind of vectorize words. something like this:
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from keras.preprocessing.text import one_hot
from keras.preprocessing.sequence import pad_sequences
from keras.models import Sequential
from keras import layers

df = pd.read_csv('../input/kickstarter-campaigns-dataset/kickstarter_data_full.csv')

df_X = [] # for x class
df_y = [] # for labels

for i in range(len(df)):
    tmp = str(df['blurb'][i]) + " " + str(df['goal'][i]) + " " + str(df['pledged'][i]) + " " + str(df['country'][i]) + " " + str(df['currency'][i]) + " " + str(df['category'][i]) + " " + str(df['spotlight'][i])
    df_X.append(tmp)
    df_y.append(str(df['SuccessfulBool'][i]))

vocab_size = 1000
encoded_docs = [one_hot(d, vocab_size) for d in df_X]
max_length = 20
padded_docs = pad_sequences(encoded_docs, maxlen=max_length, padding='post')
X_train, X_test, y_train, y_test = train_test_split(padded_docs, np.array(df_y)[:, None].astype(int), test_size=0.25, random_state=1000)
model = Sequential()
model.add(layers.Embedding(vocab_size, 100, input_length=max_length))
model.add(layers.Flatten())
model.add(layers.Dense(10, activation='relu'))
model.add(layers.Dense(1, activation='sigmoid'))

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])
print(model.summary())
model.fit(X_train, y_train,
          epochs=50,
          verbose=1,
          validation_data=(X_test, y_test),
          batch_size=10)


text:
Q: - (BOOL)ccTouchBegan responds on simulator but not on device I am working on a Pause screen menu for a game. After displaying the pause screen, I have the user touch the screen to hide the pause screen and resume the game. This works perfect on the simulator but doesn't work when I test on an actual device. It seems that the device doesn't respond to touches specifically for the pause menu. Every other part of the game works fine on both the simulator and device. It's weird how it does work on the simulator but not on the device. This is the code I have for the pause screen:
- (id)init {
if ((self = [super init])) {

    CGSize windowSize = [[CCDirector sharedDirector] winSize];
    //windowSize.height = 768.0;
    //windowSize.width = 1024.0;

    CCSprite *whiteScreen = [CCSprite spriteWithFile:@"OutOfTime.png"];
    whiteScreen.position = ccp(windowSize.width / 2, windowSize.height / 2);
    [self addChild:whiteScreen];

    CCLabelTTF *touchToDismiss = [CCLabelTTF labelWithString:@"Touch screen to continue"     fontName:@"Marker Felt" fontSize:30];
    touchToDismiss.color = ccBLACK;

    touchToDismiss.position = ccp(windowSize.width / 2, 20);
    [self addChild:touchToDismiss];
    }

    return self;
}

- (void)onEnter {
    [super onEnter];
    [[CCTouchDispatcher sharedDispatcher] addTargetedDelegate:self priority:0 swallowsTouches:NO];
}

- (void)gameOverWithScore:(NSInteger)score {
    CGSize windowSize = [[CCDirector sharedDirector] winSize];
    //windowSize.height = 768.0;
    //windowSize.width = 1024.0;

    CCLabelTTF *touchToDismiss = [CCLabelTTF labelWithString:@"Game Over" fontName:@"Marker Felt" fontSize:75];
    touchToDismiss.color = ccBLACK;
    touchToDismiss.position = ccp(windowSize.width / 2, windowSize.height / 2 + 40);
    [self addChild:touchToDismiss];

    NSString *scoreString = [NSString stringWithFormat:@"Final Score: %d", score];
    CCLabelTTF *scoreLabel = [CCLabelTTF labelWithString:scoreString fontName:@"Marker Felt" fontSize:60];
    scoreLabel.color = ccBLACK;
    scoreLabel.position = ccp(windowSize.width / 2, (windowSize.height / 2) - 40);
    [self addChild:scoreLabel];
}

- (void)setMessage:(NSString *)message {

}

- (void)dealloc {
    [super dealloc];
}

- (BOOL)ccTouchBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    NSLog(@"haha");
    return YES;
}

A: You probably should add the following line on your init
self.isTouchEnabled = YES;

You have to do this for every CCLayer you have that has touch events.
EDIT: just noticed that your ccTouchBegan only prints a Log.
This log is easily viewed in the debug window of XCode, but in the device it is hidden from the user.
Try doing something else.


text:
Q: Approximate inverse matrix Does a method exist to calculate the approximate inverse matrix for a matrix whose elements are small?
To be clearer, let's suppose the elements of the matrix $A$ to be function of a small parameter, i.e. $a_{ij} = a_{ij} (\epsilon)$. Is it possible to obtain the elements of the inverse $A^{-1}$ avoiding to calculate it before and then to study the limit for $\epsilon \rightarrow0$.
For example could we expand the inverse in a series of $\epsilon$ whose terms can be calculated from $A$?

A: It is in general difficult to compute the inverse of a matrix $A$ when the entries $a_{ij}$ are all near $0$, since the matrix inverse function $A \to A^{-1}$ is so badly behaved as $A \to 0$.  When $A$ is near $0$, $A^{-1}$ becomes very large, giving rise to computational instabilities.  This can even be seen when $A$ is $1 \times 1$, by looking at the derivative of the map $x \to x^{-1}$:  if $x$ is a function of some parameter $\epsilon$, $x = x(\epsilon)$, then we have
$\frac{dx^{-1}(\epsilon)}{d\epsilon} = -x^{-2}\frac{dx(\epsilon)}{d\epsilon}$,
showing that $\frac{dx^{-1}(\epsilon)}{d\epsilon}$ can become very large even when $\frac{dx(\epsilon)}{d\epsilon}$ is small.  This situation gives rise to numerical errors which become amplified by a factor of $\frac{1}{x^2}$, often severely degrading the accuracy, hence the utility, of approximation methods for $x$ near $0$.  And basically the same thing happens with matrices.  If $A(\epsilon)$ is a parametrized family of matrices, differentiable in $\epsilon$, then we may write
$A^{-1}(\epsilon)A(\epsilon) =  I$,
and taking $\epsilon$-derivatives yields
$\frac{dA^{-1}(\epsilon)}{d\epsilon}A(\epsilon) + A^{-1}(\epsilon)\frac{dA(\epsilon)}{d\epsilon} = 0$,
from which it follows that
$\frac{dA^{-1}(\epsilon)}{d\epsilon} = -A^{-1}(\epsilon)\frac{dA(\epsilon)}{d\epsilon}A^{-1}(\epsilon)$,
and this equation shows that errors in $A(\epsilon)$, as estimated by $\frac{dA(\epsilon)}{d\epsilon}$ via first-order expansion
$A(\epsilon + \Delta \epsilon) \approx A(\epsilon) + \frac{dA(\epsilon)}{d\epsilon}(\Delta \epsilon)$,
will also be subject to a potentially very large "magnification factor" of magnitude roughly
$\vert A^{-1} \vert^2$, where $\vert A^{-1} \vert$ denotes your favorite matrix norm applied to $A^{-1}$:
$A^{-1}(\epsilon + \Delta \epsilon) \approx A^{-1}(\epsilon) + \frac{dA^{-1}(\epsilon)}{d\epsilon}\Delta \epsilon = A^{-1}(\epsilon) - A^{-1}(\epsilon)\frac{dA(\epsilon)}{d\epsilon}A^{-1}(\epsilon)\Delta \epsilon$,
whence
$\vert A^{-1}(\epsilon + \Delta \epsilon) -  A^{-1}(\epsilon) \vert \approx \vert A^{-1}(\epsilon)\frac{dA(\epsilon)}{d\epsilon}A^{-1}(\epsilon)\Delta \epsilon \vert \approx \vert A^{-1} \vert^2 \vert \frac{dA(\epsilon)}{d\epsilon}\Delta \epsilon \vert$.
For these reasons and other, similar ones, people try to avoid computing $A^{-1}$ when
$\vert A \vert$, hence $A$, is small.  What is done, however, is to compute approximations to $A^{-1}(\epsilon)$ when some of the entries of $A(\epsilon)$ are small.  For example, if we know $A^{-1}(0)$ and we have
$A(\epsilon) = A(0) + (\Delta A)(\epsilon) = A(0)(I + A^{-1}(0)(\Delta A (\epsilon)))$
with
$\vert  A^{-1}(0)(\Delta A (\epsilon)) \vert < 1$,
we can in fact exploit the Neumann series mentioned by Hagen von Eitzen in this comment and 40 votes in his answer to obtain, using the notation $D(\epsilon) =  A^{-1}(0)(\Delta A (\epsilon))$,
$A^{-1}(\epsilon) = (I + D(\epsilon))^{-1}A^{-1}(0) = (I - D(\epsilon) + D^2(\epsilon) - D^3(\epsilon) + . . . )A^{-1}(0)$,
which avoids direct computation of $A^{-1}(\epsilon)$ but replaces it with computing the powers $D^i(\epsilon)$ of $D(\epsilon)$.  This expression will presumably boil down to a power series in $\epsilon$ if $D(\epsilon)$ is sufficiently nice as a function of $\epsilon$, e.g., if $D(\epsilon)$ is analytic in $\epsilon$.
Finally, in your case
$A(\epsilon) = \frac{1}{\epsilon^2}(I - B(\epsilon))$,
you are fortunate in so far as the factor $\frac{1}{\epsilon^2}$ is a scalar and can be "pulled out in front" of the matrices.  Thus all you have to do is evaluate the series for
$(I - B(\epsilon))^{-1} = (I + B(\epsilon) + B^2(\epsilon) + B^3(\epsilon) + . . . )$
and multiply the final result by $\frac{1}{\epsilon^2}$.  Care must be taken, however, to compute a sufficient number of terms of the above Neumann series for $(I - B(\epsilon))^{-1}$ that a relatively high degree of convergence is obtained; otherwise, when you multiply by $\frac{1}{\epsilon^2}$ introduction of severe inaccuracies may occur, as I have (hopefully) explained in the above.
Hope this helps.  Cheers.

A: The comment by Hagen von Eitzen refers to Neumann series for the inverse. With $A=\epsilon^{-2}(I-B(\epsilon)$) it takes the form
$$A^{-1}=\epsilon^2 (I+B(\epsilon)+B(\epsilon)^2+B(\epsilon)^3+\dots) \tag1$$
A sufficient condition for the convergence of (1) is $\|B(\epsilon)\|<1$.
The necessary and sufficient condition for the convergence of (1) is $\rho(B(\epsilon))<1$, where $\rho$ is the spectral radius.


text:
Q: Text wrap nightmare in PHP after PREG_REPLACE Provinces is a group_concat of all the individual records that contain province, some of which are blank.
So, when I encode:

$provinces = ($row['provinces']);

echo "".wordwrap($provinces, 35, "
")."	";

This is what the result looks like:

Minas Gerais,,,Rio Grande do
Sul,Santa Catarina,Paraná,São Paulo

However, when I try to preg_replace out some of the nulls, and add some spaces with this expression:

$provinces = preg_replace($patterns,
  $replaces, ($row['provinces']));

echo "".wordwrap($provinces, 35, "
")."	";`

This is what I get!!! :(

Minas Gerais, Rio Grande do
Sul, Santa
Catarina, Paraná, São Paulo

The output is very unnatural looking.
BTW: Here are the search and replace arrays:
$patterns[0] = '/,,([,]+)?/';       $replaces[0] = ', ';
$patterns[1] = '/^,/';              $replaces[1] = '';
$patterns[2] = '/,$/';              $replaces[2] = '';
$patterns[3] = '/\b,\b/';           $replaces[3] = ', ';
$patterns[4] = '/\s,/';             $replaces[4] = ', ';

UPDATE: I even tried to change Paraná to Parana

Minas Gerais, Rio Grande do
Sul, Santa
Catarina, Parana, São
Paulo

A: Don't use   as the replacement. wordwrap() considers that 6 characters. It doesn't interpret the HTML entity. That's why your lines are breaking funny. If you want   replace spaces after you wordwrap()
Also, your first pattern should be:
// match one or more commas together
$patterns[0] = '/,+/';

A: Is the wordwrap() really necessary? It sounds like you are rendering this content into a table cell of some fixed width and you don't want individual entries to split across lines.
If this inference is correct - and if none of your entries is actually so long that forcing it to a single line will break your layout - then how about this: explode() on commas into an array, remove the whitespace-only entries, replace normal spaces in each array entry with  , and implode() back on , (a comma followed by a space). Then let the rendering browser break lines wherever it needs.


text:
Q: Is there a notion analogous to separability but requiring definable rather than countable sets? Among models of $\lambda$-calculus, some like the Bohm tree model have the property that every element is a directed sup of definable elements, whereas others like the $D_\infty$ and $P(\omega)$ models contain "extra" elements (e.g. step functions) that are not sups of sets of $\lambda$-definable elements.
Among models of the real numbers, standard models have the property that every element is a sup of a set of rational (0,1,+,-,*,/-definable) points, whereas nonstandard models can contain "extra"  elements like infinitesimals.
Does this property have a common name? A model is ___ if every element is a sup of a set of definable elements, for a give notion of definability.
Related properties of similar grammatical form:

*

*separability of a metric space

*algebraicity of a continuous lattice

*completeness of a partial order or semilattice

*standardness of a model of the reals

*full-abstraction of model of a programming language


text:
Q: How to add custom items to QFileDialog? I am using non-native QFileDialog (for choosing directory path) and I need to add some custom drives. I don't even need to display any content inside of these drives for now, I just need to display these drives on the top level (and preferably with my icon) and output some special string in the result when user selects it.

What is the easiest way to implement this?
I have read in the documentation that proxy model can be used for that, but I don't understand how to implement such model, all examples show only filtering and sorting of the already available items.

A: If I understand you correctly, you want to add additional drives to the side bar on the left side of the file dialog?
The function you are looking for is QFileDialog::setSidebarUrls
#include <QApplication>
#include <QMainWindow>
#include <QHBoxLayout>
#include <QPushButton>
#include <QFileDialog>

int main(int argc, char** argv)
{
    QApplication app(argc, argv);
    QMainWindow window;

    QWidget widget;
    QHBoxLayout layout(&widget);

    QPushButton open("open");
    layout.addWidget(&open);

    QObject::connect(&open, &QPushButton::clicked, [&]()
        {
            QFileDialog dialog;
            dialog.setOption(QFileDialog::DontUseNativeDialog);

            QList<QUrl> drives;
            drives << QUrl::fromLocalFile(QDir("D:").absolutePath());
            drives << QUrl::fromLocalFile(QDir("E:").absolutePath());
            drives << QUrl::fromLocalFile(QDir("foobar").absolutePath());
            dialog.setSidebarUrls(drives);

            dialog.exec();
        });

    window.setCentralWidget(&widget);
    window.show();
    return app.exec();
}

The result of this is shown below:

If, however, the drives you've added don't exist / aren't accessible, then they will be shown greyed out.

A: General Information
You are right that you need to set a proxy model.
Basically your task is to add a row with a QAbstractProxyModel. This is quite a bit more difficult than removing rows.
If we look at the source code of QFileDialog::setProxyModel, we find this:
proxyModel->setParent(this);
d->proxyModel = proxyModel;
proxyModel->setSourceModel(d->model);

From this we know that QFileDialoghas an internal model which is automatically set as the source of the proxy model. Looking in the private header, we find that the source model's type is QFileSystemModel. We can therefore expect that our proxy model needs to be able to supply the same roles as the source model. The docs has a list of them: FileIconRole, FileNameRole, FilePathRole, FilePermissionRole.
To make matters worse, QFileDialog sometimes calls proxyModel.mapToSource() and proxyModel.mapFromSource() to access the source index. Because we want to add a row, our new indexes have no corresponding source index (in the source model). This means we have to write our own implementation of mapToSource and mapFromSource.
Implementation
I would suggest starting from a QIdentityProxyModel because you can use the available methods for all indexes you just pass to the source model.
I don't know exactly how many methods you need to re-implement and how often you can just use the ones provided by QIdentityProxyModel. Start with the easy stuff:
int MyDriveProxyModel::rowCount(const QModelIndex &parent = QModelIndex()) const {
    if (parent.isValid()) {
        return QIdentityProxyModel::rowCount(parent);
    } else {
        return QIdentityProxyModel::rowCount(parent) + 1;
    }
}

and then re-implement the two mapping methods:
QModelIndex MyDriveProxyModel::mapToSource(const QModelIndex &proxyIndex) const {
    if (this_index_belongs_to_the_added_row) { // there are many ways for this
        return this->createIndex(proxyIndex.row(), proxyIndex.column(), /* some_data */);
    }
    return QIdentityProxyModel::mapToSource(proxyIndex);
}

QModelIndex MyDriveProxyModel::mapFromSource(const QModelIndex &proxyIndex) const {
    ...
}

Once this works, you need to do implement at least QAbstractItemModel::data and QAbstractItemModel::flags in a similar manner.
Conclusion
It should be doable but is quite a bit of work where it's very easy to make mistakes. What Qt really seems to need is a way to combine multiple models into one, but I haven't seen such a class yet and therefore you'll have to do this the hard way.


text:
Q: CodeIgniter Passing POST data from RestClient to RestServer API I've spent my whole day trying to figure out this problem. Posting this issue here is my last hope. I hope someone can help to continue working on my first job.
So, POST works fine when directly passing data from my views to the RestServer directly. However, RESTServer API is not able to find POSTs data sent from the RestClient.
Here are the snippets:
RestClient API:

        $ver = 'v1';
        $config = array('server'          => base_url()."v1",
                        'api_key'         => 'xxxxxx',
                        'api_name'        => 'X-API-KEY',
                        'http_user'       => 'admin',
                        'http_pass'       => 'xxxxx',
                        'http_auth'       => 'basic',
                );

        $this->rest->initialize($config);
        $this->rest->format('application/json');
        $param = array(
                'id' => $this->input->post('id'), // works fine here
                'name' => $this->input->post('name')
                );
        $user = $this->rest->post('employer/postNewProject', $param, 'json');

        //if (isset($user->errors)) show_404('admin');
        $this->rest->debug();

RestServer API
class Employer extends REST_Controller
{
    public function __construct()
    {
        parent::__construct();
        $this->lang->load("application");
        $this->load->library("users/auth");
        Datamapper::add_model_path( array( APPPATH."modules" ) );
    }

    public function postNewProject_post()
    {
        // I tired $this->post() and $this->input->post() but both not finding the data
        $message = array("id" => $this->post("id"), "name" => $this->input->post("name"));
        $this->response($message, 200); // 200 being the HTTP response code
    }
}

Results:
Response when using $this->post('id');
{"id":false}

Response when using $this->post();
{"id":[]}

Note: I've replaced the POSTS requests with hardcoded data, and still the RestServer is not able to recieve the data from my RestClient.
If you need me to provide anything else, please ask.
Thank you in advance.

A: i figure out when and empty 3rd perameter is passed(or when you remove 3rd param) then it works.
    //Not working
    $user = $this->rest->post('employer/postNewProject', $param, 'json');
    //when i change to this ,it's working
     $user = $this->rest->post('employer/postNewProject', $param.'');
     //or
    $user = $this->rest->post('employer/postNewProject', $param);

if some one has a better solution so that i can award bounty.

A: Use this method to send Rest client data to rest server using post method. Read comment on every line
// initialize you setting
     $config = array('server' => base_url() . "v1",
            'api_key' => 'xxxxxx',
            'api_name' => 'X-API-KEY',
            'http_user' => 'admin',
            'http_pass' => 'xxxxx',
            'http_auth' => 'basic',
        );
        $this->rest->initialize($config);
// Set method of sending data

        $method = 'post';
// create your param data

        $param = array(
            'id' => $this->input->post('id'), // works fine here
            'name' => $this->input->post('name')
        );
// url where you want to send your param data.

        $uri = 'employer/postNewProject';
        // set format you sending data
        $this->rest->format('application/json');

// send your param data to given url using this

        $result = $this->rest->{$method}($uri, $params);

//code for your controller employer/postNewProject
Controller
function postNewProject()
{
    $data=array(
        'id' => $this->post('id'),
        'name' => $this->post('name')
        );
      print_r($data);
}

A: make sure you receive data, use
 echo '
 all data received: '.print_r($_REQUEST,1).'
';

make sure is from post
echo '
 post data: '.print_r($_POST,1).'
';

A:
Content type application/x-www-form-urlencoded used for post method

 $param = array(
            'id' => $this->input->post('id'), // works fine here
            'name' => $this->input->post('name')
            );

 $user = $this->rest->post('employer/postNewProject', $param, 'application/x-www-form-urlencoded');

Content type json for post method
      RestServer API will be changed for post

public function postNewProject_post()
{
   $entity = file_get_contents('php://input', 'r');
   print_r($entity);
}

A: On your RestServer API, it won't have access to POST data,  the POST data from RestClient API is passed into RestServer API via $param array, and RestServer API receives that array.  In RestServer API you should be able to access those values via the $param array assuming the RestServer API functions consume the $param array and passes it thru.


text:
Q: Android microphone sensitivity change after phone call My application is measuring volume of captured audio as a function of  samples absolute amplitude.
I've noticed and unexpected behavior in android.media.AudioRecord of Android SDK. Let's assume following flow:

*

*Application is launched

*Audio volume is being measured

*Phone call is answered/dialed

*Audio volume is being measured

The noise around the microphone is produced by TV with constant volume setting. Values measured for point 2 are in range [55-65] and values measured for point 4 are in range [15-25] (please see the audio visualization for 2. and 4. below).
I understand that there must be some volume adjustment going on when phone call occurs. Is it possible to monitor those adjustments or to get rid of them?
I've tried AutomaticGainControl but it is not supported on my Nexus 5 and I do not want to use it since the target devices might not support it as well.
Update
This volume adjustment is happening not only after phone call. I've just noticed the same behavior when phone was just lying on the table measuring volume.

A: In regard to resources that your app is sharing with other apps (the microphone in this matter) - you should always treat them carefully and assume there configuration may change during a phone call or other usage like switching to another app that's using the microphone.
Instead of trying to monitor for changes in gain , which may require root or other elevated privileges - I would take another approach and do the following:

*

*Save the mic sensitivity level to a configuration file (shared_prefs) in your recording activity when the user is recording . do the same if the user changes it of course during usage of your app.

*In the onResume proc of your recording activity - load the mic sensitivity  level value and set it before continuing to record (How to adjust microphone sensitivity while recording audio in android - Solved)

If there is a phone call that throws your app to the background and takes control of the mic, once it's finished - your app will return to the foreground and retain the mic sensitivity level for further recording.
Hope this helps.


text:
Q: Debug Tests in NG Test I am using Angular CLI and VSCode but none of my breakpoints in my spec files seem to be getting hit when I run ng test?
Do I need to do some config?

A: Update for Angular version 9
The source files have been moved but you can still debug this way if you do the following steps

*

*In devtools, select the sources tab

*Press CTRL + P

*Type in the name of the file you want to debug

Valid for versions below 9
The other answers are completely valid answers but having been using Angular for around 18 months now I tend to do it in the browser - chrome tools!
Run ng test then f12 and find the spec file via the webpack context. Add a breakpoint(s) and refresh and it will hit said breakpoints. As per screenshot

A: Just to add to the other answers:

*

*Follow the instructions @titusfx mentioned.

*In the terminal run ng test.

*In Visual Studio Code debug view select ng test from the drop down.

*you might need to refresh the browser if cannot hit the break points the first time.

A: This is what worked for me with:

*

*Angular 9.0.6 + Visual Studio Code 1.43.2

*Angular 8.2.13 + Visual Studio Code 1.39.2

*Angular 7, Angular CLI 1.0.* and Chrome on Windows 7.

Change configuration files
In your project root directory open karma.conf.js. Right after singleRun: false add , followed by this section:
    customLaunchers: {
      ChromeDebug: {
        base: 'Chrome',
        flags: [ '--remote-debugging-port=9333' ]
      }
    }

Add configuration to .vscode/launch.json.

*

*For versions 8.* - 9.* (note "pathMapping section!):
{
  "type": "chrome",
  "request": "attach",
  "name": "Unit tests",
  "address": "localhost",
  "port": 9333,
  "sourceMaps": true,
  "webRoot": "${workspaceFolder}",
  "pathMapping": {
    "/_karma_webpack_": "${workspaceFolder}"
  }
},

*For version 7.*:
{
  "type": "chrome",
  "request": "attach",
  "name": "Unit tests",
  "address": "localhost",
  "port": 9333,
  "sourceMaps": true,
  "webRoot": "${workspaceFolder}"
},

Start debugging

*

*Run ng test --browsers ChromeDebug

*Wait for Chrome browser to start. You will see something like this in command line:
01 06 2017 16:07:29.276:INFO [launcher]: Launching browser ChromeDebug with unlimited concurrency

*Set the breakpoint in one of your .spec.ts files.

*In Visual Studio Code choose Unit tests debug configuration and hit F5 ("Start Debugging" button).

*Press Shift+Ctrl+F5 or refresh the Chrome window to rerun the tests and hit the breakpoint.

For convenience
You can also modify your package.json and add a new script:
"test-debug": "ng test --browsers ChromeDebug",

Then next time you want to start ng test with debugging just run:
npm run test-debug

References:

*

*Debugging Jasmine Unit tests running with Karma runner in VS Code

*Debugging Karma tests with VSCode

*Angular CLI 8.1.3 Debug Unit Tests configuration - Unverified breakpoint

*microsoft/vscode-recipes - Chrome Debugging with Angular CLI

A: In the new release of VSCode (1.14.0) they follow this recipe:
You can debug the Angular App entirely ( including the unit tests ), the recipe is straightforward.

A: You can simply add a 'debugger'
where you want to debug and run
ng test

When the chrome browser opens, turn on the dev tools and it will stop on your 'debugger'


text:
Q: ASP.net mvc Remote Validation, is it secure? How to secure? I recently came across Remote Validation in asp.net mvc.  Really helpful feature but doesn't adding something like this to a registration form, say to check for username or email, open up a security hole?  Couldn't someone use this to mine information from the site?  Captca would be an obvious solution to this problem, but has anyone been able to integrate it with the [Remote] validation?
public class CreateUserModel : EditUserModel {
    [Required]
    [StringLength(6, MinimumLength = 3)]
    [Remote("IsUID_Available", "Validation")]
    [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")]
    [Editable(true)]
    public override string UserName { get; set; }
}

A: You could use a Captcha if you want. For example with Google's ReCaptcha you could install the  microsoft-web-helpers NuGet, sign up for a ReCaptcha account in order to obtain your private/public key pairs and then simply modify your view model so that when you perform the remote call the 2 additional fields are included:
public class CreateUserModel : EditUserModel
{
    [Required]
    [StringLength(6, MinimumLength = 3)]
    [Remote("IsUID_Available", "Validation", AdditionalFields = "recaptcha_response_field,recaptcha_challenge_field", HttpMethod = "POST")]
    [RegularExpression(@"(\S)+", ErrorMessage = "White space is not allowed.")]
    [Editable(true)]
    public override string UserName { get; set; }
}

and in the view:
@using Microsoft.Web.Helpers
@model CreateUserModel
@{
    ReCaptcha.PublicKey = "... public key obtained from Google ...";
}

<script src="@Url.Content("~/Scripts/jquery.validate.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.js")" type="text/javascript"></script>

@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.UserName)
    @Html.ValidationMessageFor(x => x.UserName)
    @ReCaptcha.GetHtml(theme: "red")
    <button type="submit">OK</button>
}

and in the controller:
[HttpPost]
public ActionResult IsUID_Available(string username)
{
    if (!ReCaptcha.Validate(privateKey: "... private key obtained from Google ..."))
    {
        return Json("sorry, please enter a correct Captcha first");
    }

    // TODO: the user entered a correct Captcha => you can proceed
    // into usrname existence verification:
    bool userExists = _repository.UserExists(username);
    return Json(userExists);
}


text:
Q: Double Free Detected in C When Deallocating a String Struct Whenever I run the testing code for my programming, it terminates with this message:

free(): double free detected in tcache 2

Going into gdb and using the 'backtrace' command lets me know that the issue is my String_Dispose function.

(#5  0x000000000040131c in String_Dispose (ppStr=0x7fffffffdee0) at
String.c:225)

This is my code for the String_Dipose function:
/**  Deallocates a String object and all its content.
 *
 *   Pre:
 *     *ppStr is a pointer to a proper String object, so
 *     **ppStr is a proper String object
 *     **ppStr was allocated dynamically
 *   Post:
 *     (**ppStr).data has been deallocated
 *     **ppStr has been deallocated
 *     *ppStr == NULL
 */
void String_Dispose(String** ppStr) {

    ///  Implement this function!!  ///
    free((**ppStr).pData);
    free(*ppStr);

    *ppStr = NULL;
}

This is what a call to the function would look like in practice:
String *pStr = String_Create("And as we wind on down the road...", 34);
. . .
// Initialize the String and use it until we're done with it.
. . .
String_Dispose(&pStr);
// At this point, every trace of the String object is gone and pStr == NULL

Here is the rest of the code for context, I'm not sure if it's correct (it's also unfinished) but the main issue here is String_Dipose.
#include "String.h"
#include <stdlib.h>
#include <assert.h>
#include <stdio.h>

/** The String is initialized to hold the values in *src.
 *
 *  Pre:
 *    *pSrc is C string with length up to slength (excludes null char)
 *  Post on success:
 *    A new, proper String object S is created such that:
 *       S.pData != pSrc->pData
 *       Up to slength characters in *pSrc are copied into dest->data
 *         (after dynamic allocation) and the new string is terminated
 *         with a '\0'
 *       S.length is set to the number of characters copied from *pSrc;
 *         this is no more than slength, but will be less if a '\0' is
 *         encountered in *pSrc before slength chars have occurred
 * Post on failure:
 *    NULL is returned
 *
 * Returns:
 *    pointer to the new String object;
 *    NULL value if some error occurs
 */
String* String_Create(const char* const pSrc, uint32_t slength) {

    ///  Implement this function!!  ///
    String* str = (String*) malloc(sizeof(String));

    if (str == NULL) {
        printf("Failed to allocate memory.");
        return -1;
    }

    str->pData = pSrc;
    str->length = slength;

    return str;
}

/** Compares two Strings.
 *
 *  Pre:
 *    *pLeft is a proper String object
 *    *pRight is is a proper String object
 *
 *  Returns:
 *    < 0 if *pLeft precedes *pRight, lexically
 *      0 if *pLeft equals *pRight
 *    > 0 if *pLeft follows *pRight, lexically
 */
int32_t String_Compare(const String* const pLeft, const String* const pRight) {

    ///  Implement this function!!  ///

    uint32_t left = 0, right = 0;
    uint32_t leftLength = pLeft->length, rightLength = pRight->length;

    while (left < leftLength && right < rightLength) {
        int compare = pLeft->pData[left++] - pRight->pData[right++];

        if (compare != 0) {
            return compare;
        }
    }

    return (pLeft->pData[left] - pRight->pData[right]);
}

/** Appends the String *pSrc to the String *pDest.
 *
 *  Pre:
 *    *pDest is a proper String object
 *    *pSrc is is a proper String object
 *    pSrc != pDest (i.e., the source and destination are different String objects)
 *  Post on success:
 *    pSrc->pData is appended to the String pDest->pData
 *    *pDest is a proper String object
 *  Post on failure:
 *    *pDest is unchanged
 *
 *  Returns:
 *    the length of pDest->pData, if nothing goes wrong;
 *    a negative value, if some error occurs
 */
int32_t String_Cat(String* const pDest, const String* const pSrc) {

    ///  Implement this function!!  ///

    uint32_t srcLength = pSrc->length, destLength = pDest->length;

    char* strCmb = (char*) malloc(sizeof(char) * (srcLength + destLength + 1));

    if (strCmb == NULL) {
        printf("Failed to allocate memory.");
        return -1;
    }

    uint32_t i = 0, j = 0;

    while (j < destLength) {
        strCmb[i++] = pDest->pData[j++];
    }

    j = 0;

    while (j < srcLength) {
        strCmb[i++] = pDest->pData[j++];
    }

    strCmb[i] = '\0';

    pDest->pData = strCmb;
    pDest->length = i;

    return pDest->length;
}

/** Makes an exact, full copy of a substring.
 *
 * Pre:
 *   *pSrc is a proper String object
 *   startIdx + length <= pSrc->length
 * Post:
 *    no memory leaks have occurred
 *    A new, proper string object S has been created such that S holds
 *      the specified substring of *pSrc
 *
 * Returns:
 *    pointer to a String object which holds a copy of specified substring;
 *    NULL if failure occurs
 */
String* String_subString(const String* const pSrc, uint32_t start, uint32_t length) {

    ///  Implement this function!!  ///

    String* subStr = (String*) malloc(sizeof(String));

    if (subStr == NULL) {
        printf("Failed to allocate memory.");
        return -1;
    }

    subStr->pData = NULL;
    subStr->length = length + 1;

    char* strData = (char*) malloc(sizeof(char) * (length + 1));

    int i = start, j = 0;

    while (i < length) {
        strData[j] = pSrc->pData[i];
        j++;
    }

    strData[j+1] = "\0";

    subStr->pData = strData;

    return subStr;
}

/** Erases a specified sequence of characters from a String.
 *
 * Pre:
 *   *pSrc is a proper String object
 *   startIdx + length <= src->length
 * Post:
 *    no memory leaks have occurred
 *    the specified range of characters have been removed
 *    *pSrc is proper
 *
 * Returns:
 *    if successful, pSrc
 *    NULL if failure occurs
 */
String* String_Erase(String* const pSrc, uint32_t start, uint32_t length) {

    ///  Implement this function!!  ///

    return pSrc;
}

/**  Deallocates a String object and all its content.
 *
 *   Pre:
 *     *ppStr is a pointer to a proper String object, so
 *     **ppStr is a proper String object
 *     **ppStr was allocated dynamically
 *   Post:
 *     (**ppStr).data has been deallocated
 *     **ppStr has been deallocated
 *     *ppStr == NULL
 */
void String_Dispose(String** ppStr) {

    ///  Implement this function!!  ///
    free((**ppStr).pData);
    free(*ppStr);

    *ppStr = NULL;
}

I'm not sure what the issue is, I've also tried:
String* ptr = *ppStr;

free (ptr->data);
free (ptr);

*ppStr= NULL;

This ends up in the same result, I'm a little lost and would like a push in the right direction.
Struct declaration inside of String.h:
struct _String {

   char     *pData;    // dynamically-allocated array to hold the characters
   uint32_t  length;   // number of characters in the string
};
typedef struct _String String;

A: The call seems correct to me. There are two small inconsistencies that aren't germane to your problem:
 if (str == NULL) {
    printf("Failed to allocate memory.");
    return -1;
 }
 str->pData = pSrc;
 str->length = slength;
 return str;

should be (since you want to return a pointer, not "-1")
 if (str == NULL) {
    printf("Failed to allocate memory.");
 } else {
    str->pData = pSrc;
    str->length = slength;
 }
 return str;

In String_Cat, the previous value of pData should be freed to avoid leaks unless it is NULL (it seems to me it would never be, however); or better, modified using realloc() instead of using strCmb.
Another strange thing is that you seem to use both Pascal-style strings (with lengths stored along the text) and ASCIIZ strings (e.g. strCmb[i] = '\0';); and this might conflict with the allocation (for example, a string like "Hello" coming out of strcat'ting He and llo would have a length of six, but your test string "And as we wind on down the road..." is 34 characters and has a length of 34 rather than 35. When Str_Compar'ing, this might bite you in the back.
A sample program with the above code runs correctly:
==1129378== Memcheck, a memory error detector
==1129378== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==1129378== Using Valgrind-3.15.0 and LibVEX; rerun with -h for copyright info
==1129378== Command: ./zot
==1129378==
Allocating dummy string
Freeing 0x4a51040
Freeing 0x1fff000900
==1129378==
==1129378== HEAP SUMMARY:
==1129378==     in use at exit: 0 bytes in 0 blocks
==1129378==   total heap usage: 3 allocs, 3 frees, 1,090,632 bytes allocated
==1129378==
==1129378== All heap blocks were freed -- no leaks are possible
==1129378==
==1129378== For lists of detected and suppressed errors, rerun with: -s
==1129378== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)

So, it looks like the error might lie in whatever code calls String_Dispose().
For example, if you use literally your sample test code,
String *pStr = String_Create("And as we wind on down the road...", 34);

then the string you are passing to String_Created was not allocated, so the pStr object carries along a string unsuitable for free(), and trying to free it upon String_Dispos'ing would invoke undefined behaviour.


text:
Q: Finding integer solutions to $2x^2+y^2+8x+2y-93=0$
Given integers $x$ and $y$, find all sets of $(x, y)$ that satisfy the following:
$$2x^2+y^2+8x+2y-93=0$$

Factorization was the first thought I have, however, after rearranging as follows:
$$(2x+\text{ ___ }y+\text{ ___ })(x+\text{ ___ }y+\text{ ___ })$$
I find it difficult to find values for the coefficients of $y$, because we'll always get $xy$ terms.
Note: due to the fact that $x$ and $y$ are both integers, I suppose the coefficients should also be integers?


text:
Q: Find min natural number $n$ so that $2^{2002}$ divides $2001^{n}-1$ Can someone explain me how this type of examples are being solved?
I know that I can watch this example like this $2001^{n}\equiv 1\ ({\rm mod}\ 2^{2002})$ but I don't know what to do when the divisor is such a large number like $2^{2002}$
$2^{2002}|2001^{n}-1$

A: This problem is easily solved using the "lifting the exponent lemma". You can google it, but for sake of completeness I'm going to write the lemma for the special case that we will use.
First, for a prime number $p$, we denote $v_{p}(n)$ the exponent of $p$ in the factorization of $n$. So, if $v_{p}(n)=k$, then $p^{k}\mid n$, but $p^{k+1}\nmid n$.
Lemma: If $x$ and $y$ odd integers such that $4\mid x-y$ and $n\in \mathbb{Z}^{+}$, then $$v_{2}(x^n-y^n)=v_{2}(x-y)+v_{2}(n).$$
Applying the lemma to $x=2001$ and $y=1$ gives us $v_{2}(2001^n-1)=v_{2}(2001-1)+v_{2}(n)$. Since $v_{2}(2000)=4$, we get $v_{2}(2001^n-1)=4+v_{2}(n)$. Now, because we want $2^{2002}\mid 2001^n-1$, we must have $v_{2}(n)\ge 1998$.
Therefore $2^{1998}\mid n$ and hence the minimal natural number is $n=2^{1998}$.


text:
Q: Why is the transformer not receiving any AC voltage, and why is the LED not lighting up?
I built an electrical muscle stimulator circuit to simulate in Proteus. I am not getting any AC voltage on the primary and secondary transformers and the LED (D1) doesn't light up either when I run it. What is the problem?


text:
Q: multiple entries in database I have a PHP script which adds an unique email to a mysql data base. The PHP script is:
<?php
    try {
          $pdo = new PDO('mysql:host=localhost;dbname=ourdatabase', 'shyam', 'mypassword');
          $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
          $pdo->exec('SET NAMES "utf8"');
    }
    catch (PDOException $e) {
        exit();
    }

    try {
          $email=$_POST['email'];
          $sql = "SELECT username FROM users WHERE email LIKE '$email'";
          $result = $pdo->query($sql);
    } catch (PDOException $e) {
          exit();
    }

    if ($row = $result->fetch()) {
        $resturant[] = array('status' => "userexists");
        echo json_encode($resturant);
        exit();
    } else {
        try {
            $sql = 'INSERT INTO users SET
               email = :mailaddress,
               password = :password,
               tagline = :tagline';

            $s = $pdo->prepare($sql);
            $s->bindValue(':mailaddress', $_POST['email']);
            $s->bindValue(':password', $_POST['password']);
            $s->bindValue(':tagline', $_POST['tagline']);
            $s->execute();
            exit();
        } catch (PDOException $e) {
             exit();
        }
    }
   ?>

I am accessing this script from a swift file :
@IBAction func registerClick(sender: AnyObject) {

    let url:NSURL = NSURL(string: url_to_request)!
    let session = NSURLSession.sharedSession()

    let request = NSMutableURLRequest(URL: url)
    request.HTTPMethod = "POST"
    request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringCacheData

    let paramString = "email=\(email.text!) & password=\(password.text!) & tagline=\(tagline.text!)"
    request.HTTPBody = paramString.dataUsingEncoding(NSUTF8StringEncoding)
    for index in 1...10{
    let task = session.dataTaskWithRequest (request, completionHandler: {data, response, error -> Void in })

    task.resume()
    }

    }

But multiple entries are added in the database:
databse screen shot

I ran the loop to check if many users try to register with the same email at the same time.
How can I run only one instance of this PHP script and let others be in queue. Pls help as I am stuck here.

A: I would suggest to simply add UNIQUE on email:
alter table users add unique (email)

That will help you avoid race conditions.
You're also not handling mixed case scenarios, and not trimming the emails, which you should do.


text:
Q: WSO2 API Manager 2.0.0 : white screen on the application view screen when running as a systemd service Consecutively to WSO2 API Manager 2.0.0 : white screens after installing https certificate, I've just installed a fresh new WSO2 API Manager (single node) from the 2.0.0 zip distribution using MySQL Database to try to avoid problems related to H2 database.
After the install is complete, it starts with no warning and no error (after a few tries to get all things right in master-datasources.xml).
In publisher, I can log in as admin, create a new API, import swagger json contract, finalize API with no problem.
In store, I can log in as admin, view the API I've just created, create a new application via the right-side drop down menu, subscribe to it.
BUT when I try to open an application in order to generate keys and token, I just get a white empty screen. Nothing can help me in the logs :
[29/Nov/2016:16:17:33 +0100] "GET /store/site/pages/application.jag?name=MyNewApp&tenant=carbon.super HTTP/1.1" 200 3 "https://10.22.106.101:9443/store/site/pages/applications.jag?tenant=carbon.super" "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:50.0) Gecko/20100101 Firefox/50.0"

EDIT :
A few minutes after I get the page crash (maybe not related ?) I have this printing repeatedly in wso2carbon.log :
WARN {sun.rmi.transport.tcp.TCPTransport$AcceptLoop} -  RMI TCP Accept-11111: accept loop for ServerSocket[addr=0.0.0.0/0.0.0.0,localport=11111] throws {sun.rmi.transport.tcp.TCPTransport$AcceptLoop}
java.lang.OutOfMemoryError: unable to create new native thread

Again, this is a basic installation (unzip) plugged into MySQL database with no customization/configuration.
EDIT 2 : So I think I have found the cause, but not the solution. This problem does not occur when I launch via direct command line, it occurs only when I launch through systemd service :
sudo sytemctl start wso2am.service

/etc/systemd/system/wso2am.service :
[Unit]
Description=WSO2 API Manager

[Service]
User=linc

ExecStart=/bin/bash -c ". /etc/profile.d/setenv.sh; /home/linc/wso2am-2.0.0/bin/wso2server.sh start"
Type=forking

[Install]
WantedBy=multi-user.target

So is WSO2 not compatible with systemd launching ? or am I missing some parameter ?

A: I have followed this blog post to run APIM as a Linux service. Please have a look. It should work without a problem. (Make sure to add #!bin/sh at the top of myService.sh)

A: Finally I have WSO2 API manager running as a Systemd service.
This is my 'wso2apim.service' file

[Unit]
Description=WSO2 API Manager

[Service]
Environment= JAVA_HOME=/usr/lib/jvm/java-8-oracle
WorkingDirectory=/opt/wso2/wso2am-2.0.0
User=wso2
ExecStart=/bin/bash /opt/wso2/wso2am-2.0.0/bin/wso2server.sh
ExecStop= /bin/bash -c '/opt/wso2/wso2am-2.0.0/bin/wso2server.sh stop'
ExecReload=/bin/bash -c '/opt/wso2/wso2am-2.0.0/bin/wso2server.sh restart'

[Install]
WantedBy=multi-user.target

It's simple, but tricky

*

*The service type is simple (not fork or either). (Default value)

*The ExecStart has not to include the 'start' option. With the
start option, it tries a nohup, that is not working

*But, the stop has to include the stop options

Hope it helps