text:
Q: How do I deploy the web2py scheduler for multiple apps? According to the following I need to create the following file:
/etc/init/web2py-scheduler.conf

http://web2py.com/books/default/chapter/29/13/deployment-recipes#Start-the-scheduler-as-a-Linux-service--upstart-
web2py-scheduler.conf
description "web2py task scheduler"
start on (local-filesystems and net-device-up IFACE=eth0)
stop on shutdown
respawn limit 8 60 # Give up if restart occurs 8 times in 60 seconds.
exec sudo -u <user> python /home/<user>/web2py/web2py.py -K <myapp>
respawn

The Question
What do I do if I want to have a scheduler for 2 apps?
Should I create two .conf files or create 1 file with 2 instances of the exec command?
The solution with two files would be:

/etc/init/web2py-scheduler.app1.conf:

description "web2py task scheduler App1"
start on (local-filesystems and net-device-up IFACE=eth0)
stop on shutdown
respawn limit 8 60 # Give up if restart occurs 8 times in 60 seconds.
exec sudo -u <user> python /home/<user>/web2py/web2py.py -K App1
respawn

/etc/init/web2py-scheduler.app2.conf:

description "web2py task scheduler App2"
start on (local-filesystems and net-device-up IFACE=eth0)
stop on shutdown
respawn limit 8 60 # Give up if restart occurs 8 times in 60 seconds.
exec sudo -u <user> python /home/<user>/web2py/web2py.py -K App2
respawn

The solution with one file:

/etc/init/web2py-scheduler.conf:

description "web2py task scheduler"
start on (local-filesystems and net-device-up IFACE=eth0)
stop on shutdown
respawn limit 8 60 # Give up if restart occurs 8 times in 60 seconds.
exec sudo -u <user> python /home/<user>/web2py/web2py.py -K App1
exec sudo -u <user> python /home/<user>/web2py/web2py.py -K App2
respawn

sorry if this is obvious but I have no experience in writing conf files and how this part of the system works.
thank you

A: ok I think both are possible, I settled on using a two file solution.
The complete files are as follows (note I've substituted <user> with www-data which is the actual user):

/etc/init/web2py-scheduler.app1.conf:

description "web2py task scheduler App1"
start on (local-filesystems and net-device-up IFACE=eth0)
stop on shutdown
respawn limit 8 60 # Give up if restart occurs 8 times in 60 seconds.
exec sudo -u www-data python /home/www-data/web2py/web2py.py -K App1
respawn

/etc/init/web2py-scheduler.app2.conf:

description "web2py task scheduler App2"
start on (local-filesystems and net-device-up IFACE=eth0)
stop on shutdown
respawn limit 8 60 # Give up if restart occurs 8 times in 60 seconds.
exec sudo -u www-data python /home/www-data/web2py/web2py.py -K App2
respawn

The solution with one file:

/etc/init/web2py-scheduler.conf:

description "web2py task scheduler"
start on (local-filesystems and net-device-up IFACE=eth0)
stop on shutdown
respawn limit 8 60 # Give up if restart occurs 8 times in 60 seconds.
exec sudo -u www-data python /home/www-data/web2py/web2py.py -K App1,App2
respawn

In the one file App1,App2 should NOT have a space in between.


text:
Q: Using the Facebook PHP SDK inside a Cake PHP Application I am looking for advice and guidance on how to use the Facebook PHP SDK inside my Cake PHP application.
I have read articles (one or 2 on SO) around adding the Facebook PHP SDK as a Vendor Package, but after consulting the Cake Cook Book:
http://book.cakephp.org/2.0/en/development/vendor-packages.html
It appears that support for vendor packages has been removed and that the preferred method is to repackage the functionality as a plugin.
Can you please advise me on how to do this. Best case would be a working example of how to return data to my Cake PHP application after providing the plugin with some parameters:

*

*Method: eg. FQL

*Query: Eg. SELECT  eid, name, description,
start_time, end_time, location, venue, pic_cover FROM event WHERE eid
= xyz

*access token: 'App ID | Secret Key'

Just worth mentioning, I have in the past developed client side jquery plugins that uses the Facebook Javascript SDK. Essentially I am looking to build a server side equivalent of this and implement it inside my CakePHP application

A: I can see that you are using CakePHP 2. Recently i worked on a facebook application using SDK version 5 which uses Namespace . What i did to load the SDK in my controller is , modified the Bootstrap file to include libraries using Namespace .
in /app/Config/bootstrap.php added following code :
spl_autoload_register(function ($class) {

    foreach (App::path('Vendor') as $base) {

        $path = $base . str_replace('\\', DS, $class) . '.php';

        if (file_exists($path)) {

            include $path;

            return;

        }

    }

});

Then i placed the Facebook Sdk in /app/Vendor/ directory .
I could successfully load the Facebook library in my controller as follows:
function login(){
    session_start();
    App::import('Vendor','Facebook',array('file'=>'Facebook'.DS.'Facebook.php'));
    $this->fb = new Facebook\Facebook([
      'app_id' => 'YOUR APP ID',
      'app_secret' => 'APP SECRET',
      'default_graph_version' => 'v2.5',
    ]);
    $helper = $this->fb->getRedirectLoginHelper();
    $permissions = ['email', 'user_likes','publish_actions','manage_pages','publish_pages','read_page_mailboxes','pages_show_list','pages_manage_cta']; // optional
    $loginUrl = $helper->getLoginUrl('Your Callback URL', $permissions);

    echo 'Log in with Facebook!';
    exit;
}

You can see the same steps in my blog too . Loading Facebook SDK in CakePHP2

A: Importing vendor libraries is still supported, the (not very detailed) documentation is about vendor assets (CSS, JS, images, etc).
Assuming the Facebook PHP SDK folder is placed in /app/Vendor/, import the library as described in the Cook Book:
App::import('Vendor', 'Facebook', array
(
    'file' => 'facebook-php-sdk' . DS . 'src' . DS . 'facebook.php'
));

and then use it as shown in the SDK examples and tests:
$facebook = new Facebook(array(
    'appId'  => 'YOUR_APP_ID',
    'secret' => 'YOUR_APP_SECRET',
));
$response = $facebook->api(array(
    'method' => 'fql.query',
    'query' => 'SELECT eid, name, description, start_time, end_time, location, venue, pic_cover FROM event WHERE eid = xyz',
));

redpajama_set_name: RedPajamaStackExchange


text:
Q: I cannot do anything to dynamically added content within window load resize function working demo without window load resize
But the same code within the load resize function is not working properly.
$(window).on('load resize', function(){

$('div').wrapAll('
');
$('.cc div').wrap('
');

var groupLength = $('.cc .group').length;
    var groups = $('.cc .group');
    if(groupLength == 2){
        groups.css('width','50%');
    } else if(groupLength == 3){
        groups.css('width','33.33%');
    } else {
        groups.css('width','10%');
    }
});

demo

You may say it's working when resizing. But obviously it's not working on load, why? So, there might be a good way to handle this?

A: It is because by default the fiddle adds the script in a window.load handler so by the time your script is executed the window.load event is already fired so your handler will not get executed again.
In the second dropdown in the left panel select No Wrap
$(window).on('load resize', function () {

    $('div').wrapAll('
');
    $('.cc div').wrap('
');

    var groupLength = $('.cc .group').length;
    var groups = $('.cc .group');
    if (groupLength == 2) {
        groups.css('width', '50%');
    } else if (groupLength == 3) {
        groups.css('width', '33.33%');
    } else {
        groups.css('width', '10%');
    }
});

Demo: Fiddle
The window.load event does not work like document.ready handler which will call the handler method even if the event is already triggered.

A: You can trigger resize() on page load since jsFiddle has wrapped your code inside $(window).load(function() {...}); by default:
$(window).on('load resize', function(){

$('div').wrapAll('
');
$('.cc div').wrap('
');

var groupLength = $('.cc .group').length;
    var groups = $('.cc .group');
    if(groupLength == 2){
        groups.css('width','50%');
    } else if(groupLength == 3){
        groups.css('width','33.33%');
    } else {
        groups.css('width','10%');
    }
}).resize(); // <-- Here

Updated Fiddle


text:
Q: python3 correct argv usage Here is the code I have for reading a text file a storing it as a dictionary:
from sys import argv

def data(file):
    d = {}
    for line in file:
        if line.strip() != '':
            key,value = line.split(":")
            if key == 'RootObject':
                continue
            if key == 'Object':
                obj = value.strip()
                d[obj]={}
            else:
                d[obj][key] = value.strip()
    return d

file = open(argv[1])
planets = data(file)
print(planets)

My question is did I implement the argv correctly so that any user can run the dictionary by just typing solardictionary.py random.txt in the commandline and run it. I tried running this but I keep getting an index error and I'm not sure there might be something wrong with my argv implementation.

A: You need to type file = open(sys.argv[1],'r') in order to access the array because it is contained within the sys module.
http://docs.python.org/3.1/library/sys.html#module-sys
You may also be interested in opening the file within a try-catch block.


text:
Q: ASP.Net form issue after moving servers - "Failure sending mail" After hours and hours of head scratching and not knowing WHY my site's code used to work on the old server and now on the new server it just doesn't work (changed IP of mailserver, used subdomain address for the server, changed ports, tried 25, 26, 587 and anything suggested by the server admins) I have finally stumbled through the real issue (I think) which is that the hosting requires authentication.
I have no idea how to add authentication to my old code and the support doesn't even reply to my tickets anymore. Any help is appreciated.
This is the part in the registration file which sends the activation code:
MailClass.MailGonder("info@mysite.com", TxtEMail.Text, "Activation", body, "info@mysite.com", "emailpassword", "mail.mysite.com", 587);

And this is the Mail_Class.cs file which handles the mail sending of all pages (there are other pages which also use this other than the registration page):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net.Mail;
using System.Net;

namespace Sngl
{
public class MailClass
{
    public MailClass() { }

    public static void MailGonder(string kimden, string kime, string title, string body, string senderEmail, string senderPassword, string smtpServer, int port)
    {
        try
        {
            System.Net.Mail.MailMessage MyMailMessage = new System.Net.Mail.MailMessage(kimden, kime, title, body);
            MyMailMessage.IsBodyHtml = true;
            MyMailMessage.Priority = System.Net.Mail.MailPriority.High;
            System.Net.NetworkCredential mailAuthentication = new
            System.Net.NetworkCredential(senderEmail, senderPassword);
            System.Net.Mail.SmtpClient mailClient = new System.Net.Mail.SmtpClient(smtpServer, port);
            mailClient.EnableSsl = false;
            mailClient.UseDefaultCredentials = false;
            mailClient.Credentials = mailAuthentication;
            mailClient.Send(MyMailMessage);

            PropertyClass.Result = true;

        }
        catch (Exception ex)
        {
            PropertyClass.Result = false;
            PropertyClass.Message = ex.Message;
        }
    }
}
}

Error message shown is: "Failure sending mail."
No more details are given.

A: The link you gave must be for a really old posting because the example it gives uses obsolete .net classes. I've converted it to c# for you below, but i've got no idea if it will work as I've never used this stuff before.
using System;
using System.Web.Mail;

namespace Sngl
{
    public class MailClass
    {
        public MailClass() { }

        public static void MailGonder(string kimden, string kime, string title, string body, string senderEmail, string senderPassword, string smtpServer, int port)
        {
            try
            {
                var message = new MailMessage
                {
                    From = kimden,
                    To = kime,
                    Subject = title,
                    Body = body
                };
                message.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserver"] = smtpServer;
                message.Fields["http://schemas.microsoft.com/cdo/configuration/smtpserverport"] = port;
                message.Fields["http://schemas.microsoft.com/cdo/configuration/sendusing"] = 1;
                message.Fields["http://schemas.microsoft.com/cdo/configuration/smtpauthenticate"] = 1;
                message.Fields["http://schemas.microsoft.com/cdo/configuration/sendusername"] = senderEmail;
                message.Fields["http://schemas.microsoft.com/cdo/configuration/sendpassword"] = senderPassword;
                message.Fields["http://schemas.microsoft.com/cdo/configuration/smtpconnectiontimeout"] = 60;

                SmtpMail.SmtpServer = smtpServer;
                SmtpMail.Send(message);

                PropertyClass.Result = true;
            }
            catch (Exception ex)
            {
                PropertyClass.Result = false;
                PropertyClass.Message = ex.Message;
                throw;
            }
        }
    }
}


text:
Q: How to answer incoming call in browser using javascript and php connection.on('incoming', function(conn) {}) function not called.
I am trying to implement the incoming call in the browser. What I tried is a javascript code
var number = $("#number").val();

params = {
    "PhoneNumber": number,
    "CallerId": "+13604924000",
    "AgentName": "Noman Javed",
};

Twilio.Device.setup(token);

Twilio.Device.ready(function(device) {

    console.log('Ready');

    // ---------------------------------------------------
    // Explicitly create a new outgoing connection
    var connection = Twilio.Device.connect(params);

    console.log('PhoneNumber: ' + params.PhoneNumber);

    $('#hangup_btn_span').show();
    $("#hangup_btn").show();

    connection.on('error', function(error) {
        console.log(error);
    });

    connection.on('accept', function(conn) {

    });

    connection.on('incoming', function(conn) {
        console.log("incoming call connection object log");
        console.log(conn);
        console.log('Incoming connection from ' + conn.parameters.From);
        // accept the incoming connection and start two-way audio
        // conn.accept();
    });

}

For outgoing calls, I had to add the URL of the Twiml App outgoing call URL and dial the call using rest API to hit twiml page.
For incoming calls, I had add incoming call URL in the phone number incoming call URL that is
mydomain.com/Welcome/incoming_call
The incoming call urls code is:
header('Content-Type: application/xml');
// Load the required files
require APPPATH . 'libraries/vendor/autoload.php';

use Twilio\Jwt\ClientToken;
use Twilio\Rest\Client;
use Twilio\TwiMl;
use Twilio\TwiML\VoiceResponse;

    file_put_contents('request.log', "\n" . "incoming call - : " . json_encode($_REQUEST)  . "\n", FILE_APPEND);
?>
<Response>
   <Pause length="2"/>
   <Say voice="woman">Dialing number</Say>
   <Dial callerId="<?php echo $_REQUEST['From']; ?>" >
        <?php echo $_REQUEST['To']; ?>
   </Dial>
</Response>

How I will receive the call in the browser in this function with parameters
connection.on('incoming', function(conn) {
    console.log("incoming call connection object log");
    console.log(conn);
    console.log('Incoming connection from ' + conn.parameters.From);
    // accept the incoming connection and start two-way audio
    // conn.accept();
});

Do I need to add an incoming call URL in Twiml App too or just add in the phone number incoming URL?
Thanks in advance for helping and guiding.

A: First, in the twiml app you have to add the url for your backend api where you have your php code and add that twiml app to your incoming number.
Now, while generating the token for your user you must have used an 'identity'. We need to use that identity value to connect the incoming call to the user. Something like below:
$response = new VoiceResponse();
$dial = $response->dial('');
$dial->client(IDENTITY_VALUE);

this dial->client will connect the incoming call to the browser.
If you have not used identity attribute in your token generation, check this url:
https://www.twilio.com/docs/iam/access-tokens?code-sample=code-creating-an-access-token-voice-2&code-language=PHP&code-sdk-version=5.x


text:
Q: Need help in creating CriteriaQuery First of all, I would like to know if it is possible to do?
Below is my query and I am trying to build using criteria.
SELECT CONCAT('record-', rl.record_id) AS tempId,
        'sloka' AS type,
         rl.record_id AS recordId,
         rl.title AS title,
         rl.locale as locale,
         rl.intro AS intro,
         rl.title AS localetitle,
         NULL AS audioUrl,
         lp.name AS byName,
         lp.person_id AS byId,
         lp.name AS onName,
         lp.person_id AS onId

    FROM record_locale rl
        LEFT JOIN record r ON rl.record_id = r.record_id
        LEFT JOIN locale_person lp ON r.written_on = lp.person_id
    WHERE rl.title LIKE :title
        AND rl.locale = :locale
        AND lp.locale = :locale

UNION

SELECT CONCAT('lyric-', s.song_id) AS tempId,
        'bhajan' AS type,
        s.song_id AS recordId,
        s.title,
        l.locale as locale,
        NULL AS intro,
        l.title AS localetitle,
        s.audio_url AS audioUrl,
        lpb.name AS byName,
        lpb.person_id AS byId,
        lpo.name AS onName,
        lpo.person_id AS onId

    FROM song s
        LEFT JOIN locale_person lpb
    ON (s.written_by = lpb.person_id AND lpb.locale = :locale)
        LEFT JOIN locale_person lpo
    ON (s.written_on = lpo.person_id AND lpo.locale = lpb.locale)
        INNER JOIN lyric l
    ON (l.locale = lpb.locale AND l.song_id = s.song_id)

    WHERE s.title LIKE :title AND s.approved_by IS NOT NULL

    ORDER BY localeTitle ASC

// END

Based on few conditions, I might need to have union of both queries or just individual query without union.

A: Converting the SQL to JPQL is usually a good first step, as we can't quite tell what these tables map to, or what you are expecting to get back. If it is possible to do in JPQL, it should be possible with a criteria query. Except in this case: JPA/JPQL does not have the union operator so it won't work in straight JPA, but some providers such as EclipseLink have support.  See:
UNION to JPA Query
and
http://www.eclipse.org/eclipselink/documentation/2.5/jpa/extensions/j_union.htm


text:
Q: Find all transaction of same within time window before each observation in R I have a data base of work orders containing materials reserved for different plants.
I need to find how many times each material have been requested in a time window before the current observation.
I have tried the following approach, but with a dataframe of 7 million lines, i'll take 300 months.
result<-data.frame()
for (i in 1:nrow(work.orders)){
  wo.date_f<- work.orders$original_basic_start_date[i] %>% as_date()
  days.back<-30 # Time windows for searching
  mat_f<- work.orders$material[i]
  plant_f<-work.orders$plant[i]
  total_resb_found<-work.orders %>% filter(plant==plant_f,
                       material==mat_f,
                       (original_basic_start_date %>% as_date())<wo.date_f,
                       (original_basic_start_date %>% as_date())-wo.date_f<days.back) %>% nrow()
  result[i,1]<-mat_f
  result[i,2]<-plant_f
  result[i,3]<-total_resb_found
  print(paste0(i," out of ", nrow(work.orders)))
}

So the approach is:

*

*Find date, material and plant of row 1.

*filter main data frame for material and plant found in previous step

*filter data frame for dates before date found in step 1, and also after said date - time window

*count how many lines found

*record result in data frame

I understand this is a brute-force approach, so deffinitely tons of room for improvement, but i havent been able to think of a good one
Any ideas on a more efficient approach?
Thanks
Edit: added a sample data with desired result (as result column)
 structure(list(material = c("000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010199498", "000000000010339762",
"000000000010199498", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010199498", "000000000010339762",
"000000000010339762", "000000000010199498", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010199498", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010199498",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010199498", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010199498",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010199498", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010199498", "000000000010199498",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010199498",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010199498", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762", "000000000010199498", "000000000010199498",
"000000000010339762", "000000000010339762", "000000000010339762",
"000000000010339762"), original_basic_start_date = c("20201106",
"20200702", "20200618", "20200923", "20201205", "20201118", "20201231",
"20201022", "20200819", "20200823", "20201118", "20201106", "20201106",
"20200826", "20201123", "20201111", "20200912", "20200930", "20200916",
"20200717", "20200702", "20200929", "20201016", "20200624", "20201123",
"20201105", "20200620", "20200626", "20200608", "20200712", "20200616",
"20201209", "20200904", "20210130", "20201123", "20201117", "20200620",
"20210311", "20200812", "20201130", "20200816", "20200802", "20200805",
"20200705", "20200731", "20201123", "20200703", "20200926", "20200718",
"20201105", "20200618", "20200815", "20200609", "20200729", "20210112",
"20201121", "20210110", "20201008", "20200705", "20200902", "20200918",
"20200713", "20200828", "20200722", "20210126", "20200906", "20200902",
"20210106", "20201229", "20210117", "20210321", "20210204", "20201005",
"20210109", "20210106", "20210526", "20210203", "20201001", "20201206",
"20210221", "20210103", "20210112", "20200719", "20201019", "20200707",
"20210110", "20210219", "20200710", "20210331", "20210103", "20201222",
"20201027", "20210116", "20210130", "20200709", "20210120", "20210208",
"20210220", "20201106", "20210205", "20201223", "20210211", "20210303",
"20210428", "20200724", "20210203", "20200831", "20210207"),
    plant = structure(c(16L, 34L, 16L, 16L, 21L, 20L, 10L, 15L,
    25L, 37L, 20L, 37L, 37L, 10L, 17L, 25L, 32L, 39L, 25L, 16L,
    37L, 17L, 19L, 25L, 27L, 16L, 39L, 34L, 17L, 19L, 17L, 25L,
    16L, 17L, 16L, 16L, 36L, 17L, 16L, 27L, 16L, 37L, 16L, 16L,
    17L, 16L, 39L, 32L, 19L, 27L, 19L, 16L, 16L, 19L, 20L, 15L,
    39L, 16L, 16L, 16L, 16L, 16L, 16L, 25L, 16L, 16L, 19L, 25L,
    19L, 27L, 17L, 33L, 32L, 33L, 15L, 25L, 25L, 16L, 19L, 21L,
    16L, 20L, 16L, 16L, 37L, 16L, 16L, 37L, 25L, 27L, 37L, 32L,
    37L, 37L, 19L, 21L, 20L, 17L, 27L, 47L, 16L, 16L, 25L, 25L,
    16L, 32L, 16L, 20L), .Label = c("B201", "B21B", "B401", "B501",
    "B504", "B521", "B701", "B71A", "B991", "C602", "C603", "C690",
    "CS01", "CY01", "CY02", "CY04", "CY05", "CY06", "CY07", "CY08",
    "CY09", "CY11", "CY12", "CY13", "CY16", "CY21", "CY30", "CY91",
    "CY95", "D106", "D192", "FX01", "FX03", "FX05", "FX06", "FX07",
    "FX10", "FX1A", "FX1C", "FX1E", "FX21", "FX5A", "FX5B", "FX5C",
    "FX92", "FX94", "KB01", "PA02", "PA04", "PA05", "PA12", "PB1A",
    "PB51", "PI01", "PI03", "PI08", "PI0A", "PI0B", "PI0F", "PN9A",
    "PN9B", "PN9D", "PN9E", "PP9A", "PR90", "PR92", "PT01", "PT02",
    "PT07", "PT08", "S501", "S502", "S503", "S504", "S505", "S507",
    "S50I", "S516", "S517", "S593", "U201"), class = "factor"),
    Result = c(23L, 1L, 1L, 18L, 0L, 0L, 0L, 0L, 2L, 4L, 0L,
    5L, 5L, 0L, 4L, 4L, 0L, 2L, 3L, 5L, 0L, 3L, 6L, 0L, 2L, 22L,
    0L, 0L, 0L, 2L, 1L, 5L, 15L, 5L, 25L, 24L, 0L, 7L, 9L, 3L,
    11L, 3L, 8L, 2L, 2L, 25L, 1L, 1L, 3L, 0L, 0L, 10L, 0L, 4L,
    2L, 1L, 3L, 20L, 2L, 14L, 17L, 4L, 12L, 1L, 30L, 16L, 5L,
    6L, 8L, 5L, 8L, 0L, 2L, 0L, 2L, 11L, 7L, 19L, 7L, 2L, 28L,
    2L, 6L, 21L, 1L, 29L, 32L, 2L, 9L, 4L, 7L, 3L, 0L, 8L, 1L,
    1L, 5L, 6L, 1L, 0L, 27L, 31L, 8L, 10L, 7L, 4L, 13L, 4L)), .Names = c("material",
"original_basic_start_date", "plant", "Result"), row.names = c(NA,
-108L), class = "data.frame")

A: Here's a stab at it:

plant.pool <- 1:4
material.pool <- 1:5
date.pool <- seq(as.Date('2010/01/01'), as.Date(now()), by="day")
n.out <- 7e6

## Generate 7 mill records
d <- data.table(
    plant = sample( plant.pool, size=n.out, replace=TRUE ),
    material = sample( material.pool, size=n.out, replace=TRUE ),
    original_basic_start_date = sample( date.pool, size=n.out, replace=TRUE ),
    id = 1:n.out
)[ order(original_basic_start_date) ]

window.size <- 30

## Do the actual rolling calculation, and time it, demonstrating the first 100k only
system.time( the.counts <- frollapply(
    d[ 1:1e5, .(id) ],
    window.size,
    function(x){
        d[ id %in% x, sum( plant==last(plant) & material==last(material) ) ]
    }
))

As you can see, I deliberately process only the first 100k records, and time this.
After a couple of runs on my ageing workstation (8-9 years old, 8 cores),  it clocks in on around 17 seconds to process those 100k records. This might extrapolate to 3.3 hours, which is substantially faster than 300 months. Also your computer is likely faster than mine, so all the merrier. Once you see you have my speeds or faster, you could time the 100k rows as I do, and start it up and check back in when it should be done.
data.table is generally suited for big things that need to go faster. There might be better suited functions out there though (you might have to look to python or c even), though I haven't found a solution that could look at both material and plant column in their optimized rolling functions (frollsum w/friends)
EDIT:
You added data after my first attempt, but I think the principle of my approach still holds.
EDIT 2:
Also rollapply doesn't process the first 1:window.size rows, you would have to them yourself, (which should be a fairly simple matter now that you have 300 months minus a few hours on your hands)

A: The issues with your current approach that cause the increase in time is these line of code
result[i,1]<-mat_f
result[i,2]<-plant_f
result[i,3]<-total_resb_found

Adding one rows to matrix, dataframe in R is very inefficient and require a lot of additional work which would be fast when the number of rows is small. Once the number of rows reach certain threshold, the cost multiply by every new row. So you estimation of 300 months maybe a bit optimistics :)
This is my personal experience testing various stuff. Though I haven't really quantify or do a thorough research on this. However I know for sure it related with memory allocation similar to performance issue when you pre-allocate memory for an array of 100 elements versus define an empty array and add one item at a time.
Updated approach
After some stress test and further clearification here is my updated code for better performance
library(doParallel)
library(dplyr)
library(lubridate)
library(purrr)

# Parallel on 4 cores
registerDoParallel(4)

# Create a df which is 70000 your sample data (70000 x 108 = 7.5M records)
work.orders <- purrr::map_dfr(seq_len(70000), ~df)
# To allow more properly testing the data, a random date in span of one and a half years was generated and assign to original_basic_start_date
random_dates <- as.Date(rdunif(nrow(work.orders), as.integer(as.Date("2020-01-01")), as.integer(as.Date("2021-06-01"))), origin = "1970-01-01")
work.orders$original_basic_start_date <- random_dates
work.orders <- work.orders %>% arrange(original_basic_start_date)

# As the same material & plant on same date will return same results
# Therefore we only need to calculate once for those. Here is filter the
# original data to only contain no duplicated date records for a pair of
# material & plant
work.orders_unique_date <- work.orders %>%
  group_by(material, plant) %>%
  filter(!duplicated(original_basic_start_date)) %>%
  ungroup() %>%
  arrange(original_basic_start_date)
# Get all the date presented in the data
all_date_in_data <- unique(work.orders_unique_date[["original_basic_start_date"]])
# Time windows for searching
days.back <- 30
# Time the performance
system.time(
  # Here for each date we filter the original data frame to only have date
  # that in the range of defined windows which allow faster calculation
  all_result <- bind_rows(foreach(i_date = all_date_in_data) %do% {
    message(sprintf("%s Process date: %s", Sys.time(), i_date))
    smaller_df <- work.orders %>%
      filter(original_basic_start_date < i_date) %>%
      filter(original_basic_start_date - i_date < days.back)
    unique_item_on_date <- work.orders_unique_date %>%
      filter(original_basic_start_date == i_date)
    # for one date, calculate the requirement result for all pair of
    # material & plant on that date
    result <- bind_rows(foreach(i = 1:nrow(unique_item_on_date)) %dopar% {
      mat_f <- unique_item_on_date$material[i]
      plant_f <- unique_item_on_date$plant[i]
      # Here using the smaller df which already filter by date windows
      total_resb_found <- smaller_df %>%
        # Separate condition into multiple filter which should speed it up a bit
        filter(plant == plant_f, material == mat_f)
        nrow()
        tibble(date = i_date, mat_f, plant_f, total_resb_found)
    })
    result
  })
)

Some message output from the process above. Maximum 2 seconds per day consistently. If your data have 7M records in span of 2 years then it should take around 1 hour or even less
2021-03-12 08:58:41 Done Process date: 2020-08-15 in 1.83 seconds
2021-03-12 08:58:42 Done Process date: 2020-08-16 in 1.66 seconds
2021-03-12 08:58:44 Done Process date: 2020-08-17 in 1.93 seconds
2021-03-12 08:58:46 Done Process date: 2020-08-18 in 1.72 seconds
2021-03-12 08:58:48 Done Process date: 2020-08-19 in 1.77 seconds
2021-03-12 08:58:50 Done Process date: 2020-08-20 in 1.74 seconds
2021-03-12 08:58:51 Done Process date: 2020-08-21 in 1.78 seconds
2021-03-12 08:58:53 Done Process date: 2020-08-22 in 1.78 seconds
2021-03-12 08:58:55 Done Process date: 2020-08-23 in 1.73 seconds
2021-03-12 08:58:57 Done Process date: 2020-08-24 in 1.94 seconds
2021-03-12 08:58:59 Done Process date: 2020-08-25 in 1.78 seconds
2021-03-12 08:59:00 Done Process date: 2020-08-26 in 1.78 seconds
2021-03-12 08:59:02 Done Process date: 2020-08-27 in 1.81 seconds
2021-03-12 08:59:04 Done Process date: 2020-08-28 in 1.84 seconds
2021-03-12 08:59:06 Done Process date: 2020-08-29 in 1.83 seconds
2021-03-12 08:59:08 Done Process date: 2020-08-30 in 1.76 seconds
2021-03-12 08:59:10 Done Process date: 2020-08-31 in 1.94 seconds
2021-03-12 08:59:11 Done Process date: 2020-09-01 in 1.78 seconds
2021-03-12 08:59:13 Done Process date: 2020-09-02 in 1.86 seconds
2021-03-12 08:59:15 Done Process date: 2020-09-03 in 1.82 seconds
2021-03-12 08:59:17 Done Process date: 2020-09-04 in 1.80 seconds
2021-03-12 08:59:19 Done Process date: 2020-09-05 in 1.88 seconds
2021-03-12 08:59:20 Done Process date: 2020-09-06 in 1.78 seconds
2021-03-12 08:59:23 Done Process date: 2020-09-07 in 2.08 seconds
2021-03-12 08:59:24 Done Process date: 2020-09-08 in 1.89 seconds
2021-03-12 08:59:26 Done Process date: 2020-09-09 in 1.88 seconds
2021-03-12 08:59:28 Done Process date: 2020-09-10 in 1.86 seconds
2021-03-12 08:59:30 Done Process date: 2020-09-11 in 1.87 seconds

Timing of the first 100 days is 60 seconds
   user  system elapsed
 93.281  73.571  60.310

And here is sample result
> tail(all_result, 20)
# A tibble: 20 x 4
   date       mat_f              plant_f total_resb_found
   <date>     <chr>              <fct>              <int>
 1 2020-04-08 000000000010199498 C602               13318
 2 2020-04-09 000000000010339762 FX01               66596
 3 2020-04-09 000000000010339762 CY04              441597
 4 2020-04-09 000000000010199498 CY16              160625
 5 2020-04-09 000000000010199498 FX03               13350
 6 2020-04-09 000000000010199498 FX10               13418
 7 2020-04-09 000000000010339762 CY07              120541
 8 2020-04-09 000000000010339762 CY30               80768
 9 2020-04-09 000000000010339762 FX10              120076
10 2020-04-09 000000000010339762 FX03               13498
11 2020-04-09 000000000010199498 C602               13448
12 2020-04-09 000000000010339762 FX1C               53672
13 2020-04-09 000000000010339762 CY08               80234
14 2020-04-09 000000000010339762 CY05              120682
15 2020-04-09 000000000010339762 CY09               40493
16 2020-04-09 000000000010339762 FX07               13325
17 2020-04-09 000000000010339762 CY02               40204
18 2020-04-09 000000000010339762 FX05               26671
19 2020-04-09 000000000010339762 C602               13576
20 2020-04-09 000000000010339762 KB01               13331

[Updated: add time to process whole 7.5M records]
    user   system  elapsed
1665.785 1096.865  891.837


text:
Q: Testing mapDispatchToProps calls have fired with ReactTestingLibrary I am using mapDispatchToProps to make a dispatch call to an API in the useEffect of my functional component.
I am a little stuck as how to actually test this in my unit tests with React Testing Library.
I can pass my Redux store quite easily, however I don't think I've ever had to pass the dispatch before and I'm a little lost.
I did try to pass the dispatch function with my store, but this of course didn't work.
Component
const mapDispatchToProps = dispatch => ({
    myDispatchFunction: () => dispatch(someDispatch())
});
const mapStateToProps = ({someStateProp}) => ({
    myStateProp: !!someStateProp // This isn't important
});

const MyComp = ({myDispatchFunction}) => {
    useEffect(() => {
        !!myStateProp && myDispatchFunction();
    }, []);

    return ...
}

Test
it('Should trigger dispatch function on load', () => {
    const mockFunc = jest.fn(); // My attempt at mocking the dispatch call
    const store = {someStateProp: true, myDispatchFunction: mockFunc};
    render(
        <Provider store={mockStore(store)}>
            <MyComponent />
        </Provider>
    );

    expect(mockFunc).toHaveBeenCalled();
});

This fails...

A: Your code has no real meaning, but the same with the test method, try not to mock functions and modules that have no side effects, I/O operations, and use their original implementation.
For your example, don't mock mapStateToProps, mapDispatchToProps, and dispatch functions. We can create a test store, populate the test state data, and collect the dispatch actions in the component.
If your component uses some state slice, verify that your component is rendering correctly. This is also called behavior testing. This testing strategy is more robust if the component behaves correctly, regardless of whether your implementation changes.
Why not mock? Like mapStateToProps, where a mock implementation changes its behavior if you don't know how it is implemented, resulting in an error-based implementation of the test case. Your tests may pass but the actual code at runtime is not correct.
E.g.
index.tsx:
import { useEffect } from 'react';
import { connect } from 'react-redux';

const mapDispatchToProps = (dispatch) => ({
  myDispatchFunction: () => dispatch({ type: 'SOME_ACTION' }),
});
const mapStateToProps = ({ someStateProp }) => ({
  myStateProp: !!someStateProp,
});

const MyComp = ({ myDispatchFunction, myStateProp }) => {
  useEffect(() => {
    !!myStateProp && myDispatchFunction();
  }, []);

  return null;
};

export default connect(mapStateToProps, mapDispatchToProps)(MyComp);

index.test.tsx:
import { render } from '@testing-library/react';
import React from 'react';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import MyComp from './';

describe('71555438', () => {
  test('should pass', () => {
    let dispatchedActions: any[] = [];
    const store = createStore(function rootReducer(state = { someStateProp: 'fake value' }, action) {
      if (!action.type.startsWith('@@redux')) {
        dispatchedActions.push(action);
      }
      return state;
    });
    render(
      <Provider store={store}>
        <MyComp />
      </Provider>
    );
    expect(dispatchedActions).toEqual([{ type: 'SOME_ACTION' }]);
  });
});

Test result:
 PASS  stackoverflow/71555438/index.test.tsx (9.562 s)
  71555438
    ✓ should pass (16 ms)

-----------|---------|----------|---------|---------|-------------------
File       | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-----------|---------|----------|---------|---------|-------------------
All files  |     100 |      100 |     100 |     100 |
 index.tsx |     100 |      100 |     100 |     100 |
-----------|---------|----------|---------|---------|-------------------
Test Suites: 1 passed, 1 total
Tests:       1 passed, 1 total
Snapshots:   0 total
Time:        10.565 s

Note: We should ignore the action dispatched by createStore internally and we only need to collect the actions dispatched by users(our code).


text:
Q: Add active class to custom link on load What happens is that the active link is removed on refresh, what should I do so on refresh it checks which link is on and adds the class? I believe this should be done with js, any tips are helpful thanks in advance.
I have this setup for links in my php file:
<?php if (!is_page('main')){  ?>

            <a href="<?php echo get_term_link( 21, 'product_cat' ); ?
            >">

<?php echo get_cat_name( 21 ); ?>

            <a href="<?php echo get_term_link( 20, 'product_cat' ); ?
            >">

<?php echo get_cat_name( 20 ); ?>

            <a href="<?php echo get_term_link( 18, 'product_cat' ); ?
            >">

<?php echo get_cat_name( 18 ); ?>

    <?php } ?>

And I have js:
$('.shop-categories li a').click(function() {

    $('a').removeClass('active');
    $(this).addClass('active');
});

A: Try this:
var cp_url= window.location.pathname;

$('.shop-categories li').find('a').each(function() {
   $(this).toggleClass('active', $(this).attr('href') == cp_url);
})

A: fixed with:
$('.shop-categories li a').filter(function() {
    return $(this).prop('href') === browserUrl;
}).addClass('active');

A: I think you need this...
$('.shop-categories li a').click(function() {
   $(this).addClass('active').siblings('a').removeClass('active');
});


text:
Q: Transition probability function of stochastic difference equations A stochastic difference equation given in the form
$X_{\{ n+1\}}=T(X_n)+e_{n+1} \;, n\geqslant 0, \; T:\mathbb{R}^m \rightarrow \mathbb{R}^m$. with state space $(\mathbb{R}^m,\mathbb{B}_m, u_m)$.
The random forcing terms on the right-hand side of the stochastic difference equation are of the following form:
$e_n=\left( \begin{array}{l}
e_n^{'} \\
0 \\
\vdots \\
0
\end{array} \right)$ with $e_n^{'}$ i.i.d., each having an absolutely continuous distribution and p.d.f. $f(.)$ is positif everywhere in $\mathbb{R}$.
Let $A\in \mathbb{B}_m$ and $x\in\mathbb{R}^m$.  Let
$x=\left( \begin{array}{l}
x_1 \\
x_2 \\
\vdots \\
x_n
\end{array} \right)$
Define
$A_x= \left\{y=\left( \begin{array}{l}
x_1 \\
x_2 \\
\vdots \\
x_n
\end{array} \right)\in \mathbb{R}^m : y_i=x_i, i\geqslant 2, \, y\in A
\right\}$.
Let $v:\mathbb{R}^m \rightarrow \mathbb{R}$ be the projection map onto the first coordinate, i.e., $v(y)=y_1$.
Then
$\mathbb{P}(x,A)= \displaystyle \int_{v_{(A_{Tx})}-(Tx)_1}f(t) dt$
where $(Tx)_1$ is the first coordinate of $Tx$ and we have written $Tx$ for $T(x)$\
My questions are:

*

*why $\{X_n\}$ with $\mathbb{P}(x,A)$ forms a Markov chain.

*how we constructed the transition probability.

*I can't understand $v_{(A_{Tx})}-(Tx)_1$.


text:
Q: Correlation between two images using EMGU I'm already searching for some hours... couldn't find any help..
I'm using EMGU (beginner with that) and found here:(How to calculate the correlation between two images in EMGU?) the way to PERFORM the correlation:
Image<>.MatchTemplate()

My question is how can I get the x,y shifts.
Thanks a lot in advance.

A: writing your own loops to find the min/max values and x/y points is not needed and your own code will run much slower than the build in and highly optimized c++ version
the function you are looking for is a one liner
res.MinMax(minValue, maxValue, pointMin, pointMax)
http://www.emgu.com/wiki/files/1.3.0.0/html/a6a35810-2a33-f1a7-ea9a-27371688fd77.htm
here MinMax in use
How to find the max occurred color in the picture using EMGU CV in C#?

A: Gosh... Found out finally + maxVal gives the quality of the Match.
var res = img1.MatchTemplate(img2, TemplateMatchingType.CcoeffNormed);
        int maxXIdx = 0, maxYIdx = 0;
        float maxVal = float.MinValue;
        var dat = res.Data;
        int numChanels = dat.GetLength(2),
            numCols = res.Cols, numRows = res.Rows;
        for (int i = 0; i < numChanels; i++)
        {
            for (int x = 0; x < numCols; x++)
            {
                for (int y = 0; y < numRows; y++)
                {
                    var val = dat[y, x, i];
                    if (val > maxVal)
                    {
                        maxVal = val;
                        maxXIdx = x;
                        maxYIdx = y;
                    }
                }
            }
        }
        int shiftX = maxXIdx, shiftY = maxYIdx;


text:
Q: Не работает повторное воспроизведение ролика c youtube iframe api на мобильных устройствах Здравствуйте,
разработали сайт. На сайт вставили iframe you tube. На компьютере воспроизводится нормально. На мобильных устройствах: планшетах и телефонах кнопка плей на плеере работает только один раз. При повторном нажатии уже не работает.
С нашей стороны проверили все нормально. Проблема где то в плеере.
Как решить?
Спасибо
p.s. Телефоны Android IOS, планшет IOS, браузеры Chrome Safari. Музыка и изображение авторские.


text:
Q: Javascript generating content from an array on user search I'm having issues dynamically creating content from an array of images. What I want to happen is that when keywords are entered into the searchbar (try "joyride" or "nick"), all of the images that match the keywords show up.  Currently, only one image shows up, and it doesn't necessarily match the keyword.  I think I'm going wrong with the javascript function - I feel like I shouldn't be using innerHTML to create the photos, especially because when the keyword is deleted, it just leaves the one image.
Would it be easier to do it all in jQuery/javascript, instead of generating the initial gallery of images in jQuery and trying to do the filtering in javascript? I'm lost.
http://scf.usc.edu/~uota/itp301/final/odc-photos.html
This is a working version of the page, with the arrays and other code that I am using.
Thanks in advance!
 $(document).ready(function(){
    for(var i = 0; i < src.length; i++){
    var content = "
";
    content += "

";
    content += "
";
    $("#gallery").append(content).hide().fadeIn(250);
}

});

var songSearch = function(keyword){
var foundFlag = false;
var content = "";

for (var i = 0; i < src.length; i++){
if (tags[i].toLowerCase().indexOf(keyword) != -1 || keyword == "") {
    content = "
";
        content += "

";
    content += "
";

        findFlag = true;
    }

}

if(findFlag){
document.getElementById("gallery").innerHTML = content;
}
else{
    content = "Your search did not return any results.";
}

 }

</script>

A: It looks like the problem is on this line in the songSearch function:
content = "
";

You are redefining the variable content instead of concatenating it. This way it will always be just the last image. Try changing it to:
content += "
";

There is also have a variable inside the songSearch function called foundFlag that is later referenced as findFlag. That shouldn't be causing the issue though.


text:
Q: Seeking a good quality reference for "lifting the exponent" This is copy/pasted from a submitted coauthored paper of mine:

Lemma: Let $k \ge 1$ and $p$ be prime.  If $a \equiv b \pmod p$, $c \ge 0$ and $c \equiv 0 \pmod{p^{k-1}}$, then $a^c \equiv b^c \pmod {p^{k}}$.

A reviewer pointed out that this is called lifting the exponent (I had no idea).  Indeed, I found that it's a consequence of the Second Form of LTE on the Art of Problem Solving:

Second Form of LTE: Let $ x,y$ be two integers, $n$ be an odd positive integer, and $p$ be an odd prime such that $ p\mid x + y$ and none of $x$ and $y$ are divisible by $p.$ then: $$v_p( x^n + y^n ) =v_p( x + y ) + v_p( n ).$$

(Here $v_p(m)$ is the largest non-negative integer for which $p^{v_p(m)}$ divides $m$.)
I'd like to add a reference to our paper, but I'm not sure where to look.  Searching for "lifting the exponent" in Google Books gives a single conference proceedings book containing the result, but in some completely irrelevant paper.  Similarly, searching for "lifting the exponent" in Google Scholar gives places its mentioned which are completely irrelevant our paper.
Question: What is a good quality reference for "lifting the exponent"?
I guess I'm looking for a reference in a number theory textbook; something better than a random paper which mentions it.

A: I don't know if the OP is still interested in the question after so long time, but the second form of LTE is typically attributed to É. Lucas:

É. Lucas, Théorie des Fonctions Numériques Simplement Periodiques, Amer. J. Math. 1 (1878), 184–196, 197-240, 289–321,

and R. D. Carmichael:

R. D. Carmichael, On the Numerical Factors of Certain Arithmetic Forms, Amer. Math. Monthly 16 (1909), no. 10, 153–159.

In particular, Carmichael fixed a mistake in Lucas' original work in the $2$-adic case.


text:
Q: Predict() with regsubsets I'm trying to replicate the results from An Introduction to Statistical Learning with Applications in R. Specifically, the Lab in section 6.5.3. I have followed the code in the lab exactly:
library("ISLR")
library("leaps")
set.seed(1)
train = sample(c(TRUE, FALSE), nrow(Hitters), rep = TRUE)
test = (!train)
regfit.best = regsubsets(Salary ~., data = Hitters[train,], nvmax= 19)

test.mat = model.matrix(Salary~., data = Hitters[test,])

val.errors = rep(NA, 19)
for (i in 1:19){
  coefi= coef(regfit.best, id = i)
  pred=test.mat[,names(coefi)]%*%coefi
  val.errors[i]=mean((Hitters$Salary[test]-pred)^2)
}

When I run this I still get the following error:
Warning message:
In Hitters$Salary[test] - pred :
  longer object length is not a multiple of shorter object length
Error in mean((Hitters$Salary[test] - pred)^2) :
  error in evaluating the argument 'x' in selecting a method for function 'mean': Error: dims [product 121] do not match the length of object [148]

And val.errors is a vector of 19 NAs.
I'm still relatively new to R and to the validation approach, so I'm not sure exactly why the dimensions of these are different.

A: It was actually an issue with not carrying over steps from the previous subsection, which omitted entries that were incomplete.

A: You need to remove rows with missing data. Run "Hitters = na.omit(Hitters)" at the beginning.


text:
Q: Bad order in angularjs ng-repeat In my little playlist script : http://www.monde-du-rat.fr/zombieReport/popup.html#/radio
The IDS are not correctly ordered : 1,10,11,2,3 ...
My json is here http://www.monde-du-rat.fr/zombieReport/resources/data/radio.json , and my html is :
            <div ng-repeat="song in songs.radio track by song.id | orderBy:'song.id*1'" class="list-group-item" id="{{song.id}}" ng-class="{ 'active' : songPlayed_name == song.name }">
            </div>

what's wrong ?

A: You can use https://github.com/petebacondarwin/angular-toArrayFilter
please see demo here http://plnkr.co/edit/PrALxOJfmtcXUntbPmSz?p=preview
<div ng:controller="Main">
      <div ng:repeat="song in songs.radio | toArray | orderBy: 'id'">
        {{song.id}} {{song.title}}

      </div>

JS:
 angular.module('app', ['angular-toArrayFilter'])

    .controller('Main', function Main($scope) {

      $scope.songs = {
        "radio": {
          "1": {
            "id": 1,
            "name": "coucou",
            "title": "\"Coucou, tu veux voir ma bite ?\" l'hymne officiel du MDR !",
            "vote": "7,5"
          },
          "2": {
            "id": 2,
            "name": "kissed",
            "title": "\"I kissed a rat\" - KitschNSniff",
            "vote": "9,5"
          },
          "3": {
            "id": 3,
            "name": "rats",
            "title": "\"It's Rats, It's Rats, It's Rat\" - KitschNSniff",
            "vote": "9,5"
          },
          "4": {
            "id": 4,
            "name": "merguez",
            "title": "\"Merguez-Partie\" - le tube culte",
            "vote": "8,5"
          },
          "5": {
            "id": 5,
            "name": "etchebest",
            "title": "\"Etchebest 1664\" - la pub culte",
            "vote": "8,5"
          },
          "6": {
            "id": 6,
            "name": "gitan",
            "title": "\"Gitan énervé\" - LE SANG DE VOS MORTS !",
            "vote": "7,5"
          },
          "7": {
            "id": 7,
            "name": "coral",
            "title": "\"Karl, Koraaal, Koarl, Karol\"",
            "vote": "5,5"
          },
          "8": {
            "id": 8,
            "name": "sax",
            "title": "\"Saxo Guy\" - musique idéale pour se détendre",
            "vote": "6,5"
          },
          "9": {
            "id": 9,
            "name": "longtime",
            "title": "\"Tomorow is a long time\" - Bob Dylan",
            "vote": "5,5"
          },
          "10": {
            "id": 10,
            "name": "blackbird",
            "title": "\"Blackbird Song\" - Lee DeWyze",
            "vote": "7,5"
          },
          "11": {
            "id": 11,
            "name": "crazy",
            "title": "\"Crazy\" - Ninet Tayeb & the Rose Band",
            "vote": "6,5"
          }
        }
      }

    })

A: The problem is that your id's are actually strings, not numbers. You would either format your JSON correctly (not wrap numbers in quotes) or just iterate through list and parse those strings as integer values.
angular.forEach($scope.songs.radio, function (song) {
  song.id = parseFloat(song.id, 10);
});

A: There are two problems with your code:

*

*you do not want to sort the items by song.id but by id

*to sort your items they should be contained in an array rather then an object

I changed both points and this is a working plunkr: http://plnkr.co/edit/CaU5TbFQTm9hVls5S3RG?p=preview


text:
Q: breaking up a single array object into many objects Apologies if this is a novice question, but I've been struggling to figure this out with no luck. I'm trying to pull a users' twitter timeline using the AFOAuth2Manager framework. Everything makes sense except the returned JSON object is an array and the entire object is one giant object. I obviously want to break it up into different elements and store them in a dictionary, but have not been able to figure it out so far.
This is a VERY partial example of what the array object looks like. The complete object is this with about 20 or so more tweets with this format attached. I will post the entire json object if requested, but it seems pretty pointless to post the entire thing.
Heres my code:
[manager GET:@"/1.1/statuses/user_timeline.json?screen_name=jack"
      parameters:nil
         success:^(AFHTTPRequestOperation *operation, id responseObject ) {

             self.object = responseObject;
             NSLog(@"Success: %@", responseObject);

             if ([responseObject isKindOfClass:[NSArray class]]) {
                 NSLog(@"object is a nsarray class");
             } else if ([responseObject isKindOfClass:[NSDictionary class]]){
                 NSLog(@"object is a nsdictionary class");
             } else {
                 NSLog(@"object is a different class");
             }

             NSArray *response = [NSArray arrayWithObject:responseObject];

             NSLog(@"count %ld", [response count]);

             NSData *dataFromTwitter = [NSKeyedArchiver archivedDataWithRootObject:self.object];

             NSError *parseError = nil;
             NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:dataFromTwitter
                                                                          options:NSJSONReadingMutableLeaves | NSJSONReadingMutableContainers|NSJSONReadingAllowFragments
                                                                            error:&parseError];

             NSLog(@"response Dict: %@", responseDict);

             NSError *e = nil;
             NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:dataFromTwitter
                                                                  options:NSJSONReadingAllowFragments
                                                                    error:&e];

             NSLog(@"jsonArray: %@", jsonArray);

             NSError *jsonError2 = nil;

             id jsonObject = [NSJSONSerialization JSONObjectWithData:dataFromTwitter
                                                             options:NSJSONReadingAllowFragments
                                                               error:&jsonError2];

             if ([jsonObject isKindOfClass:[NSArray class]]) {
                 NSLog(@"its an array!");
                 NSArray *jsonArray = (NSArray *)jsonObject;
                 NSLog(@"jsonArray2 - %@",jsonArray);
             }
             else {
                 NSLog(@"its probably a dictionary");
                 NSDictionary *jsonDictionary = (NSDictionary *)jsonObject;
                 NSLog(@"jsonDictionary - %@",jsonDictionary);
                 NSLog(@"error %@", jsonError2);
             }

         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             NSLog(@"Failure: %@", error);
         }];

{
    contributors = "<null>";
    coordinates = "<null>";
    "created_at" = "Mon Feb 29 01:18:05 +0000 2016";
    entities =         {
        hashtags =             (
        );
        symbols =             (
        );
        urls =             (
        );
        "user_mentions" =             (
                            {
                id = 14616957;
                "id_str" = 14616957;
                indices =                     (
                    0,
                    7
                );
                name = "Jason Del Rey";
                "screen_name" = DelRey;
            },
                            {
                id = 19040598;
                "id_str" = 19040598;
                indices =                     (
                    8,
                    18
                );
                name = "\U0ca0_\U0ca0";
                "screen_name" = MikeIsaac;
            },
                            {
                id = 46063;
                "id_str" = 46063;
                indices =                     (
                    19,
                    30
                );
                name = "Hunter Walk";
                "screen_name" = hunterwalk;
            }
        );
    };
    "favorite_count" = 12;
    favorited = 0;
    geo = "<null>";
    id = 704113377920978944;
    "id_str" = 704113377920978944;
    "in_reply_to_screen_name" = DelRey;
    "in_reply_to_status_id" = 704112911116013568;
    "in_reply_to_status_id_str" = 704112911116013568;
    "in_reply_to_user_id" = 14616957;
    "in_reply_to_user_id_str" = 14616957;
    "is_quote_status" = 0;
    lang = en;
    place = "<null>";
    "retweet_count" = 0;
    retweeted = 0;
    source = "Twitter for iPhone";
    text = "@DelRey @MikeIsaac @hunterwalk this changes everything";
    truncated = 0;
    user =         {
        "contributors_enabled" = 0;
        "created_at" = "Tue Mar 21 20:50:14 +0000 2006";
        "default_profile" = 0;
        "default_profile_image" = 0;
        description = "#withMalala!";
        entities =             {
            description =                 {
                urls =                     (
                );
            };
        };
        "favourites_count" = 11433;
        "follow_request_sent" = "<null>";
        "followers_count" = 3458722;
        following = "<null>";
        "friends_count" = 1859;
        "geo_enabled" = 1;
        "has_extended_profile" = 1;
        id = 12;
        "id_str" = 12;
        "is_translation_enabled" = 0;
        "is_translator" = 0;
        lang = en;
        "listed_count" = 25944;
        location = "California, USA";
        name = Jack;
        notifications = "<null>";
        "profile_background_color" = EBEBEB;
        "profile_background_image_url" = "http://abs.twimg.com/images/themes/theme7/bg.gif";
        "profile_background_image_url_https" = "https://abs.twimg.com/images/themes/theme7/bg.gif";
        "profile_background_tile" = 0;
        "profile_image_url" = "http://pbs.twimg.com/profile_images/668328458519384064/FSAIjKRl_normal.jpg";
        "profile_image_url_https" = "https://pbs.twimg.com/profile_images/668328458519384064/FSAIjKRl_normal.jpg";
        "profile_link_color" = 990000;
        "profile_sidebar_border_color" = DFDFDF;
        "profile_sidebar_fill_color" = F3F3F3;
        "profile_text_color" = 333333;
        "profile_use_background_image" = 1;
        protected = 0;
        "screen_name" = jack;
        "statuses_count" = 19066;
        "time_zone" = "Pacific Time (US & Canada)";
        url = "<null>";
        "utc_offset" = "-28800";
        verified = 1;
    };
},

A: You show no code in your question, in a comment you state you have a responseObject but not how you came by it.
The JSON you are getting from somewhere will be text, you may have it as an NSString, NSData, an NSArray whose elements are these, etc.
You need to obtain that text and then parse it as JSON, the NSJSONSerialization class will handle the parsing for you, the first line of its description states:

You use the NSJSONSerialization class to convert JSON to Foundation objects and convert Foundation objects to JSON.

Once you have those Foundation objects - arrays, dictionaries, strings, numbers, etc. you can extract the fields you are interested in.
Once you've written some code to do this if it doesn't work and you are stuck ask a new question showing your code and someone will probably be able to help you further.
HTH


text:
Q: Strange Lag Behaviour of Activity with ViewPager and AsyncTask on API 21 I am really confused how to explain my problem and it is annoying me really badly. I have three devices: HTC Desire 510 (API 19 4.4.2), HTC M8 (API 21 5.0.1) and S4Mini (API 22 CM12.1) and I tries to run my app on all these devices.
Here is what my main app activity consists of-

*

*Sliding Tabs

*ViewPager

*ListView inside each ViewPager Fragment

*Asynctask in each ListView row

So, I open my app on all three devices and results are following

*

*HTC Desire 510 API 19 & S4Mini API 22: Activity opens and swipe between Fragments is really smooth along with listView Swipes. Everything works perfectly fluid.

*HTC M8 API 21: Activity takes few seconds to open, while swiping ViewPager choreographer is saying that app is dropping frames. Listview swipes are laggy too.

Continuing using app, I open new activity from a ListView item click which starts a services and set it to foreground, and after that I come back to my previous activity by tapping back (again at my initial activity). Here is the response again.

*

*All devices run activity smoothly. Even HTC M8 which was lagging before starting a foreground service starts working very snappy. Every single kind of lag is gone. But why after having app in foreground?

Here it is in a picture form

ONLY IN HTC M8, OTHER DEVICES ARE WORKING FAST EVERYWHERE
This is bothering me a lot, Almost all other devices I have checked are really smooth even on half the RAM and CPU of M8. Is there any exception for API 21 HTC device. I know this may looks really weird but this is what happening and annoying.
Please any kind of help or suggestions are appreciated. There is a lot bunch of code of all that stuff, it's really useless to share till I have clue where the problem can be. I really don't know if there were any difference in API 21 or maybe particularly HTC M8.
Thanks!


text:
Q: Possible option for PrimayKey in Table creation with KSQL? I've started working with KSQL and quite living the experience. I'm trying to work with Table and Stream join and the scenario is as below.
I have a sample data set like this:
"0117440512","0134217727","US","United States","VIRGINIA","Vienna","DoD Network Information Center"
"0134217728","0150994943","US","United States","MASSACHUSETTS","Woburn","Genuity"

in my kafka topic-1. Is a static data set loaded to Table and might get updated once in a month or so.
I have one more data set like:
{"state":"AD","id":"020","city":"Andorra","port":"02","region":"Canillo"}
{"state":"GD","id":"024","city":"Arab","port":"29","region":"Ordino"}

in kafka topic-2. Is a stream of data being loaded to streams.
Since Table cant be created without specifying the Key, my data don't have a unique column to do so. So while loading data from topic-1 to Table, what exactly should my key be? Remember my Table might get populated/updated once in a month or so with same data and new once too. With new data being loaded I can replace them with the key.
I tried to find if there's something like incremental value as we call PrimaryKey in SQL, but didn't find any.
Can someone help me in correcting my approach towards the implementation or a query to create a PrimaryKey if exists. Thanks

A: No, KSQL doesn't have the concept of a self-incrementing key. You have to define the key when you produce the data into the topic on which the KSQL Table is defined.
--- EDIT
If you want to set the key on a message as it's ingested through Kafka Connect you can use Single Message Transform (SMT).
            "transforms":"createKey,extractInt",
            "transforms.createKey.type":"org.apache.kafka.connect.transforms.ValueToKey",
            "transforms.createKey.fields":"id",
            "transforms.extractInt.type":"org.apache.kafka.connect.transforms.ExtractField$Key",
            "transforms.extractInt.field":"id"

See here for more details.


text:
Q: Defining XSD to validate groups of permitted XML attributes for the same element I would like to define an XSD that would validate the following XML.
<parameters>
    <param name="Maximum Error Threshold" type="integer">10</param>
    <param name="Auto Shutdown Timeout Duration" type="integer" unit="seconds">300</param>
    <param name="Flow Rate Adjusment" type="integer" unit="litrePerSec">0.5</param>
    <param name="Configuration Download Time" type="timeofday" format="timestring">03:20</param>
    <param name="Maximum Issue Value" type="integer" unit="cents" format="numericfloat">145.50</param>
</parameters>

I currently have a schema which looks something like:
  <xs:element name="parameters">
    <xs:complexType>
      <xs:sequence>
        <xs:element maxOccurs="5" minOccurs="5" ref="param"/>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
  <xs:element name="param">
    <xs:complexType>
      <xs:simpleContent>
        <xs:extension base="xs:NMTOKEN">
          <xs:attribute name="name" use="required" type="AttributeNames"/>
          <xs:attribute name="type" use="required" type="AttributeTypes"/>
          <xs:attribute name="format" use="optional" type="AttributeFormats"/>
          <xs:attribute name="unit" use="optional" type="AttributeUnits"/>
        </xs:extension>
      </xs:simpleContent>
    </xs:complexType>
  </xs:element>
  <xs:simpleType name="AttributeNames">
    <xs:restriction base="xs:token">
      <xs:enumeration value="Maximum Error Threshold"/>
      <xs:enumeration value="Auto Shutdown Timeout Duration"/>
      <xs:enumeration value="Flow Rate Adjusment"/>
      <xs:enumeration value="Configuration Download Time"/>
      <xs:enumeration value="Maximum Issue Value"/>
    </xs:restriction>
  </xs:simpleType>
  <xs:simpleType name="AttributeTypes">
    <xs:restriction base="xs:NCName">
      <xs:enumeration value="integer"/>
      <xs:enumeration value="timeofday"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="AttributeFormats">
    <xs:restriction base="xs:NCName">
      <xs:enumeration value="timestring"/>
      <xs:enumeration value="numericfloat"/>
    </xs:restriction>
  </xs:simpleType>

  <xs:simpleType name="AttributeUnits">
    <xs:restriction base="xs:NCName">
      <xs:enumeration value="seconds"/>
      <xs:enumeration value="litrePerSec"/>
      <xs:enumeration value="cents"/>
    </xs:restriction>
  </xs:simpleType>

This works. But it does not give me complete validation.
I would like to ensure that the appropriate attributes are present in the 'param' element (and that these attributes contain the appropriate values), depending on what the 'name' attribute contains.
For example;
If the 'name' attribute = "Auto Shutdown Timeout Duration", then the 'type' is required and can only be "integer" and the 'unit' is required and can be "hours", "minutes" or "seconds".
But if 'name' attribute = "Maximum Error Threshold", then the 'type' is required and can only be "integer" but 'unit' is not permitted.
So I decided to describe each parameter separately; i.e. something like:
  <xs:complexType name="MaxErrorParam">
    <xs:simpleContent>
      <xs:extension base="xs:NMTOKEN">
        <xs:attribute name="name" fixed="Maximum Error Threshold"/>
        <xs:attributeGroup ref="CounterParameterAttributes"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>

  <xs:complexType name="AutoShutdownParam">
    <xs:simpleContent>
      <xs:extension base="xs:NMTOKEN">
        <xs:attribute name="name" fixed="Auto Shutdown Timeout Duration"/>
        <xs:attributeGroup ref="TimeOutParameterAttributes"/>
      </xs:extension>
    </xs:simpleContent>
  </xs:complexType>

  <xs:attributeGroup name="CounterParameterAttributes">
    <xs:attribute name="type" use="required" fixed="integer"/>
  </xs:attributeGroup>

  <xs:attributeGroup name="TimeOutParameterAttributes">
    <xs:attribute name="type" use="required" fixed="integer"/>
    <xs:attribute name="format" use="required" type="TimeUnitsType"/>
  </xs:attributeGroup>

  <xs:simpleType name="TimeUnitsType">
    <xs:restriction base="xs:NCName">
      <xs:enumeration value="minutes"/>
      <xs:enumeration value="seconds"/>
      <xs:enumeration value="hours"/>
    </xs:restriction>
  </xs:simpleType>

But this meant that i needed to define the 'param' element as follows; this causes an error because the element 'param' is defined twice with different type.
  <xs:element name="parameters">
    <xs:complexType>
      <xs:all>
        <xs:element name="param" type="MaxErrorParam"/>
        <xs:element name="param" type="AutoShutdownParam"/>
        etc...
      </xs:>
    </xs:complexType>
  </xs:element>

Can anyone please suggest a solution or point me in the right direction?

A: Nobody has answered this, I hope it's still interesting to you. The approaches you outlined do not work: XML Schema cannot validate constraints of the form "if element X contains something then check Y". Also, you cannot have two elements with the same name but different types in the same container, as you said.
However, you what you can do is to 1) create a child element in param with a name of value and a type of  xs:anySimpleType and 2) use the native XML Schema type override mechanism (xsi:type):
<parameters xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <param name="Maximum Error Threshold">
        <value xsi:type="xs:int">10</value>
    </param>
</parameters>


text:
Q: Python dictionary setdefault() method used as a return value of a recursive function Say you want to get the nth Fibonacci Number. Then, one possibility is to use the recursive function
def Fib(n, d):
    """Assumes n is an int >= 0, d dictionary
    Returns nth Fibonacci number"""
    if n in d:
        return d[n]
    else:
        d[n] = Fib(n-1, d) + Fib(n-2, d)
        return d[n]

This works quite well. I tried to shorten this to
 def Fib(n, d):
        return d.setdefault(n, Fib(n-1, d) + Fib(n-2, d))

But when I can call it with
d={0:1, 1:1}
print(f(2, d))

, or even with f(1,d), it goes into infinite loop, and restarts the kernel. In fact, any function of this form, say
def f(n, d):
    return d.setdefault(n, f(n-1,d))

has the same problem. When I tried to debug this, I saw that n keeps decreasing pass the value 1. I guess I don't understand the implementation of this method. I presumed that the setdefault method first checks whether the key is in the dictionary and returns the value, and if not, then assigns the default value to the key and returns the default value. What am I missing here?(I am using Python 3.9.1 with Spyder 4.2.0)

A: You still need a base case otherwise there's nothing to stop it from calculating, fib(-1), fib(-2), fib(-99), ...
def fib(n, d):
  return n if n < 2 else d.setdefault(n, fib(n-1, d) + fib(n-2, d))

print(fib(10, {0:0, 1:1}))

55

The problem you are experiencing with setdefault is that python is an applicative order language. That means a functions arguments are evaluated before a the function is called. In the case of setdefault, we will evaluate fib(n-1,d) + fib(n-2,d) before we attempt to lookup n in d.
A better interface might be dict.setdefault(key, lambda: somevalue) where the lambda is executed only if the default needs to be set. We could write this as lazydefault below -
def lazydefault(d, key, lazyvalue):
  if key not in d:
    d[key] = lazyvalue()
  return d[key]

def fib(n, d):
  return lazydefault(d, n, lambda: fib(n-1, d) + fib(n-2, d))

print(fib(10, {0:0, 1:1}))

55


text:
Q: How to use a re-usable frame class in tkinter? I want to have a reusable frame with widgets within one of my screens (I'm going to reuse that frame later in another screen). That frame will be part of the screen, there will be additional widgets.
I tried creating a class for the reusable frame (class FrameBovenverdieping(tk.Frame):) which should be shown in the screen ViewBezettingBoven. However, the FrameBovenverdieping shows in each screen, also in StartPage and PageTwo. I want to have it only in ViewBezettingBoven.
Also, when I'm on ViewBezettingBoven, the buttons to switch screens don't work anymore
import tkinter as tk

PLATTEGROND_BOVEN_WIDTH = 1000
PLATTEGROND_BOVEN_HEIGHT = 720
PLATTEGROND_BENEDEN_WIDTH = 1000
PLATTEGROND_BENEDEN_HEIGHT = 720

class BezettingApp(tk.Tk):

    def __init__(self, *args, **kwargs):

        tk.Tk.__init__(self, *args, **kwargs)

        self.geometry("{0}x{1}+0+0".format(self.winfo_screenwidth(), self.winfo_screenheight()))
        self.bind("<Escape>", lambda e: e.widget.quit())

        container = tk.Frame(self)
        container.pack(side="top", fill="both", expand = True)
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)

        self.frames = {}

        for F in (StartPage, ViewBezettingBoven, PageTwo):

            frame = F(container, self)

            self.frames[F] = frame

            frame.grid(row=0, column=0, sticky="nsew")

        self.show_frame(StartPage)

    def show_frame(self, cont):

        frame = self.frames[cont]
        frame.tkraise()

class StartPage(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self,parent)
        label = tk.Label(self, text="Start Page")
        label.pack(pady=10,padx=10)

        button = tk.Button(self, text="Visit Page 1",
                        command=lambda: controller.show_frame(ViewBezettingBoven))
        button.pack()

        button2 = tk.Button(self, text="Visit Page 2",
                        command=lambda: controller.show_frame(PageTwo))
        button2.pack()

class ViewBezettingBoven(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        label = tk.Label(self, text="Page One!!!")
        self.parent = parent
        self.window = FrameBovenverdieping(self)

        label.pack(pady=10,padx=10)
        self.widgets()

    def widgets(self):

        button1 = tk.Button(self, text="Back to Home",
                        command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = tk.Button(self, text="Page Two",
                        command=lambda: controller.show_frame(PageTwo))
       button2.pack()

class FrameBovenverdieping(tk.Frame):

    def __init__(self, parent):
        tk.Frame.__init__(self, parent)
        self.parent = parent
        self.widgets()

    def widgets(self):
        photo = tk.PhotoImage(file='autplacement.png')
        w = PLATTEGROND_BENEDEN_WIDTH
        h = PLATTEGROND_BENEDEN_HEIGHT
        imagelabel = tk.Label(image=photo)
        imagelabel.image = photo
        imagelabel.pack()

class PageTwo(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        label = tk.Label(self, text="Page Two!!!")
        label.pack(pady=10,padx=10)

        button1 = tk.Button(self, text="Back to Home",
                        command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = tk.Button(self, text="Page One",
                        command=lambda: controller.show_frame(ViewBezettingBoven))
        button2.pack()

app = BezettingApp()
app.mainloop()

Output:
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Lonneke Kolkman\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:\Users\Lonneke Kolkman\Google Drive\Assortimens\BezettingAppPy\bezettingapp.py", line 74, in <lambda>
    command=lambda: controller.show_frame(StartPage))
NameError: name 'controller' is not defined
Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\Lonneke Kolkman\AppData\Local\Programs\Python\Python37\lib\tkinter\__init__.py", line 1705, in __call__
    return self.func(*args)
  File "C:\Users\Lonneke Kolkman\Google Drive\Assortimens\BezettingAppPy\bezettingapp.py", line 78, in <lambda>
    command=lambda: controller.show_frame(PageTwo))
NameError: name 'controller' is not defined
>>>

The program runs, but shows the reusable frame within each page though I want it only to show within ViewBezettingBoven.

A: Your controller variable is out of scope. If you send controller to the function I can run the code without errors:
class ViewBezettingBoven(tk.Frame):

    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)

        label = tk.Label(self, text="Page One!!!")
        self.parent = parent
        self.window = FrameBovenverdieping(self)

        label.pack(pady=10,padx=10)
        #send controller to function
        self.widgets(controller)

    def widgets(self,controller):

        button1 = tk.Button(self, text="Back to Home",
                        command=lambda: controller.show_frame(StartPage))
        button1.pack()

        button2 = tk.Button(self, text="Page Two",
                        command=lambda: controller.show_frame(PageTwo))
        button2.pack()


text:
Q: Matplotlib ``figure.titlesize`` rcParam I'm trying to update my matplotlib rcParams.  According to http://matplotlib.org/users/customizing.html, the option should be present, but it is not. These are the items I can find in my rcParam file:
      u'figure.autolayout': False,
      u'figure.dpi': 80.0,
      u'figure.edgecolor': u'w',
      u'figure.facecolor': u'0.75',
      u'figure.figsize': [46.666666666666664, 35.0],
      u'figure.frameon': True,
      u'figure.max_open_warning': 20,
      u'figure.subplot.bottom': 0.1,
      u'figure.subplot.hspace': 0.2,
      u'figure.subplot.left': 0.125,
      u'figure.subplot.right': 0.9,
      u'figure.subplot.top': 0.9,
      u'figure.subplot.wspace': 0.2,

Has this feature been removed or is it somehow hidden?

A: I think this is a new option added between v1.4.3 and v1.5.x. For example, compare the code on github for v1.4.3, with v1.5.x.
The documentation you linked to must be for v1.5.x. So, maybe you could upgrade to v1.5.x if you need that option?


text:
Q: Debugging a Managed Component from C++ Win32 I have a Win32 EXE that's written in VC++. I have implementation written in C#. I've got the VC++ EXE consuming the C# DLL as outlined here: http://support.microsoft.com/kb/828736. Works great, but I need to be able to debug. Both projects are loaded into the same .SLN, but breakpoints in the C# are never hit. Is there a way to debug this in VS2012?

A: Ah, turns out this is easy if you know the right button to push. On the C++ project properties, Configuration Properties -> Debugging -> Debugger Type = "Mixed".

A: Try adding a Project reference to the C# Dll from the C++ Project.  If you have already done that,  Please clean up the solution and build. This should solve the problem.


text:
Q: What is the cause of Tensorflow memory increase? The development environment is Docker + Anaconda3.
There were approximately 500,000 image data and training sessions.
The sample source is "https://www.tensorflow.org/tutorials/load_data/images?See hl=ko".
The model.fit function continues to increase memory.
What's the reason?

*

*The python3 process also increases.
import os
import numpy as np
from matplotlib import pyplot as plt
import matplotlib.image as mpimg
import random
import math
import time
import linecache

os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'

FILENAME = 'mnist'
USE_GPU = False

WIDTH = 128
HEIGHT = 128
EPOCHES = 20
BATCH_SIZE = 256
DENSE = 10

if USE_GPU:
    print('- device GPU')
    os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
    os.environ["CUDA_VISIBLE_DEVICES"] = "0"
else:
    print('- device CPU')
    os.environ["CUDA_VISIBLE_DEVICES"] = "-1"

    tf.debugging.set_log_device_placement(True)

from keras.callbacks import EarlyStopping
import tensorflow as tf
tf.config.list_physical_devices('GPU')
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, Dropout, Flatten
from tensorflow.keras.layers import Conv2D, MaxPooling2D
from tensorflow.python.client import device_lib
import tensorflow_datasets as tfds
import pathlib
from tqdm import tqdm
from time import sleep
import psutil

class_names = ''

def get_label(file_path):
    # Convert the path to a list of path components
    parts = tf.strings.split(file_path, os.path.sep)
    # The second to last is the class-directory
    one_hot = parts[-2] == class_names
    # Integer encode the label
    return tf.argmax(one_hot)

def process_path(file_path):
    label = get_label(file_path)
    # Load the raw data from the file as a string
    img = tf.io.read_file(file_path)
    img = decode_img(img)
    return img, label

def decode_img(img):
    # Convert the compressed string to a 3D uint8 tensor
    img = tf.io.decode_jpeg(img, channels=3)
    # Resize the image to the desired size
    return tf.image.resize(img, [HEIGHT, WIDTH])

def configure_for_performance(ds):
    ds = ds.cache()
    ds = ds.shuffle(buffer_size=1000)
    ds = ds.batch(BATCH_SIZE)
    ds = ds.prefetch(buffer_size=AUTOTUNE)
    return ds

fileDir = pathlib.Path(r'./data/train')
image_count = len(list(fileDir.glob('*/*.jpg')))

list_ds = tf.data.Dataset.list_files(str(fileDir/'*/*.jpg'), shuffle=False)
list_ds = list_ds.shuffle(image_count, reshuffle_each_iteration=False)

for f in list_ds.take(5):
    print(f.numpy())

class_names = np.array(sorted([item.name for item in fileDir.glob('*') if item.name != ".DS_Store"]))
train_dict = {k: v for v, k in enumerate(np.unique(class_names))}

validation_size = int(image_count * 0.2)
train_data = list_ds.skip(validation_size)
validation_data = list_ds.take(validation_size)

print(tf.data.experimental.cardinality(train_data).numpy())
print(tf.data.experimental.cardinality(validation_data).numpy())

AUTOTUNE = tf.data.AUTOTUNE
train_data = train_data.map(process_path, num_parallel_calls=AUTOTUNE)
validation_data = validation_data.map(process_path, num_parallel_calls=AUTOTUNE)

for image, label in train_data.take(1):
    print("Image shape: ", image.numpy().shape)
    print("Label: ", label.numpy())

train_data = configure_for_performance(train_data)
validation_data = configure_for_performance(validation_data)

image_batch, label_batch = next(iter(train_data))

start_total = time.time()

num_classes = 10
tf.keras.backend.clear_session()

model = tf.keras.Sequential([
  tf.keras.layers.Rescaling(1./255),
  tf.keras.layers.Conv2D(32, 3, activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Conv2D(32, 3, activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Conv2D(32, 3, activation='relu'),
  tf.keras.layers.MaxPooling2D(),
  tf.keras.layers.Flatten(),
  tf.keras.layers.Dense(128, activation='relu'),
  tf.keras.layers.Dense(num_classes)
])

model.compile(
  optimizer='adam',
  loss=tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True),
  metrics=['accuracy'])

start = time.time()

model.fit(train_data, validation_data=validation_data, epochs=3) #Here...

end = time.time()

model.save(FILENAME, save_format="tf")

converter = tf.lite.TFLiteConverter.from_saved_model(FILENAME)
converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS,
                                    tf.lite.OpsSet.SELECT_TF_OPS]
tflite_model = converter.convert()

open(FILENAME + '.tflite', 'wb').write(tflite_model)

with open('labels.txt', 'w') as file:
    for key in train_dict:
        file.write(str(train_dict[key]))
        file.write(':')
        file.write(str(key))
        file.write('\n')

end_total = time.time()

model.fit(train_data, validation_data=validation_data, epochs=3)

There is enough memory, (32G).
However, memory continues to grow.
I also replaced the memory library with libtcmalloc-minimal4.
What's the reason?


text:
Q: Typescript select property I am new to Typescript. I want to select property
This is my observable
 entries:Observable<Log[]>;

Log class contains many properties like _id, name, etc. Now I want to get an array of string[] by extracting name out of the observable. How would I do that?
Is there any documentation available for this? I am finding this Typescript thing too tough IMHO

A: Not sure if I understood correctly what you mean by extracting name out of the observable. If you want to extract all the property names into array of strings you can do it like this:
entries.subscribe((logs: Log[]) => {
   if (logs.length) {
      // extract all defined property names from first log
      let props = Object.keys(logs[0]);
      // do something with properties
   }
});

A: var source = entries.pluck('name').toArray();

var subscription = source.subscribe(names => {
  console.log(names);
});


text:
Q: Not able to add email field in react web app I am developing a small React App that is integrating with Mobx.  I have setup a members store which is the following:
import {observable, action, computed} from 'mobx';

 class MemberStore {
@observable members = [];

@action addMember(data) {
    const existing = this.members;
    this.members = existing.concat(data);
}

@computed get memberCount() {
    return this.members.length;
 }

}
const store = new MemberStore();
export default store;

Now I have a contact page which has a form of Name and email.  Now I am able to add a name but not the email.  So basically when I click the submit button I only get the name and a 0 next to the name.
import React, { Component } from 'react';
import Navbar from '../components/Navbar';
import Footer from '../components/Footer';
import Jumbotron from '../components/Jumbotron';
import {inject, observer} from 'mobx-react';

@inject('MemberStore')
@observer

class Contact extends Component {
 handleSubmit = (e) => {
    e.preventDefault();

    const member = this.member.value;
    const email = this.email.value;
    // const email = this.email.value;
    this.props.MemberStore.addMember(member, email);
    this.member.value = '';
    this.email.value = '';
}
render() {
    const {MemberStore} = this.props;

    return (

            <Navbar />
            <Jumbotron title="Contact Page" subtitle="You want to get in touch"/>

You have {MemberStore.memberCount} members.

               <form onSubmit={e => this.handleSubmit(e)}>
                   <input type="text" placeholder="Enter Your Name" ref={input => this.member = input }/>

                   <input type="text" placeholder= "Enter Your Email" ref={input => this.email = input }/>

                   <button>Submit</button>
               </form>

                {MemberStore.members.map((member,email) => (

                        {member}
                        {email}

                ))}

    )
  }
 }

 export default Contact;

Any help would be appreciated.

A: Your problem is probably that addMember takes one parameter data, and you're passing two parameters to it when you call it: addMember(name, email).
You should pass the name and email in as an object instead:
addMember({name, email})
Your code that maps the MemberStore.members array to JSX is also taking two parameters, when it should only take one object as a param:
{MemberStore.members.map({member,email}) => (
Note that I'm using the ES6 Object Literal Property Value Shorthand syntax above.


text:
Q: Help me understand what happens with the circuit when an AC signal is applied Consider this circuit.

Transistor is 2N2222A. Ic is chosen to be 10 mA.
Hfe is 225 for that current.
Resistors are calculated to have Vbe = 0.7V and Vc = 4.5V.
I am trying to understand what happens when I inject an AC signal at the base.
Suppose an AC signal that is 1Hz, 0.02V of peak voltage (varies between +0.02V and -0.02V). The capacitor is huge (100F), just to be transparent to 1Hz.
What I think happens is this: as the input increases from 0 to 0.02V, base increases from 0.7 to 0.72V. So the base resistor is now connected between Vcc (9V) and 0.72V. Base current is now less than before, because the difference in potential across base resistor is less than before.
If base current is less, collector current is less, right? If collector current is less, the difference in potential across the collector resistor is less. If so, Vc increases, right?
My simulator says Vc (collector voltage) decreases...
What is wrong with my analysis?
YES, I know this transistor configuration for amplifiers is bad. I am just trying to see what happens to this circuit.

A: Your capacitor is transparent at 1Hz, so current flows through the capacitor into the base. Yes, the current through R11 decreases a little, but the increased current through the capacitor is the larger effect. So, changes in the ac source voltage cause proportional changes in the base current.

A: The base-emitter junction looks rather diode-like. When forward biassed, it's a very low impedance. Increasing the voltage on the base by even a few mV increases the base current dramatically.
With a grounded emitter amplifier, driven by the voltage source you've shown, it's best not to think in terms of hfe, but of a linearised gm. That is a transconductance, a change of collector current with base voltage, centred around a mean bias point, for very small base voltage signals.
If this seems complicated, it's because you're approaching the single transistor amplifier using a difficult route.


text:
Q: Avoid duplicate entries in List How can I check that List< SelectListItem> doesn't contain or insert any duplicates in Mvc3. I have tried with !Contains
Thanks

A: Try this:
var list = new List<SelectListItem>();
list.Add(new SelectListItem { Text = "Some Text", Value = "Some Value" });
list.Add(new SelectListItem { Text = "Other Text", Value = "Other Value" });

var selectListItem = new SelectListItem { Text = "Some Text", Value = "Some Value" };
if(!list.Any(l => l.Value == selectListItem.Value)
{
    list.Add(selectListItem);
}

.Contains() compares if the object reference, not the Value property

A: var list = new List<SelectListItem>();

var selectListItem = new SelectListItem { Text = "Some Text", Value = "Some Value" };
if(list.FirstOrDefault(t => t.Value != selectListItem.Value) == null)
{
    list.Add(selectListItem);
}


text:
Q: mySQL query is very slow after using DISTINCT and GROUP BY? I have tables with following structure:
-- Table structure for table `temp_app`
--

CREATE TABLE IF NOT EXISTS `temp_app` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `vid` int(5) NOT NULL,
  `num` varchar(64) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`),
  KEY `vid` (`vid`),
  KEY `num` (`num`),
) ENGINE=InnoDB  DEFAULT CHARSET=utf8 AUTO_INCREMENT=69509;

-- Table structure for table `inv_flags`
--

CREATE TABLE IF NOT EXISTS `inv_flags` (
  `num` varchar(64) NOT NULL,
  `vid` int(11) NOT NULL,
  `f_special` tinyint(1) NOT NULL, /*0 or 1*/
  `f_inserted` tinyint(1) NOT NULL, /*0 or 1*/
  `f_notinserted` tinyint(1) NOT NULL, /*0 or 1*/
  `userID` int(11) NOT NULL,
  `timestamp` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
  KEY `num` (`num`),
  KEY `userID` (`userID`),
  KEY `vid` (`vid`),
  KEY `timestamp` (`timestamp`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Execution time of the following query is 9 seconds to display 30 records. What is wrong?
SELECT date_format(ifs.`timestamp`,'%y/%m/%d') as `date`
                ,count(DISTINCT ta.num) as inserted /*Unique nums*/
                ,SUM(ifs.f_notinserted) as not_inserted
                ,SUM(ifs.f_special)  as special
                ,count(ta.num) as links /*All nums*/
                from inventory_flags ifs
                LEFT JOIN temp_app ta ON ta.num = ifs.num AND ta.vid = ifs.vid
                WHERE ifs.userID = 3
                GROUP BY date(ifs.`timestamp`) DESC LIMIT 30

EXPLAIN RESULT
id  select_type table   type    possible_keys   key key_len ref rows    Extra
1   SIMPLE  ifs ref userID  userID  4   const   12153   Using where
1   SIMPLE  ta  ref vid,num num 194 ifs.num 1

A: COUNT DISTINCT can sometimes cause rotten performance with MySql. Try this instead:
select count(*) from (select distinct...

as it can sometimes prevent MySql from writing the entire interim result to disk.
Here is the MySql bug info:
http://bugs.mysql.com/bug.php?id=21849


text:
Q: How do I prevent the decimal point from repeating? I am in the early process of creating a calculator and just testing out my code. How do I prevent the decimal point from repeating? Basically, I need the decimal point to only be displayed once when clicked.

let display = document.querySelector('.display');

let numberButtons = document.querySelectorAll('.number').forEach(function(numberButtons) {
  numberButtons.addEventListener('click', showNumber)

  function showNumber() {
    if (display.textContent == 0) {
      display.innerHTML = "";
    }
    display.innerHTML += numberButtons.innerHTML;
  }
});

0

    <button class='number' id='one'>1</button>
    <button class='number' id="two">2</button>
    <button class='number' id='decimal-point'>.</button>

A: Another option is to disable button after it has been pressed. Make sure if you clear values to reset back to (disable: false).
function singleClick() {
document.getElementById("decimal-point").disabled = true;


text:
Q: C# Xunit code: End-of-file expected error. Cannot for the life of me figure out what the cause of this is I'm currently trying to learn the C# fundamentals through Pluralsight and I'm currently at the Test Runner tutorial. I'm getting two problems which for the life of me I can't figure out, as it looks to me like I have the open/close brackets in all the right places.
They say:
Type or namespace definition, or end-of-file expected [GradeBook.Tests] csharp(CS1022) [26, 6]
Type or namespace definition, or end-of-file expected [GradeBook.Tests] csharp(CS1022) [27, 1]

And the code I'm trying to compile is:
using System;
using Xunit;

namespace GradeBook.Tests
{
    public class BookTests
    {
        [Fact]
        public void Test1()
        {
            //arrange
            var book = new Book("");
            book.AddGrade(89.1);
            book.AddGrade(90.5);
            book.AddGrade(77.3);

            //act
            var result = book.GetStatistics();

            //assert
            Assert.Equal(85.6, result.Average);
            Assert.Equal(90.5, result.High);
            Assert.Equal(77.3, result.Low);
        }
    }
}

I'm probably missing something super obvious but I'm really struggling to figure out exactly what it is.
Much appreciated!


text:
Q: Show Duplicates on MySQL bulk insert I have a CSV file which I need to enter into my Database. My modus operandi is a Bulk insert. One of the columns has a uniqueness constraint attached to it but it is not the primary column. If there is a duplicate entry, it correctly skips the line and does not enter it into the database. (On command line it indicates Duplicates: n, where n is  the total number of duplicates).
Is there anyway I can retrieve the duplicate row numbers ? For instance, using Show Warnings or Show Errors, it states the last MySQL errors and warnings, is there anyway I can retrieve the duplicates from MySQL alone ?
Thanks.

A: You could enter the data into a temporary table first, without the uniqueness constraint, and perform a query to find all the duplicates.
SELECT unique_column, count(*) c
FROM temp_tablename
GROUP BY unique_column
HAVING c > 1;

Then copy it from the temporary table to the real table with:
INSERT IGNORE INTO tablename SELECT * FROM temp_tablename;


text:
Q: Wrap every object in array in  and then return its value as  I have array of objects and i try iterate through this array and  wrap each object in this array in

 tags and then return all values of this particular object as 	.
Kindly ask for any support, i stuck there.
  private function has_the_attribute($key) {
        $object_prop = get_object_vars($this);
        return array_key_exists($key, $object_prop);
      } // has atribute
  public static function instantation($the_record) {
    $the_object = new self;

    foreach ($the_record as $key => $value) {
      if($the_object->has_the_attribute($key)) {
        $the_object->$key = $value;
      }
    }

    return $the_object;

  } // instantation

  public static function find_this_query($sql) {
    global $database;
    $result_set = $database->query($sql);
    $the_object_array = array();

    while($row = mysqli_fetch_array($result_set)) {
      $the_object_array[] = self::instantation($row);
    }

    return $the_object_array;

  } // find_this_query

public static function show_user_tasks($user_id) {
    global $database;
    $the_result_array = self::find_this_query("SELECT * FROM tasks WHERE user_id = '{$user_id}' ");
    !empty($the_result_array) ? array_shift($the_result_array) : false;
    // print_r ($the_result_array);

    for($i = 0; $i < count($the_result_array) - 1; $i++) {
      echo "
";
      foreach($the_result_array[$i] as $key => $value) {
        echo "" . $key->$value . "	";
      }
      echo "
";
    }

    }

Here also goes my var_dump
     array (size=25)
  0 =>
    object(Task)[8]
      public 'id' => string '1' (length=1)
      public 'name' => string '432 Dell Inspirian 500 Windows 7 Sat, 29 Apr 2017 23:43:10 +0200' (length=64)
      public 'pc_type' => string 'Dell Inspirian 500' (length=18)
      public 'os_type' => string 'Windows 7' (length=9)
      public 'description' => string 'Mam duży problem' (length=17)
      public 'status' => string '1' (length=1)
      public 'comments' => null
      public 'start_date' => string '2017-04-29 23:43:10' (length=19)
      public 'end_date' => null
      public 'user_id' => string '432' (length=3)
      public 'agent_id' => string '901' (length=3)
  1 =>
    object(Task)[9]
      public 'id' => string '2' (length=1)
      public 'name' => string '#432 Dell Inspirian 500 Windows 7 Sun, 30 Apr 2017 00:22:48 +0200' (length=65)
      public 'pc_type' => string 'Dell Inspirian 500' (length=18)
      public 'os_type' => string 'Windows 7' (length=9)
      public 'description' => string 'dadasda' (length=7)
      public 'status' => string '1' (length=1)
      public 'comments' => null
      public 'start_date' => string '2017-04-30 00:22:48' (length=19)
      public 'end_date' => null
      public 'user_id' => string '432' (length=3)
      public 'agent_id' => string '901' (length=3)
      ...