text:
Q: PHPMailer randomly stops sending mail after around 175 sent emails I'm using PHPMailer to send a newsletter out from a list of emails in a database. The script queries the database, puts the data into an array with a while loop, and in the while loop creates and sends the email.
It works fine until after 150 or so emails are sent, then it randomly stops. As an example, email blast #1 failed after 161 sent emails, email blast #2 failed after 165 sent emails, and email blast #3 failed after 182 sent emails.
I have been researching and researching and cannot find the cause to this. Right now I send each email in it's on To: message, and don't send them using the BCC: route. Could it be settings on my server? If so, what should I be looking for?
I also have a little bit of debugging built in. The sql script at the end adds the email to the database, along with the specific time it was sent, so that I can tell exactly how many get sent, which email stops the process, and how long it takes.
The emails it stops on show no pattern (meaning they are different email providers) and it only takes around 10 - 12 minutes to send out that many. My script timeout on the server is way high than that so that isn't the cause.
My code is as follows:
$mail = new PHPMailer();
$mail->IsSMTP();                                      // set mailer to use SMTP
$mail->Host = "*server ip here*";  // specify main and backup server
$mail->SMTPKeepAlive = true;                  // SMTP connection will not close after each email sent
$mail->SMTPAuth = false;     // turn on SMTP authentication
$mail->Username = "*user*";  // SMTP username
$mail->Password = "*pass*"; // SMTP password

while($select2 = sqlsrv_fetch_array($select)) {
$email = $select2['email'];
$unid    = $select2['id'];
$unemail = $select2['email'];
$to = $email;
$from = "newsletter@site.com";
$new_date = date("n/j/y - g:i:s a");
$headers = "From: $from\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$message2 = "";
$message2 .= $message;
$message2 .= "";

$mail->From = "newsletter@site.com";
$mail->FromName = "Newsletter";
$mail->AddAddress($to);
$mail->AddReplyTo("newsletter@site.com", "Website.com");

$mail->IsHTML(true);                                  // set email format to HTML

$mail->Subject = $subject;
$mail->Body    = $message2;

if(!$mail->Send()) {
    die("mail() Failed to send email to $to.");
    echo "

Mailer Error: " . $mail->ErrorInfo;
    exit;
} else {
    $make_sent_query = "INSERT INTO emailssent (email_signup_id, email, datesent) VALUES (?, ?, ?)";
    $params_sent = array($unid, $to, $new_date);
    $add_to_sent = sqlsrv_query($conn, $make_sent_query, $params_sent);
    if($add_to_sent) {
        echo "Message sent for email $to
";
    } else {
        die("Mail sent, but failed to insert into Sent Emails database.");
    }
}

$mail->ClearAddresses();  //clear addresses for next loop
}

A: Could this be being caused by your local mail server? If you're sending out 150 emails in a short space of time, it might be assuming that it's spamming, and stop once you reach a certain amount.
You could try slowing it down with a sleep() after sending each mail? Just a second or two should be enough if that is the cause....
Is there a reason why you want to avoid using BCC? You can send email to multiple recipients and reduce the number of emails you're sending to a fraction of what you're sending now, though it is at the cost of not being able to individualise each email.

A: I think it's timeout problem. And crontab can solve your problem http://en.wikipedia.org/wiki/Cron . You can write script to send your emails and set your crontab to run this script every minutes. Then you have never had a timeout.

A: One of the potential reasons can be PHP timing out the script. Every script gets to run for a limited amount of time. If your script takes more time than that then PHP will simply kill the script. Typically that should cause an error being reported in the error logs. Check your apache error log messages - they might contain a hint.

A: it is caused by the max_execution_time in XAMPP,
so, the script of sending emails will stop when the script is running above the max_execution_time.
the default max_execution_time  is 120seconds.
sending many emails takes much times.
you can change it by adding this script
ini_set('max_execution_time', 0);

put it before your email blasting script section, it tells the php to set it to unlimited max_execution_time.


text:
Q: Trying to plot timedelta, but the yaxis is in 1e14, want format HH:MM:SS I am plotting date time on the xaxis (which is actual dates) and then timedelta on the yaxis, which is actually time spans, or amount of time. Originally I was using date time for the yaxis, but I came across the usecase where the time values went over 24 hours, and then it broke the code. So instead I had to use timedelta in order to accommodate these values. But when I try to plot it using plot_date, the yaxis with the timedelta values comes out funny.

I have my information stored in a dataframe originally, and then change the values to a timedelta. This is the code I have to output this graph
import datetime as dt
import matplotlib.dates as mdates
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib as mpl
from matplotlib.backends.backend_pdf import PdfPages

plt.close('all')

#put data into dataframe
location='D:\CAT'
csvpath=location+('\metrics_summaryTEST.csv')
print csvpath
df=pd.read_csv(csvpath)

#setup plot/figure
media = set(df.mediaNumber.values)
num_plots = len(media)
ax = plt.gca()
pdfpath=location+('\metrics_graphs.pdf')
pp = PdfPages(pdfpath)

#declaring some variables
publishTimevals=np.zeros(len(df.publishTime.values),dtype="S20")
xdates=np.zeros(len(df.publishTime.values),dtype="S20")
ytimes=np.zeros(len(df.totalProcessTime.values),dtype="S8")

for f in sorted(media):
    name = f
    plt.figure(f)
    plt.clf()
    color = next(ax._get_lines.color_cycle)
    #PROCESS PUBLISHTIME
    publishTimevals= df.loc[df['mediaNumber']==f,['publishTime']]
    xdates = map(lambda x: mpl.dates.date2num(dt.datetime.strptime(x, '%Y-%m-%d %H:%M')),publishTimevals.publishTime)
    #PROCESS TOTALPROCESSTIME
    totalProcessTimevals= df.loc[df['mediaNumber']==f,['totalProcessTime']]
    ytimes = pd.to_timedelta(totalProcessTimevals.totalProcessTime)
    plt.plot_date(xdates,ytimes,'o-',label='totalProcessTime',color=color)
    print ytimes
    plt.show()
    #format the plot
    plt.gcf().autofmt_xdate()
    plt.xlabel('publishTime')
    plt.ylabel('ProcessTime HH:MM:SS')
    plt.legend(loc=8, bbox_to_anchor=(0.5,-0.3),ncol=3,prop={'size':9})
    ax.grid('on')
    plt.title('%s Processing Time' % (f))
    plt.margins(0.05)
    #plt.grid('on')
    plt.minorticks_on()
    plt.grid(which = 'minor', alpha = 0.3)
    plt.grid(which = 'major', alpha = 0.7)
    plt.show()

Could anyone point out what's going on here?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I set visual studio to use psake when building? I would like to set visual studio to use Psake build by default when building. Is this possible slash more effort than its worth?

A: Possible yes, and certainly worth the effort if you value consistency in the build, which it sounds like you do.
StudioShell is the main player, and here's a tidy blog post on the matter.


text:
Q: How to handle multiple network call in Alamofire I need to call 2 apis in a view controller to fetch some data from server, I want them to start at the same time, but next step will only be triggered if both of them are returned(doesn't matter it's a success or failure).
I can come up with 2 solutions :
1. Chain them together. Call api1, call api2 in api1's result handler, wait for api2's result
2. Set 2 Bool indicator variables, create a check function, if both of these indicators are true, do next. In both Apis result handler, set corresponding indicator variable, then call check function to decide if it's good to go
First one is not sufficient enough, and I can't say the second one is a elegant solution. Does Alamofire has something like combine signal in Reactivecocoa? Or any better solution?

A: Your assessment is 100% correct. At the moment, the two options you laid out are really the only possible approaches. I agree with you that your second option is much better than the first given your use case.
If you wish to combine ReactiveCocoa with Alamofire, then that's certainly possible, but hasn't been done yet to my knowledge. You could also investigate whether PromiseKit would be able to offer some assistance, but it hasn't been glued together with Alamofire yet either. Trying to combine either of these libraries with the Alamofire response serializers will not be a trivial task by any means.
Switching gears a bit, I don't really think ReactiveCocoa or PromiseKit are very well suited for your use case since you aren't chaining service calls, you are running them in parallel. Additionally, you still need to run all your parsing logic and determine whether each one succeeded or failed and then update your application accordingly. What I'm getting at is that Option 2 is going to be your best bet by far unless you want to go to all the effort of combining PromiseKit or ReactiveCocoa with Alamofire's response serializers.
Here's what I would suggest to keep things less complicated.
import Foundation
import Alamofire

class ParallelServiceCaller {
    var firstServiceCallComplete = false
    var secondServiceCallComplete = false

    func startServiceCalls() {
        let firstRequest = Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["first": "request"])
        firstRequest.responseString { request, response, dataString, error in
            self.firstServiceCallComplete = true
            self.handleServiceCallCompletion()
        }

        let secondRequest = Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["second": "request"])
        secondRequest.responseString { request, response, dataString, error in
            self.secondServiceCallComplete = true
            self.handleServiceCallCompletion()
        }
    }

    private func handleServiceCallCompletion() {
        if self.firstServiceCallComplete && self.secondServiceCallComplete {
            // Handle the fact that you're finished
        }
    }
}

The implementation is really clean and simple to follow. While I understand your desire to get rid of the completion flags and callback function, the other options such as ReactiveCocoa and/or PromiseKit are still going to have additional logic as well and may end up making things more complicated.
Another possible option is to use dispatch groups and semaphores, but that really adds complexity, but could get you much closer to a ReactiveCocoa or PromiseKit styled approach.
I hope that helps shed some light.

A: DispatchGroup would be a good option to handle multiple dependent requests in parallel
func loadData() {
    let dispatchGroup = DispatchGroup()

    func startRequests() {
        dispatchGroup.enter()
        loadDataRequest1()
        dispatchGroup.enter()
        loadDataRequest2()

        dispatchGroup.notify(queue: .main) { [weak self] in
            // Process your responses
        }

        loadDataRequest1() {
            // Save your response
            dispatchGroup.leave()
        }

        loadDataRequest2() {
            // Save your response
            dispatchGroup.leave()
        }
    }

    startRequests()
}


text:
Q: Join 2 table in Java using two different connections I have a problem. I have to do a join between 2 tables on 2 different database. I can not use the dblink. The only solution is a join in Java using two different connections.
My question is: In Hibernate you can do this?
In Java there are frameworks that allow me to do a join between two tables in two different databases?


text:
Q: How to set some config parameters for job in spring batch so that it can be used by steps and child jobs? How to set some config parameters for job e.g input file path. My use case is, I have some jobs which processes data in input files and those jobs are triggered as a part of other jobs e.g.
<job id="jobA">
    <step id="stepA" >
        <job ref="jobC"/>
    </step>
</job>

<job id="jobB">
    <step id="stepB" >
        <job ref="jobC"/>
    </step>
</job>

<job id="jobC">
    <step id="stepC" >
        <tasklet ref="steCTasklet" />
    </step>
</job>

So here, JobA and JobB triggeres jobC. JobC process data in input file provided by JobA and JobB. How do I set the different input file path for JobA and JobB so that they are passed to JobC.
We can pass it as parameters to JobA and JobB but as it is fixed for JobA and JobB, I dont want to pass them as a parameter from outside.
Also the input file path should be accessible to other steps in JobA and JobB which do not trigger other jobs.
Also I am using spring-batch-admin so I do not have direct access to job launcher as it has its own.

A: The JobStep can take a JobParameterExtractor as a dependency that will allow you to extract the job parameters you need from the StepExecution.  The implementation we provide is the DefaultJobParametersExtractor.  This pulls the job's parameters from the StepExecution's ExecutionContext (you specify what keys to use).  This implementation also includes all of the parent job's parameters in what is passed to the sub job as parameters.
You can read more about the JobParametersExtractor at the links below.
http://docs.spring.io/spring-batch/trunk/reference/html/configureStep.html#external-flows
http://docs.spring.io/spring-batch/trunk/apidocs/org/springframework/batch/core/step/job/JobParametersExtractor.html


text:
Q: $.each jquery loop printing one "undefined" for every element after getJSON request, grid data prints perfectly I'm doing a JSON request and after I loop through the elements and they rows are printed perfectly. The thing is that I keep seeing one undefined printing for every element on the top of the grid I'm building, How do I get rid of it?......

undefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefinedundefined

 $("#newsletters").click(function(){
        $.getJSON("/newsletter/getNewsletters", function(result){

            var grid="

";
            grid+="

	Año	Mes	Quincena			Publicado

";

             grid+="
<button id='agregar_button' onclick='crearNuevoNewsLetter()'>Nuevo</button>
";

             $.each(result, function(i, elem){

                    //show view fieldset, son los campos que se muestran para visualizar los datos

                    grid+=mostrarElementosViewMode(elem);

                    //crea los hidden fields asociados a los view fields creados arriba de este

                    grid+=crearRowHidden(elem);

                });

            grid+="
";

            $("#grilla").html(grid);

        });

    });

function mostrarElementosViewMode(elem){

    var elemento;

    elemento+="
";

    elemento+="<input type='hidden' value='"+elem.id+"'>	";

    elemento+=""+elem.anio+"	";

    elemento+=""+elem.mes+"	";

    elemento+=""+elem.quincena+"	";

    elemento+="<button id='editar_"+elem.id+"' value='Editar' onclick='muestraEditarFieldsNewsletter(\""+elem.id+"\")'>Editar	";

    elemento+="<button id='eliminar_newsletter_"+elem.id+"' value='Eliminar'>Eliminar	";

    if(elem.publicado == 1){
        elemento+="<input type='checkbox' id='publicado_view_"+elem.id+"' name='publicado' checked='checked'>	";
    } else {
        elemento+="<input type='checkbox' id='publicado_view_"+elem.id+"' name='publicado'>	";
    }

     elemento+="
";

    return elemento;

}

function crearRowHidden(elem){

    var nuevoHiddenFieldSet="";

    nuevoHiddenFieldSet+="
";

    nuevoHiddenFieldSet+="<input type='hidden' value='"+elem.id+"'>	";

    nuevoHiddenFieldSet+="<input name='anio' value='"+elem.anio+"' id='anio_"+elem.id+"' />	";

    nuevoHiddenFieldSet+="<input name='mes' value='"+elem.mes+"' id='mes_"+elem.id+"' />	";

    nuevoHiddenFieldSet+="<input name='quincena' value='"+elem.quincena+"' id='quincena_"+elem.id+"' />	";

    nuevoHiddenFieldSet+="<button value='Guardar' name='guardar_newsletter' id='guardar_newsletter_"+elem.id+"' onclick='guardarNewsletter("+elem.id+",\"update\")'>Guardar	";

    nuevoHiddenFieldSet+="	";

    if(elem.publicado==1){
        nuevoHiddenFieldSet+="<input type='checkbox' id='publicado_"+elem.id+"' name='publicado' checked='checked'>	";
    }else{
        nuevoHiddenFieldSet+="<input type='checkbox' id='publicado_"+elem.id+"' name='publicado'>	";
    }

    nuevoHiddenFieldSet+="
";

    return nuevoHiddenFieldSet;

}

and the web service returns this JSON:
[{"id":"12","anio":"2016","mes":"1","quincena":"4","publicado":"1"},{"id":"11","anio":"0000","mes":"1"
,"quincena":"1","publicado":"1"},{"id":"10","anio":"2000","mes":"1","quincena":"1","publicado":"1"},
{"id":"9","anio":"2000","mes":"1","quincena":"5","publicado":"1"},{"id":"8","anio":"0000","mes":"1","quincena"
:"1","publicado":"1"},{"id":"6","anio":"0000","mes":"1","quincena":"3","publicado":"1"},{"id":"5","anio"
:"2016","mes":"1","quincena":"5","publicado":"1"},{"id":"4","anio":"2016","mes":"1","quincena":"4","publicado"
:"1"},{"id":"3","anio":"2016","mes":"1","quincena":"3","publicado":"1"},{"id":"2","anio":"2016","mes"
:"1","quincena":"2","publicado":"1"},{"id":"1","anio":"2016","mes":"2","quincena":"1","publicado":"1"
}]

A: I think you must change
function mostrarElementosViewMode(elem){

    var elemento;

to
function mostrarElementosViewMode(elem){

    var elemento = '';


text:
Q: pymongo use string to query instead of dictionary Is there a way in pymongo to use a string to execute a query instead of a dictionary?
I would like to be able to use exactly the same syntax as on MongoDB shell from python/pymongo. Is that possible?

A: MongoDB shell is full-featured javascript console/interpreter with some bindings to message with a mongodb server. In contrast PyMongo lacks embedded javascript interpreter or even javascript parser so you could not execute MongoDB shell queries as-is.
Note that mongo shell queries are not json documents as they are able to contain some functions and some object constructors such as {value: 2+2}.

A: The eval() function might be what you're looking for.  Note that it executes the JS code on the db server -- NOT in a Mongo shell on some client.  Therefore it comes with lots of warnings, and I would strongly advise against using it in a serious production situation.  See the Mongo db.eval docs for details and examples.


text:
Q: MVC3 Routes - how to ensure a route with a specific value takes precedence? Given the following two defined routes:
        routes.MapRoute(name: "CityCategoryPage", url: "{city}-{state}/{categoryName}/__c/", defaults: new { controller = "Home", action = "GeoSubCategories" });
        routes.MapRoute(name: "CityStateCategoryResults", url: "{city}-{state}/{categoryName}/{searchTerm}/{pageNumber}/{pageSize}", defaults: new { controller = "Results", action = "SearchCityStateCategory", pageNumber = UrlParameter.Optional, pageSize = UrlParameter.Optional });

If I remove the second route, I get the expected action of seeing the results on the home page.  However with the second route present, I'm always forwarded to a results page.
I have an idea as to why this is happening:  "_c" is still seen as an optional parameter which matches the optional condition for the second route, but not sure how to get this to work.  I would prefer not to append the "_c" to the URL - also wondering if there is another way around this?
Thanks.

A: If I understand you correctly you want the frontpage to be displayed if no search term is provided?
If so, try to match the route with the optional searchTerm first, and default to the home page route if no searchTerm is present, like so:
routes.MapRoute(name: "CityStateCategoryResults", url: "{city}-{state}/{categoryName}/{searchTerm}/{pageNumber}/{pageSize}", defaults: new { controller = "Results", action = "SearchCityStateCategory", pageNumber = UrlParameter.Optional, pageSize = UrlParameter.Optional });
routes.MapRoute(name: "CityCategoryPage", url: "{city}-{state}/{categoryName}/", defaults: new { controller = "Home", action = "GeoSubCategories" });


text:
Q: What is the comma character meaning in right side of expression in Ruby Excuse me for this basic question but, I couldn't find the answer on Google.
I am new to Ruby and came across to this line of code:
self.primary_keys = :role_id, :action_name

What I understand from it is that self.primary_keys is a Class variable and is assigned an array or hash of symbols?
What means the right side of the expression (:role_id, :action_name)?
What is the type of it?

A: It's two symbols separated by a comma, and is an implicit array.
Equivalent to
self.primary_keys = [:role_id, :action_name]

It's more common to see the technique used on the left side of an assignment.
name, age = ["George", 21]

puts name
=> "George"

puts age
=> 21

The feature lets you swap the contents of variables without an intermediate variable.
For example, in some languages to swap a and b you need a temporary variable
temporary = a
a = b
b = temporary

In Ruby you can do
a, b = b, a

A: It's assignment
x, y = ["Srini", 25]
puts x
=> "Srini"
puts y
=> 25


text:
Q: In Middle of the process application closes in android? I have one activity which download data from the web. In middle of the downloading process application closes if I start downloading process more than one time. I am using AsyncTask to download data and Runnable to get the steps completed and. Here is my code. Do I have to remove callback for handler at finish of the task? If i put remove callback in pause or destroy method it gives force close error.
mBackgroundHandler = new Handler();
mRunnable = new Runnable()
{
    public void run()
    {
        mCounterProgress = KamaApplication.getStep();
        Log.v(TAG, "Progress: " + mCounterProgress);
        mRefreshProgress.setProgress(mCounterProgress);
        mRefreshProgress.invalidate();

        if(KamaApplication.getTotalStep() == 100 && KamaApplication.getStep() == 99)
        {
            mStop = true;
        }

        if(!mStop)
        {
            mBackgroundHandler.postDelayed(this, 1000);
        }
    }
};
mBackgroundHandler.postDelayed(mRunnable, 1000);

Here is my AsyncTask
private class DownloadFilesTask extends AsyncTask<Void, Integer, Void>
{
    protected Void doInBackground(Void... params)
    {
        try
        {
            StepsGeneratorInputJsonData stepsGeneratorInputJsonData = new StepsGeneratorInputJsonData();
            stepsGeneratorInputJsonData.provider = "Android";
            stepsGeneratorInputJsonData.identification = "Vogue";
            stepsGeneratorInputJsonData.password = "abcd";
            mResult = createAndExecuteStepsGenerator(stepsGeneratorInputJsonData);
            JSONObject mNewJSONObject = new JSONObject(mResult);
            String mEndDate = mNewJSONObject.getString("endDate");
            if(mEndDate.equals("null"))
            {
                mRefreshSuccess = false;
            }
            else
            {
                mRefreshSuccess = true;
            }

        }
        catch (Exception eException)
        {
            Log.v(TAG, "HotTestGettingError: " + eException.toString());
            mRefreshSuccess = false;
        }
        return null;
   }
   protected void onProgressUpdate(Integer... progress)
   { }
   protected void onPostExecute(Void result)
   {
        if(mRefreshSuccess)
        {
            insertData();
        }
        else
        {
            Message mMessage = new  Message();
            mMessage.what = 0;
            mHandler.sendMessage(mMessage);
        }
        mBackgroundHandler.removeCallbacks(mRunnable);
        updateDisplay();
    }
}

And I saw the logcat and got this :
06-25 12:08:28.007: INFO/WindowManager(128): WIN DEATH: Window{408fc1d8 com.mygosoftware.kama/com.mygosoftware.kama.Usage paused=false}
06-25 12:08:28.011: INFO/ActivityManager(128): Process com.mygosoftware.kama (pid 17691) has died.
06-25 12:08:28.078: INFO/ActivityManager(128): Start proc com.sec.android.app.twlauncher for activity com.sec.android.app.twlauncher/.Launcher: pid=17817 uid=10015 gids={3003, 1015, 3002}
06-25 12:08:28.078: INFO/ActivityManager(128): Low Memory: No more background processes.
06-25 12:08:28.148: INFO/Zygote(17817): Zygote: pid 17817 has CALL PRIVILEGED permission, then set capability for CAP_SYS_ADMIN (21)
06-25 12:08:28.312: INFO/ActivityThread(17817): Pub com.sec.android.app.twlauncher.settings: com.sec.android.app.twlauncher.LauncherProvider
06-25 12:08:28.445: INFO/Launcher(17817): onCreate():  product model family:S1 product model : GT-I9000

06-24 16:47:38.269: ERROR/InputDispatcher(128): channel '40823250 com.mygosoftware.kama/com.mygosoftware.kama.Usage (server)' ~ Consumer closed input channel or an error occurred.  events=0x8
06-24 16:47:38.269: ERROR/InputDispatcher(128): channel '40823250 com.mygosoftware.kama/com.mygosoftware.kama.Usage (server)' ~ Channel is unrecoverably broken and will be disposed!
06-24 16:47:38.304: INFO/ActivityManager(128): Process com.mygosoftware.kama (pid 7637) has died.

I have put in AndroidManifest file
<activity android:name=".Usage" android:screenOrientation="portrait"
        android:clearTaskOnLaunch="true">

and also set
 intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

and also put
    onPause() method in my activity.
Moreover, I have referred this link Activity restarts on Force Close. Mine is very similar problem. I have done everything what they written in answer but still getting the error.
What should I do to remove this error?
Thanks.

A: private void startDownload() {
        String url = GlobalVariable.Getstr();
        new DownloadFileAsync().execute(url);

    }
class DownloadFileAsync extends AsyncTask<String, String, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(DIALOG_DOWNLOAD_PROGRESS);
        }

        @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(this);

//          mProgressDialog.setIcon(R.drawable.icon);
            mProgressDialog.setIcon(R.drawable.tab_icon_pitchforkfm);
            mProgressDialog.setTitle("Downloading file... "
                    + fileName.toString());

            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }

    @Override
        protected String doInBackground(String... arg0) {

            int len1 = 0;
            int count;
            try {
                URL url = new URL(GlobalVariable.Getstr());
                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();
                int lenghtOfFile = c.getContentLength();
                Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);
                String PATH = Environment.getExternalStorageDirectory()
                        + "/download/";
                Log.v(LOG_TAG, "PATH: " + PATH);
                File file = new File(PATH);
                file.mkdirs();

                 String fileName = "workTest.mp3";

                File outputFile = new File(file, fileName);

                FileOutputStream fos = new FileOutputStream(outputFile);

                InputStream is = c.getInputStream();

                byte[] buffer = new byte[1024];
                long total = 0;

                while ((count = is.read(buffer)) != -1) {
                    total += count;
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));
                    // fos.write(buffer, 0, len1);
                    fos.write(buffer, 0, count);
                }
                fos.close();
                is.close();

            } catch (IOException e) {
                Log.d(LOG_TAG, "Error: " + e);
            }
            return null;
        }

        protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC", progress[0]);

            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }
        protected void onPostExecute(String unused) {
            dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
            //refreshList();
            Toast.makeText(
                    FindFilesByType.this,
                    "Downloading of " + fileName
                            + " complete.", Toast.LENGTH_LONG).show();
            try{
            refreshList();
            } catch (Exception e) {
                Toast.makeText(FindFilesByType.this, "ERROR " + e.toString(),
                        Toast.LENGTH_LONG).show();
            }

above is my entire code.. this code is downloading a specified mp3 file from the URL.. and save it to the SDCARD.. and showing me the progressbar also depending upone the downloading has completed..hope this useful for you.. still getting
        and problem the let me know Happy coding:):) Pragna


text:
Q: How to prove that if $S(n)$ is triangular number for $n \in Z_{+}$, then $a=9 $? Let $a\ge 1$ is natural number.
Denote $S(n)=1+a+a^2+a^3+...+a^n$ for $n=1,2,3,...$
How to prove that: if $S(n)$ is triangular number for $n \in Z_{+}$, then $a=9 $?
 http://mathworld.wolfram.com/TriangularNumber.html


text:
Q: split string with comma and newspace in 2d or jagged array and access items in c# Hi there I have a text file like this, many lines 2 columns
CF7CED1BF035345269118A15EF2D45A06, product1
CF7CED1BF035345269118A15EF2D45A09, product2
....
...
...
...

I need to split this and access each field, more precise I need to make a loop that creates many files like product1.txt product2.txt etc and will enclose the codes on its left.
So I need to create files with filenames of columns [2] of all lines and enclose the column[1] as value of each line
I know how to do basic stuff in arrays, like read all lines and store them, but i don't know how to make a loop that will read both field 1 then 2 of LINE 1, create the file and store (I know how to read and save to file) and go on on next LINE 2 and go on field 1 and field 2 again and so on.
Someone suggested using jagged arrays would be faster than 2d arrays

A:
"When you use ReadLines, you can start enumerating the collection of
  strings before the whole collection is returned; when you use
  ReadAllLines, you must  wait for the whole array of strings be
  returned before you can access the  array. Therefore, when you are
  working with very large files, ReadLines can be more efficient."

string path_read = @"c:\read\file.txt";
//Path to save resulting files.
string path = @"c:\temp\";
char[] comma = new char[1]{','};
//ASSUMPTION: Your every row has comma separated 2 values.
//Do a for loop.
//Code now use File.ReadLines
foreach (var currentLine in File.ReadLines(path_read))
{
   string[] itemArray = currentLine.Split(comma, StringSplitOptions.RemoveEmptyEntries);
   // Your item array now has 2 values from 2 columns in the same row.
   // Do whatever with it.
   File.WriteAllText(path+itemArray[1]+".txt", itemArray[0], Encoding.UTF8);
}

A: Do you need to keep the contents for any further use? if the intent is to read and the save the contents to separate files then there is no need for a separate array.
using (var reader = new StreamReader(@"input.txt"))
        {
            while (!reader.EndOfStream)
            {
                var inputText = reader.ReadLine();
                var splitText = inputText.Split(',');

                File.AppendAllLines(splitText[1] + ".txt", new List<string> {splitText[0]});
            }
        }


text:
Q: C#: list of  of = list of  doesn't compile I've got a base Class ScenBase and a derived class ScenC. I have a class HexC derived form the base class Hex. I also have a class UnitC derived from the base class Unit. I can set an array of Hex to point to an array of HexC, but the compiler won't let me set a List of Unit to point to a list of UnitC:
// The Core Database for the game scenario.
// Theoretically multiple secenarios can be loaded
// into memory at the same time.
[Serializable]
public class ScenC : ScenBase
{
    public bool playable { get; set; }
    public HexC[,] hexCs { get; private set; }
    public List<UnitC> unitCs { get; private set; }

    // A database for every user and AI entity.
    public List<ScenV> chViews { get; private set; }
    public List<string> characters { get; private set; }

    public ScenC(int xDimI, int yDimI) : base (xDimI, yDimI)
    {
        playable = false;
        chViews = new List<ScenV>();
        characters = new List<string>();
        characters.Add("Supreme");
        hexCs = new HexC[xDim, yDim];
        hexs = hexCs;                //this line complies fine
        newHex = (int x, int y) => new HexC(this, x,  y);
        unitCs = new List<UnitC>();

        // **This line won't compile**
        unitCs = units;
        Init();
    }
}

Here are the fields properties for the base class ScenBase:
[Serializable]
public abstract class ScenBase
{
    public Hex[,] hexs;
    public List<Unit> units { get; protected set; }
    public DateTime currGameTime { get; set; }
    public int xDim { get; set; }
    public int yDim { get; set; }
    public double scale { get; protected set; }
    protected delegate Hex NewHex(int x, int y);
    protected NewHex newHex;

    //Rest of Class not shown for simplicity
}

Why Can't I set a List<Hex> to a List<HexC> when that follows the "is a" implicit cast rule, but I can set array to array

A: This is not possible.
Had it been possible, you would have been able to add a different derived type to the list.
For example:
List<Car> cars = new List<Car>
List<Vehicle> vehicles = cars;   //Error!
vehicles.Add(new Bicycle());     //That's not a car!

What you're asking for is called covariance; it's only possible for immutable interfaces (such as IEnumerable<T>)

A: you could use a list of interfaces (1) where the Hex and Unit conform to the nominated interface in some way.  otherwise, you will need to cast.
ref: http://msdn.microsoft.com/en-us/library/dd465120.aspx
btw: any interface of IEnumerable is already covariant (see: http://msdn.microsoft.com/en-us/library/9eekhta0.aspx).  Syntax: the out in IEnumerable<out T> defines covariance.
(1) A list of interface
using System;
using System.Collections.Generic;

public interface IHex {
    string ToString();
}

public class Hex : IHex
{
    public override string ToString() { return "Hex"; }
}

public interface IHexC : IHex {}
public class HexC : Hex
{
    public override string ToString() { return "HexC"; }
}

public class Test{
    public static void Main()
    {
        IList<IHex> HexList = new List<IHex>();

        HexList.Add(new Hex());
        HexList.Add(new HexC());
        HexList.Add(new HexC());

        foreach(var o in HexList){
            Console.WriteLine(o.ToString());
        }

    }
}

Console output:
Hex
HexC
HexC

A: Not possible like SLaks said, you could use an interface instead. IList<IHex> for example...

A: you can't cast a
   List<UnitC> // UnitC - to a derived from a Unit class

to a
    List<Unit> // Unit - the base class

try with a IUnit interface instead

A: A general point to consider, in addition to SLaks' explanation as to why your code doesn't work is that using a generic defines a new type:
Unit is a type.
UnitC is a type derived from Unit.

List<Unit> is a new type.
List<UnitC> is a new type, but is not derived from List<Unit>.

However,
Hex[] defines multiple instances of the Hex type.
HexC[] defines multiple instances of the HexC type (which is derived from Hex).

Your assignment doesn't work because the compiler can't ensure that the elements of units are actually instances of UnitC, but if you attempted the inverse (units = unitCs), that wouldn't work, either, because List < UnitC > isn't derived from List < Unit >.


text:
Q: [Vue warn]: Error in created hook (Promise/async): "ReferenceError: document is not defined" I'm new to vue.js and I cannot seem to figure out what is going wrong in this code.
Everytime I load the page, the below mentioned error pops up, which is causing the page to get stuck.
Error in created hook (Promise/async): "ReferenceError: document is not defined"

This is the component I created.
I'm attaching the code below. Hoping to find some insights on this.
<template>

        <v-container v-else>

            <DocumentViewHeader
                :title="title"
            />

            <v-row>
                <v-col cols="9">
                    <citation-card
                        id="citations"
                        class="citation-card"
                    />

                    <citation-card
                        id="similar-articles"
                        class="citation-card"
                    />
                </v-col>
            </v-row>

        </v-container>

</template>

API call details are below:
getDataFromServer ({context}, { pid }) {
    return this.$axios.$get('/info', { params: {paper_id: pid}})
},

The above mentioned server API is working fine.


text:
Q: Вернуть индекс найденного значения import pandas as pd
import numpy as np

Open_Time_s=['2022-04-30 11:05:00+03:00','2022-04-30 11:10:00+03:00']
intersect=[np.nan,np.nan,'intersect_2022-04-30 11:05:00+03:00','intersect_2022-04-30 11:10:00+03:00']

df = pd.DataFrame.from_dict({'Open Time':Open_Time_s,'Intersections':intersect},orient='index').transpose()
df['LEVEL']=np.nan

Нужно записать в поле 'LEVEL' индекс найденных значений поля 'Intersections' из 'Open Time'
код:
df['LEVEL']=df['Intersections'].loc[df['Intersections'].isna()==0].apply(lambda x: df[df['Open Time'].isin(x.replace(r'intersect_', ''))].index)

ошибка: only list-like objects are allowed to be passed to isin(), you passed a [str]. Не понимаю почему возникает из lambda..


text:
Q: How do I get a type of a class at runtime with a string that inherits from an abstract class and use the retrieved type as a parameter How do I retrieve a class at run-time via string and still have the functionality of a generic like Example where ExampleAbstract: new()  ?
I get the error Cannot convert type 'System.Type' to 'CodeStuff.Automobile' [ReminderCodeFolder] when using Windows reflection to get the type.
public abstract class Automobile{
    public abstract void stuff();
}

public class Car : Automobile{
    public override void stuff(){
        Console.WriteLine("Nice");
    }
}

public class Program{
    public static void CarStuff(Automobile b){
        b.stuff();
    }

    static void Main(string[] args){
        Type ReadType = Type.GetType("CodeStuff.Car");
        CarStuff(Automobile(/*Solution*/))
    }
}

A: using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace CodeStuff
{
    public abstract class Automobile
    {
        public abstract void stuff();
    }
    public class Car : Automobile
    {
        public override void stuff()
        {
            Console.WriteLine("nice");
        }
    }

    class Program
    {
        public static void CarStuff(Automobile b)
        {
            b.stuff();
        }

        static void Main(string[] args)
        {
            Type ReadType = Type.GetType("CodeStuff.Car");
            Object obj = Activator.CreateInstance(ReadType);
            CarStuff((Automobile)obj);

            Console.ReadLine();
        }
    }
}

Output : nice


text:
Q: how to import songs dynamically to our app in Objective C I tried iPhone app.In this app I need to import all songs into table-view when I click on import button.I don't know how to import songs dynamically.Please tell me what are the Frameworks to be used.
But i have played  Locally  saved songs like code:-
using this two Frameworks `AVFoundation.framework,MediaPlayer.framework
#import "ViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#import <AVFoundation/AVFoundation.h>

@interface ViewController ()

@property (nonatomic, strong) AVAudioPlayer *audioPlayer;

- (IBAction)playSound:(id)sender;

@end

@implementation ViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    NSBundle *mainBundle = [NSBundle mainBundle];
    NSString *filePath = [mainBundle pathForResource:@"drum" ofType:@"mp3"];

    NSData *fileData = [NSData dataWithContentsOfFile:filePath];

    NSError *error = nil;

    self.audioPlayer = [[AVAudioPlayer alloc] initWithData:fileData
                                                     error:&error];
    [self.audioPlayer prepareToPlay];
    self.audioPlayer.numberOfLoops = -1;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (IBAction)playSound:(id)sender {
    [self.audioPlayer play];

    UIView *wrapperView = [[UIView alloc] initWithFrame:CGRectMake(20, 120, 260, 20)];
    wrapperView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:wrapperView];

    MPVolumeView *volumeView = [[MPVolumeView alloc] initWithFrame: wrapperView.bounds];
    [wrapperView addSubview:volumeView];
}

@end

Output  for this code is songs played locally but I need when I click play button it should  import 10 songs in tableView and then songs mush be played.
Please give me any idea.
Thanks in advanced.


text:
Q: How to ignore rows with moving 30 day interval? I got stuck with a SQL problem. Let's say we have a dataset like this in Redshift :
account_id  day          event_id
111         2019-01-01   1000
111         2019-01-02   1001
111         2019-01-02   1002
111         2019-01-10   1003
111         2019-01-25   1004
111         2019-02-05   1005
111         2019-02-24   1006
111         2019-02-28   1007
111         2019-03-02   1008
111         2019-03-15   1009
222         2019-01-01   1000
222         2019-01-02   1001
222         2019-01-02   1002
222         2019-01-10   1003
222         2019-01-25   1004
222         2019-02-05   1005
222         2019-02-24   1006
222         2019-02-28   1007
222         2019-03-02   1008
222         2019-03-15   1009

I need to pick event_ids that happen after 30 days of window PER ACCOUNT_ID, but then change starting date of new window based on the first event date I find.
so in this case FOR BOTH ACCOUNT_IDS 111 and 222:

*

*we pick first event_id = 1000, and then we should ignore everything until 1st of February (30 days)

*then we pick event_id = 1005, and we should ignore everything until 5th of March (since event_id = 1005 happened on 5th of February)

*then we pick up event_id = 1009 on 15th of March, and we should ignore everything until 15th of April...

you get the picture..
How to do this?

A: I also couldn't find a solution purely based on window functions.
But in PostgreSql a recursive CTE works for this.
The temp table is used to have an id that can be used to connect to the next record.
CREATE TEMPORARY TABLE tempEventDates (
 id SERIAL primary key,
 account_id int not null,
 day date not null,
 min_day date not null,
 event_id int not null
);

INSERT INTO tempEventDates (account_id, day, min_day, event_id)
SELECT account_id, day,
MIN(day) OVER (PARTITION BY account_id) as min_day, event_id
FROM yourtable
GROUP BY account_id, day, event_id
ORDER BY account_id, day, event_id;

WITH RECURSIVE RCTE AS
(
    SELECT id, account_id, event_id, day, min_day
    FROM tempEventDates
    WHERE day = min_day

    UNION ALL

    SELECT t.id, t.account_id, t.event_id, t.day,
     CASE WHEN t.day > c.min_day + interval '30 days' THEN t.day ELSE c.min_day END
    FROM RCTE c
    JOIN tempEventDates t
      ON t.account_id = c.account_id
     AND t.id = c.id + 1
)
SELECT account_id, day, event_id
FROM RCTE
WHERE day = min_day
ORDER BY account_id, day;

A test on rextester here

A: I can hardly see any solution based on pure window functions since subsequent rows depend on previous rows in such extent where the strength of window functions IMHO does not suffice.
Here is PG solution based on recursive query:
with recursive t (day,event_id) as (
  select date '2019-01-01', 1000 union
  select date '2019-01-02', 1001 union
  select date '2019-01-02', 1002 union
  select date '2019-01-10', 1003 union
  select date '2019-01-25', 1004 union
  select date '2019-02-05', 1005 union
  select date '2019-02-24', 1006 union
  select date '2019-02-28', 1007 union
  select date '2019-03-02', 1008 union
  select date '2019-03-15', 1009
), rec (day, event_id) as (
  select t.* from t where day = (select min(day) from t)
  union all
  select tl.* from rec, lateral (select * from t where t.day > rec.day + interval '30 days' order by t.day limit 1) tl
)
select * from rec order by day;

UPDATE after specification change (account_id addition):
with recursive t (account_id,day,event_id) as (
  select 111, date '2019-01-01', 1000 union
  select 111, date '2019-01-02', 1001 union
  select 111, date '2019-01-02', 1002 union
  select 111, date '2019-01-10', 1003 union
  select 111, date '2019-01-25', 1004 union
  select 111, date '2019-02-05', 1005 union
  select 111, date '2019-02-24', 1006 union
  select 111, date '2019-02-28', 1007 union
  select 111, date '2019-03-02', 1008 union
  select 111, date '2019-03-15', 1009 union
  select 222, date '2019-01-01', 1000 union
  select 222, date '2019-01-02', 1001 union
  select 222, date '2019-01-02', 1002 union
  select 222, date '2019-01-10', 1003 union
  select 222, date '2019-01-25', 1004 union
  select 222, date '2019-02-05', 1005 union
  select 222, date '2019-02-24', 1006 union
  select 222, date '2019-02-28', 1007 union
  select 222, date '2019-03-02', 1008 union
  select 222, date '2019-03-15', 1009
), seed as (
  select t.*, row_number() over (partition by t.account_id order by day) as rn
  from t
), rec (account_id, day, event_id) as (
  select account_id, day, event_id
  from seed
  where rn = 1
  union all
  select tl.*
  from rec,
  lateral (
    select *
    from t
    where t.account_id = rec.account_id
      and t.day > rec.day + interval '30 days'
    order by t.day
    limit 1
  ) tl
)
select *
from rec
order by account_id, day;


text:
Q: How to create draggable web component So one of my assignments is to create a window, in which I should be able to append different applications. The window itself is more or less done and I am trying to make the component draggable.
I believe that most of it is done and actually works. I can see in the console that the X and Y-positions actually are changing when I move my mouse, however, the window itself does not move.
I believe that it's because of that pos3 and pos4 never gets a value, they're both undefined and I have no idea what I've done wrong. I hope that you guys understand what I'm after and can point me in the right direction.
Fiddle:
https://jsfiddle.net/wLx2qgu0/
This is my code with some bad variable naming:

const template = document.createElement('template')
template.innerHTML = `

`

class Window extends window.HTMLElement {
  constructor () {
    super()

    this.attachShadow({ mode: 'open' })
    this.shadowRoot.appendChild(template.content.cloneNode(true))
    this.pos1 = this.pos1 || 0
    this.pos2 = this.pos2 || 0
    this.pos3 = this.pos3 || 0
    this.pos4 = this.pos4 || 0
    this.mover = this.shadowRoot.querySelector('#mover')
    this.cont = this.shadowRoot.querySelector('#container')
  }

  connectedCallback () {
    this.dragElement(this.cont)
  }

  dragElement (event) {
    this.mover.addEventListener('mousedown', (e) => {
      this.sender(event)
    })
  }

  elementDrag (event) {

    event = event || window.event
    this.moveWindow(event.clientX, event.clientY)
  }

  moveWindow (x, y) {
    this.pos1 = this.pos3 - x
    this.pos2 = this.pos4 - y
    this.pos3 = x
    this.pos4 = y
    this.style.top = this.offsetTop - this.pos2 + 'px'
    this.style.left = this.offsetLeft - this.pos1 + 'px'

  }

  closeDragElement () {
    /* stop moving when mouse button is released: */

    document.onmouseup = null
    document.onmousemove = null
  }

  // Events
  sender (event) {
    event = event || window.event
    this.pos3 = event.clientX
    this.pos4 = event.clientY
    console.log(this.pos3)
    document.onmouseup = this.closeDragElement
    document.onmousemove = this.elementDrag.bind(this)
  }
}

window.customElements.define('window-board', Window)

A: Check this https://jsfiddle.net/0n4skL3r/

*

*You need to add styles to your shadow elements inside the script

*Call this.dragElement() function to attach the mousedown event. I did it in the constructor.


text:
Q: Is there a more concise way of using Select Case here? I'm testing an input to see if it consists of Japanese characters, which fall within a certain unicode block. I could do it with If, but I like the neater syntax for Select Case. Said that, I'm not quite sure how to write a "Case" that excludes numbers falling between two values.
This works, but could possibly be written more concisely:
For Each c As Char In jpstring
    Select Case AscW(c)
        Case 12352 To 12543, 12784 To 12799

        Case Else
            Return False
    End Select
Next

I tried doing something like:
Case Not 12352 To 12543, 12784 To 12799

But that doesn't work, and nor does wrapping it in brackets like below:
Case Not (12352 To 12543, 12784 To 12799)

Is there a way to write a Case so that it specifically excludes multiple ranges of numbers?

A: AFAIK there is no way to have a Case match an excluded range. However, you could use > and <:
For Each c As Char In jpstring
    Select Case AscW(c)
        Case < 12352, 12544 To 12783, > 12799
            Return False
        Case Else

    End Select
Next

Of course, if you only want to return True or False, it may be more concise to simply return the result of the comparison:
For Each c As Char In jpstring
    Dim asc = AscW(c)
    Return asc < 12352 OrElse (asc >= 12544 AndAlso asc <= 12783) OrElse asc > 12799
Next

A: How about some LINQ?
Dim j() as Char = inputText.Select(Function(c) Ascw(c)).Where(Function(i) (i > 12351 AndAlso i < 12544) OrElse (i > 12783 AndAlso i < 12800))

Making an extension method might also be a nice way to tidy things up:
Module CharExtensions

    <Extension()>
    Public Sub IsJapanese(c As char)
        Dim i = AscW(c)
        Return (i > 12351 AndAlso i < 12544) OrElse (i > 12783 AndAlso i < 12800
    End Sub
End Module

   Dim j() as Char = inputText.Where(Function(c) c.IsJapanese)


text:
Q: Is every separable metrizable space a closed subspace of a convex set in a normed space? This is from Infinite-Dimensional Topology, Prerequisites and Introduction. Here a space means a metrizable and separable space.

Lemma 1.2.3. For every compact space $X$ there exists an isometric $i:X\to C(X)$ such that for every $Y\subseteq X$ the set $i(Y)$ is closed in the convex hull of $i(Y)$.
Remark. Actually every space is a closed subspace of a convex set in a normed space, because every space can be thought of as a subspace of the compact Hilbert cube $Q$ (theorem 1.4.18).

But theorem 1.4.18 only says every space is homeomorphic to a subspace of $Q$. How can we obtain then that every space $X$ is a closed subspace of a convex set in a normed space? Wouldn't we need actually that $X$ can be thought of as a closed subspace of $Q$? But wait, then $X$ need be compact which is the case we want to avoid.
What do you think?
Thank you.

A: Lemma 1.2.3. Indeed says what you state and the proof is clear (IMHO), in fact it says a little more, namely that $i(X)$ lies in the closed ball of radius $\operatorname{diam}(X)$, by part (2).
Now if $X$ is a space we embed $X$ into $Q$ using some embedding $e$, such that $e(X) \subseteq Q$ and $e(X) \simeq X$.
We apply the lemma to $Q$ and get $i: Q \to C(Q)$ such that $i(e[X))$ is a closed subset of $\operatorname{conv}(i(e(X)))$. So $X$ embeds (via $e\circ i$) into $\operatorname{conv}(i(e(X)))$ as a closed subset. The codomain is indeed a convex subset of a normed linear space (namely $C(Q)$, which is even a Banach space).
So the closedness is from subcondition (1) of lemma 1.2.3 in the book, that for every $Y \subseteq X$ the image $i(Y)$ is closed in $\operatorname{conv}(i(Y)$.


text:
Q: What loop should I use for the Question posted down below? Question is how to get the program to ask for input until a valid choice (4-20) is given by the user? I just need to know how to repeat a question. So if a user inputs the wrong number then it will ask the user to input a valid number until the user enters a correct number between 4-20.
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main() {
int num;        //integer for number
int roll;       //integer for roll
srand(time(0)); //seed random number generator

cout << "You are about to roll a single die" << endl;
cout << "How many sided die would you like to roll(4-20)? ";
cin >> num;
cin.ignore();

roll = 1 + rand() % num;        //mods random number
if (num >= 4 && num <= 20) {
    cout << "You rolled: " << endl;
    cout << roll << endl;
}

else
{
    cout << "Please play again and enter a number between 4 and 20" << endl;
    cout << "Press RETURN to continue..."<<endl;
    cin.get();
    cout<<"Exiting"<<endl;

}

return 0;
}

A: Do a while loop to keep on asking for input and have a if statement to break when it is between 4 and 20.

A: Try this
while(1)
{
    cout << "Please enter a number between 4 and 20: ";
    cin >> num;

    if (num >= 4 && num <= 20)
    {
        //mods random number
        //do something
        break;
    }
}


text:
Q: Where do I get Wordpress add_filter variables I am learning wordpress action and filter, action is easier to understand. but filter is hard.
Here is my question:
Below is the sample code, I got it from another site, it replace "best" to "second-best". What I don't understand is where do I get those variables in add_filter and cut_the_boasting?
What if I want to change the word 'Archive' to 'ABC' in default wordpress. What word do I use to replace jacks_boast and $boast?
add_filter( 'jacks_boast' , 'cut_the_boasting');
function cut_the_boasting($boast) {
 $boast = str_replace ( "best" , "second-best" , $boast );
 return $boast;
 }

This must be newb question, but many thanks.

A: You can only use a filter if that filter hook exists, and is applied to a variable with apply_filters(). For your example to work, somewhere in the source code you would find something like:
echo apply_filters( 'jacks_boast', 'best' );

which echoes 'best', unless that value is filtered. With your filter applied, it would echo 'second-best'.


text:
Q: MongoDB index not used when sorting, although prefix matches I'm trying to fetch a set of records in the most efficient way from MongoDB, but it goes wrong when I add a sorting stage to the pipeline. The server does not use my intended index. According to the documentation it should however match the prefix:
https://docs.mongodb.com/manual/tutorial/sort-results-with-indexes/#sort-and-non-prefix-subset-of-an-index
I have an index which looks like this:
{
    "v" : 2,
    "key" : {
        "account_id" : 1,
        "cdr_block" : 1,
        "billing.total_billed" : 1,
        "times.created" : -1
     },
     "name" : "IDX_by_account_and_block_sorted"
}

So I would suppose that when I filter on account_id, cdr_block and billing.total_billed, followed by a sort on times.created, the index would be used.
However that is not the case; when I check the query explanations in MongoDB shell;
this one does NOT use the index, but uses an index that is composed of times.created only, so it takes a few minutes:
db.getCollection("cdr").aggregate(
    [
        {
            "$match" : {
                "account_id" : 160.0,
                "cdr_block" : ObjectId("5d11e0364f853f15824aff47"),
                "billing.total_billed" : {
                    "$gt" : 0.0
                }
            }
        },
        {
            "$sort" : {
                "times.created" : -1.0
            }
        }
    ],
    {
        "allowDiskUse" : true
    }
);

If I leave out the $sort stage, it does use my above mentioned index.
I was thinking that it was perhaps due to the fact that it's an aggregation, but this 'regular' query also doesn't use the index:
db.getCollection("cdr").find({
    "account_id" : 160.0,
    "cdr_block" : ObjectId("5d11e0364f853f15824aff47"),
    "billing.total_billed" : {
        "$gt" : 0.0
    }
}).sort({"times.created" : -1 });

A: $sort Operator and Performance
$sort operator can take advantage of an index when placed at the beginning of the pipeline or placed before the $project, $unwind, and $group aggregation operators. If $project, $unwind, or $group occur prior to the $sort operation,
$sort cannot use any indexes.


text:
Q: How to Connect Python to Heroku Postgres Database? #Error no encryption I'm trying to stablish connection to Heroku Postgres Database and a receive this error:
psycopg2.OperationalError:
FATAL:  password authentication failed for user "hdyarfoicbluoo"
FATAL:  no pg_hba.conf entry for host "95.92.208.27", user "hdyarfoicbluoo", database "d7jcaupbs6m4ud", no encryption

My code is:
import psycopg2

conn = psycopg2.connect( dbname=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST)

conn.close()

I look forward to receiving an answer.
I tried to use DATABASE_URL but don't work, either:
conn = psycopg2.connect(DATABASE_URL, sslmode='require')

Traceback (most recent call last): File "/home/aluno-di/Desktop/dbaccess.py", line 9, in <module>
DATABASE_URL = os.environ['postgres://hdyarfoicbluoo:xxxx@ec2-63-32-248-14.eu-west-1.compute.amazonaws.com:5432/d7jcaupbs6m4ud'] File "/usr/lib/python3.8/os.py", line 675, in __getitem__ raise KeyError(key) from None KeyError: 'postgres://hdyarfoicbluoo:xxxxx@ec2-63-32-248-14.eu-west-1.compute.amazonaws.com:5432/d7jcaupbs6m4ud'

A: In the first case you are missing the sslmode argument:
conn = psycopg2.connect(
    dbname=DB_NAME,
    user=DB_USER,
    password=DB_PASS,
    host=DB_HOST,
    sslmode="require",  # <-- Here
)

But it is better to use the DATABASE_URL environment variable, as you try to do in your second example. Heroku may change your database credentials at any time, and always using this variable is the best way to ensure that your application continues to work.
The whole point of storing connection strings in environment variables is so you don't have to put them directly in your code. Use the name of the environment variable to retrieve its value.
Something like this should work:
DATABASE_URL = os.environ["DATABASE_URL"]

conn = psycopg2.connect(DATABASE_URL)


text:
Q: How to write "pseudo" binary into file using php? I have a string containing something like "01001010" and I want to write it into a file using binary. In other words, what's inside that file is not the chars 0/1,  but in binary format.
How can I make that?

A: So you mean you want to convert a string of 0s and 1s (eg $bitString = '01010101...';) into binary data (0x55...), and then write that to a file, you need to do this in two steps.
First, convert your string of zeros and ones into binary - see Converting string of 1s and 0s into binary value, then compress afterwards ,PHP
Note that strings in PHP can store binary data.
Then just write the output to a file, eg using file_put_contents().


text:
Q: Is it possible to schedule an svn update? I use eclipse galileo with subversive plugin or Tortoise SVN to do an update.
It is possible to schedule an auto-update (eg. every night)?
If yes, is it possible to configure it to just update the non-conflicting files?

A: Just schedule a task to run a batch file every night. The batch file just calls an svn update using a Subversion command line client. Simple enough, right?

A: I had the same problem with the popup lingering when the connection dropped, so I just installed a command line version of svn and checked the returned ERRORLEVEL using a Windows batch script

A: I use this command via a scheduled task - this assumes you have Silksvn installed (but any svn client will do this)
"C:\Program Files\SlikSvn\bin\svn" update --accept postpone d:\SourceCode >> c:\svn.log

It will only update files that aren't conflicting also, so no worry about that.
OR even, do it from TortoiseSVN using this command
C:\Program Files\TortoiseSVN\bin\TortoiseProc.exe /command:update /path:d:\sourcecode /closeonend:1

closeonend can be one of these
/closeonend:0 don't close the dialog automatically

/closeonend:1 auto close if no errors

/closeonend:2 auto close if no errors and conflicts

/closeonend:3 auto close if no errors, conflicts and merges

/closeonend:4 auto close if no errors, conflicts and merges for local operations

A: Microsoft Task Scheduler or CRONw


text:
Q: jquery.min.js:9600 XHR failed loading: POST I want to upload a pdf from jspdf to my server.
I use Ajax for it.
I open the Javascript by a function in my form.

onsubmit="pdferzeugen();"

above the ajax code i create the pdf by "jspdf" and save it to a datauri (base64).
Javascript:
var datauri = pdf.output('datauri');
var data = new FormData();
data.append("pdf_data", datauri);

$.ajax({
    url: "./uploads/upload.php",
    type: "POST",
    processData: false,
    contentType: false,
    data: data,
});

upload.php:
if(!empty($_POST['pdf_data'])){
    $data = $_POST['pdf_data'];
    $fname = "test.pdf"; // name the file
    $file = fopen("./uploads/" .$fname, 'w'); // open the file path
    fwrite($file, $data); //save data
    fclose($file);
}

But this isnt working for me.
Chrome always say:

jquery.min.js:9600 XHR failed loading: POST "http://app-her-visitor/begehung/uploads/upload.php".

I searched whole google for this error, but no success.
I hope you can help me :-)
Thanks for help
Greetings

A: The issue is between the data you are sending. Verify your data before sending it through ajax because the data type should be:

*

*PlainObject or String or Array & success method must have at least one argument

*Type: Function( Anything data, String textStatus, jqXHR jqXHR )

Good Luck.

A: The answer was i refreshed the page after submitting the form and send the base64 Data to my server.
I need to prevent it from refreshing page so it will successfully send the data.
HTML
onsubmit="pdferzeugen();return false"

Javascript
var datauri = pdf.output('dataurl');

$.ajax({
    url: "./uploads/upload.php",
    type: "POST",
    data: { pdf: datauri },
    success: function(data) {},
});

PHP
$pdf = str_replace('data:application/pdf;base64,', '', $_POST['pdf']);
$pdf_decoded = base64_decode ($pdf);
$pdf = fopen ('Begehungsprotokoll.pdf','w');
fwrite ($pdf,$pdf_decoded);
fclose ($pdf);

The return false in the onsubmit will prevent it from reload the page and now the pdf upload to my server.


text:
Q: Apply where condition only to secondary table using leftjoin with knex.js I am using knex.js library to select all rows from a table and get a count() from a secondary table. The following code works fine:
    knex.schema.raw("SET sql_mode=''").then(() => {
    knex.select('empresas.id','empresas.rut','empresas.empresa','empresas.razon_social','procesos2.id','procesos2.id_empresas','procesos2.estado')
    .from('empresas')
    .leftJoin('procesos2', 'empresas.id', 'procesos2.id_empresas')
    .count('procesos2.id as total')
    .groupBy('empresas.id')

This query shows all rows from the table empresas and if there are rows from the table procesos2 it gets the count.
No i want to add a condition to the count, .where('procesos2.estado', '=', 0)
If i add this where clause i get a correct count but only shows one row and not all rows from empresas.
How to add the condition to get a count for all rows from table empresas.

A: It is possible in knex.js to add conditions to the join statement using on() and adding condotions with andOn().
This is working
knex.schema.raw("SET sql_mode=''").then(() => {
    knex.select('empresas.id AS ide','empresas.rut','empresas.empresa','empresas.razon_social','procesos2.id','procesos2.id_empresas','procesos2.estado')
    .from('empresas')
    .leftJoin('procesos2', function() {
        this.on('procesos2.id_empresas ', '=', 'empresas.id')
            .andOn('procesos2.estado', '=', 0)
    })
    .count('procesos2.id as total')
    .groupBy('empresas.id')


text: Q: EC2 Instance count over time I am looking for a way to see the number of my EC2 instances (running + stopped) over time. I tried to find it in cost explorer, cloud watch and ec2 dashboards but failed in doing so. Is that possible?


text:
Q: A normality criterion I'm trying to solve exercise 8.5 from the book "A course in Commutative algebra" by Gregor Kemper. It says

Let $R$ be a ring and $a\in R$ such that $a$ is not a zero divisor, the ideal $(a)$ is a radical ideal and the localization $R_a$ (localization with respect $U= \left\{ 1,a,a^2,\ldots\right\}$) is a normal domain. Then $R$ is normal.

What i have done so far is the following.
Since $\text{Quot}(R_a)=\text{Quot}(R)$ and  $R_a$ is normal, if we take an element $x \in \text{Quot}(R_a)$ which is integral over $R_a$ we must have $x \in R_a$ so $x = \frac{r}{a^m}$ for some element $r\in R$ and an integer $m \in \mathbb{N}.$ Now suppose that $x$ is integral over $R,$ so we have a polynomial with coefficients in $R$ $$t^n +c_1 t^{n-1}+\cdots +c_1t+c_n$$ such that $$x^n +c_1 x^{n-1}+\cdots +c_1x+c_n=0.$$ From the above we know that $x \in R_a$ so in order to show that $x\in R$ we must show that $\frac{r}{a^m}= \frac{r'}{1}$ which means that there is a $a^{\nu}$ such that $a^{\nu} r =a^{\nu} a^m r'.$
I cant really proceed from here, any hints?

A: All you need to show is that $R$ is integrally closed in $R_a = R[\frac{1}{a}]$. Once you have done that it is easy: If $x \in Quot(R)$ is integral over $R$, it is in particular integral over $R_a$ and thus we have $x \in R_a$ by assumption. If you have managed to show the above, you deduce $x \in R$ and you are done.
So let us take $x=\frac{r}{a^m} \in R_a$ integral over $R$. We can choose $m$ minimal, hence there is no representation of $x$ with the exponent of $a$ in the denominator being smaller than $m$.
We have an equation:
$$0 = x^n + c_{n-1}x^{n-1} + \dotsb + c_0= \frac{r^n}{a^{mn}} + \dotsb + c_0$$
After multiplication with $a^{mn}$ we deduce $r^n \in (a)$ (provided that $m>0$), hence $r \in (a)$ since $(a)$ is radical. Write $r = r'a$ and get the contradiction $x = \frac{r'}{a^{m-1}}$.


text:
Q: How to find a substring within a string and then print everything after the substring using a function I keep running into a lot of problems while trying to implement my code. Im new to Swift and the syntax is very frustrating.
I cannot loop through the string. I MUST use a method/library function.
func findNextItem(from: String, in:[String]) -> String?{

return  nil
}

//FUNCTION MUST WORK WITH THE BELOW CODE
let bucketList = ["Travel to Antarctica", "Climb Mount Everest", "Run a
marathon", "Write a book", "Build an iOS app"]
let item1 = findNextItem(from: "Write a book", in: bucketList)
let item2 = findNextItem(from: "Build an iOS app", in: bucketList)
let item3 = findNextItem(from: "Run a marathon", in: [])

print(item1!) // "Build an iOS app"
print(item2!) // "Travel to Antarctica"
print(item3)  // nil


text: Q: How to create horizontal scrolling chart in d3 When I creating a gantt chart my time scale is high and small tasks are not properly visible so I want to scroll horizontally so I can view my chart properly anyone please help?


text:
Q: Sticky sidebar not scrolling the way it should Hello everybody and thanks for taking time to read this.
A friend of mine helped me hack together a very basic template with a "sticky" sidebar that is supposed to be max window height and stick on the right side until the footer appears at that point it should scroll upwards like regular content. In my case it appears to "hide" behind the footer element. My javascript/jquery skills are close to null and I have no idea how to fix this. I asked two friends but they could not help me as well.
I uploaded everything to codepen here http://codepen.io/anon/pen/JGMXOJ.
.footer-fix {
position: fixed;
top: 0;
right: 0;
height: 100vh;
}

The .footer-fix class is applied at the moment the sidebar should start scrolling upwards but it fails todo so.

A: A few things:
1) Since you have a fixed height of 100vh on the sidebar, you should make sure its .main-content counterpart has a min-height of at least that.  This way you don't have freaky behavior when you remove the sidebar from the normal flow of the DOM (when you add position: fixed).  So:
.main-content {
    ...
    min-height: 100vh;
}

2) You're using floats.  Always, always clear floats.  This is as simple as adding an :after pseudo-element to .content:
.content:after {
    content: '';
    clear: both;
    display: table;
}

This prevents the parent of the floated elements from collapsing, allowing you to size/position the children relative to the parent.  You'll need this for step 4.
3) Just a setup change:  Move the .footer outside the main tag, so instead of this structure:

    ...
    ...

You have this:

    ...
    ...

...

(I'd also use the HTML5 footer tag and change the CSS selectors).  This makes the next step possible:
4) Change the CSS of .footer-fix to:
.footer-fix {
    position: absolute;
    bottom: 0;
    right: 0;
}

So when you're ready to unfix the sidebar, you'll absolutely position it at the bottom of its parent.  To make this work, you'll also need to create a stacking context for the parent (.content):
.content {
    ...
    position: relative; /* defines a new stacking context */
}

5) And finally, your JavaScript will look like this:
var $wannaBeSticky = $('.sidebar'),
    currentPosition = $wannaBeSticky.offset().top,
    footerOffset = $('footer').offset().top;

$(window).scroll(function(event) {
    var scrollTop = $(this).scrollTop();

    if (scrollTop >= currentPosition) {
        $wannaBeSticky.addClass('fix');
    } else {
        $wannaBeSticky.removeClass('fix');
    }

    if (scrollTop + $(this).height() >= footerOffset) {
        $wannaBeSticky.removeClass('fix').addClass('footer-fix');
    } else {
        $wannaBeSticky.removeClass('footer-fix');
    }
});

This is very similar to what you had before, I just cleaned up the code and improved the logic for adding/removing the classes.
You may also want to handle window resizing and trigger a scroll on window on page load.
Here's a working CodePen.  Best of luck.


text:
Q: What does continuity of a function mapping a topological space to a real line interval mean? It makes sense for continuity to be defined on a function mapping a real line to a real line. Or how continuity is defined on a function between two topological spaces (every preimage of an open set is an open set). But what does, continuity on a function between a topological space and real line interval mean? Like in Urysohn's Lemma.
Is it just defined in a particular way or one can derive its meaning by looking at how continuity is defined b/w two topological spaces and two real line intervals?
I'm not very good with words so I hope the question made some sense.
Thanks in advance.

A: It is defined in the same way continuity between any two topological spaces is defined - so the question boils down to if an interval $I$ of the real line is a topological space, then what is the topology?
We usually endow the real line with the Euclidean metric, which induces a topology whose open sets are open intervals and unions of open intervals.  But what if the space we're in is an interval of the real line?  Given an interval $I \subset \mathbb{R}$, it is natural to give it the subspace topology, wherein we take the open sets to be the open sets of the real line intersected with $I$.  As a concrete example, if $I = [0, 1]$, then the sub-interval $(1/2, 1]$ is open in $I$ under the subspace topology since $(1/2, 1] = (1/2, 2) \cap I$, and $(1/2, 2)$ is an open set in $\mathbb{R}$.
We have thus induced a topology on $I$, so given a topological space $X$, any function $f:X \rightarrow I$ is continuous whenever the preimage of any open set in $I$ is an open set in $X$.


text:
Q: How to iterate through IEnumerable collection using for each or foreach? I want to add one by one values but in for loop how can I iterate
through one by one values and add it inside dictionary.
IEnumerable<Customer> items = new Customer[]
{
     new Customer { Name = "test1", Id = 111},
     new Customer { Name = "test2", Id = 222}
};

I want to add { Name = "test1", Id = 111} when i=0
and want to add { Name = "test2", Id = 222} when i=1 n so on..
Right now i'm adding full collection in every key.(want to achieve this using foreach or forloop)
public async void Set(IEnumerable collection)
{
   RedisDictionary<object,IEnumerable <T>> dictionary = new RedisDictionary>(Settings, typeof(T).Name);
// Add collection to dictionary;
   for (int i = 0; i < collection.Count(); i++)
   {
     await dictionary.Set(new[] { new KeyValuePair<object,IEnumerable <T>  ( i ,collection) });
   }
}

A: If the count is need and the IEnumerable is to be maintained, then you can try this:
int count = 0;
var enumeratedCollection = collection.GetEnumerator();
while(enumeratedCollection.MoveNext())
{
 count++;
 await dictionary.Set(new[] { new KeyValuePair<object,T>( count,enumeratedCollection.Current) });
}

A: New version
var dictionary = items.Zip(Enumerable.Range(1, int.MaxValue - 1), (o, i) => new { Index = i, Customer = (object)o });

By the way, dictionary is a bad name for some variable.

A: I'm done using
string propertyName = "Id";
    Type type = typeof(T);
                var prop = type.GetProperty(propertyName);
                foreach (var item in collection)
                {
                    await dictionary.Set(new[] { new KeyValuePair<object, T>(prop.GetValue(item, null),item) });
                }

A: So you want to a an item from the collection to the dictionary in the for loop?
If you cast your IEnumerable to a list or an array, you can easily access it via the index. For example like this:
Edit: Code at first created a list every time it looped, which should of course be avoided.
var list = collection.ToList(); //ToArray() also possible
for (int i = 0; i < list.Count(); i++)
{
  dictionary.Add(i, list[i]);
}

I'm not 100% if that is what you need, though. More details to your question would be great.


text:
Q: yii2 pass variable to another model is it possible to do something like this?
model:
class Model1 extends ActiveRecord {

    public $contentUploadedFile;
    ...

    public function extract() {
        ... (assign values from uploaded file content to Model attributes, e.g:)
        $this->datum = $contentUploadedFile[1];
        ...
    }
}

upload model:
class UploadModel extends Model {

    public $uploadedFiles;

    public function rules() {
        return [
            [['uploadedFiles'], 'file', 'extensions' => 'txt', 'checkExtensionByMimeType' => false, 'skipOnEmpty' => true, 'maxFiles' => 2],
        ];
    }
}

upload controller:
    class UploadController extends Controller {
    ...

    public function actionUpload() {
        $model = new UploadModel;

        if (Yii::$app->request->isPost && $model->validate()) {
            $files = UploadedFile::getInstances($model, 'uploadedFiles');

            foreach ($files as $file) {
                $t = new Model1;
                $t->contentUploadedFile = file($file->tempName);

                $t->extract();
                $t->save();
            }
        }

        return $this->render('upload', [
                    'model' => $model,
        ]);
    }
}

but it doesn't work (undefined variable contentUploadedFile). Maybe my logic is totally wrong. All in all, is it possible to pass value to another model somehow similar like this? Or is it totally wrong logic? It would be nice if there would be a builtin functionality in Yii2 that would handle multiple created models, but not using a form and still, with proper validation. Is there something like this?
Thanks.

A: Try a first step this way
class UploadController extends Controller {
...

  public function actionUpload() {
      $model = new UploadModel;

      if (Yii::$app->request->isPost && $model->validate()) {
          $files = UploadedFile::getInstances($model, 'uploadedFiles');

          foreach ($files as $file) {
              $t = new Model1;
              $t->contentUploadedFile = file($file->tempName);
              // first try local assigment when all work transfer the logic in the model extract() function
              $t->dbfield1 =  $t->contentUploadedFile->field1
              $t->dbfield2 =  $t->contentUploadedFile->field2
              // $t->extract();
              //
              if ($t->validate()) {
                $t->save();
              } else {
              // validation failed: $errors is an array containing error messages
                $errors = $t->errors;
                var_dump($errors);
              }

              if
          }
      }

      return $this->render('upload', [
                  'model' => $model,
      ]);
  }
}

For model use $this to refer the attribute
class Model1 extends ActiveRecord {

   public $contentUploadedFile;
   ...

   public function extract() {
       ... (assign values from uploaded file content to Model attributes, e.g:)
        $this->datum = $this->$contentUploadedFile[1];
        ...
   }
}


text:
Q: How to declare a (multi-dimensional) array with value inputted by the user? What we're being taught at school is this:
int x;
cin >> x;
int array[x];

OR
int x, y;
cin >> x >> y;
int array[x][y];

However, I am aware that it's invalid code in C++. But even if it is, it still does the job and works as expected, however, I'm looking to find the answer of how it's properly done?

A: This is not standard C++ but many compiler including gcc and clang support variable length arrays as an extension in C++ even though it is a C99 feature. Althought both gcc and clang will warn you this is an extension if the -pedantic flag is used with a message similar to this:

warning: ISO C++ forbids variable length array 'array' [-Wvla]

An alternative in standard C++ would be to use std::vector or dynamic allocation via new:
int x;
cin >> x;
int *array new int[x] ;
//...
delete [] array ;

the 2D dynamic allocation case is well covered in How do I declare a 2d array in C++ using new?. Using a container is probably better since you do not have to worry about deleting the allocated memory afterwards.

A: Properly it is done with dynamic arrays:
int x;
cin >> x;
int* array = new int[x];

Note, that in this case it is your responsibility to free the allocated memory; or use smart pointers.
Another approach is using STL containers, e.g. vector.

A: Usually it is done either by using standard container std::vector or by allocating the array dynamically in the heap. For example
int x, y;
cin >> x >> y;
int **array = new int * [x];

for ( size_t i = 0; i < x; i++ ) array[i] = new int[y];

A: The most straightforward way to get a dynamically sized array is with std::vector:
int x;
cin >> x;
vector<int> array(x);

Multidimensional arrays are a bit more complicated; one option is:
int x, y;
cin >> x >> y;
vector<vector<int>> array(x, vector<int>(y));

More efficiently, but less simply, you might consider using a one-dimensional array of size x*y, with accessor functions to treat is as two-dimensional.


text:
Q: Geometric interpretation of the conjugation operation in the dual Steenrod algebra As the dual mod 2 Steenrod algebra, $A$, is a Hopf algebra, it has the conjugation operation, $\chi:A\to A$. Milnor also gives a formula for this.
I wonder if there is any source telling about a geometric interpretation of this operation.

A: I do not know if this is what you are searching for, but for the Steenrod algebra itself $\chi$ is closely related to Spanier-Whitehead duality. Let $X$ be a spectrum and $DX=F(X,S)$ its Spanier-Whitehead dual we have an isomorphism
$$Hom(H^*(X,\mathbb{F}_2),\mathbb{F}_2)\rightarrow H^{-*}(DX,\mathbb{F}_2)$$
the contragredient action on the left of a Steenrod operation $\Theta$ corresponds to the action on the right of $\chi \Theta$.
When $X=M$ is a smooth manifold, Atiyah duality identifies $DM$ with the Thom spectrum of $Th(\nu)$ where $\nu=-TM$ is the stable normal bundle of $M$. And we get an isomorphism
$$H_i(M,\mathbb{F}_2)\cong Hom(H^i(M,\mathbb{F}_2),\mathbb{F}_2)\rightarrow H^{-i}(DM,\mathbb{F}_2)\cong H^{dim(M)-i}(M,\mathbb{F}_2).$$
This explains the Wu formula, that relates the total Stiefel-Whitney classe $w(M)$ of $M$ with the Wu class $v(M)$:
$$v(M)=\chi(Sq)(w(M)).$$


text:
Q: Controled prop name in TypeScript I'm stuck with a TypeScript typing problem and can't find anything related.
I'm trying to add dynamic slots to my components, and want props' name to be a specific template including any string, a number and the 'Slot' string (i.e. custom3Slot).
What I'd like to achieve is to declare this type of props like this in my component's props TS declaration:
[key: SlotName]: ReactElement;

For now, SlotName is declared like this :
type SlotName = `${string}${number}Slot`;

The problem is the first string can only take one character. So "c3Slot" is valid, but "cu3Slot" or "custom3Slot" are not. I can't find a way to make this first string being of any length.
Complete exmaple (playground link):
type SlotName = `${string}${number}Slot`;

interface TheInterface {
    [key: SlotName]: ReactElement;
}

const x: TheInterface = {
    c3Slot:  /*...*/,
    cu3Slot: /*...*/, // Error: Object literal may only specify known
                      // properties, and 'cu3Slot' does not exist in type
                      // 'TheInterface'. (2322)
};

A: Surprisingly, ${string}${number} just means "a single character followed by a number" even though ${string} on its own (without another placeholder after it) would allow multiple characters. There's a feature suggestion to...update...that behavior (originally a bug report), but it was marked "working as intended" by the language creator and closed.
Until/unless they do that, you can define SlotName as a union of a bunch of patterns to allow multiple characters:
type SlotName =
    `${string}${number}Slot` |
    `${string}${string}${number}Slot` |
    `${string}${string}${string}${number}Slot` |
    `${string}${string}${string}${string}${number}Slot` |
    `${string}${string}${string}${string}${string}${number}Slot` |
    `${string}${string}${string}${string}${string}${string}${number}Slot` |
    `${string}${string}${string}${string}${string}${string}${string}${number}Slot` |
    `${string}${string}${string}${string}${string}${string}${string}${string}${number}Slot`;

That allows:
const x: TheInterface = {
    c3Slot: {type: "a"},
    cu3Slot: {type: "b"},
    cxx3Slot: {type: "c"},
    cxxx3Slot: {type: "d"},
    cxxxx3Slot: {type: "e"},
    cxxxxx3Slot: {type: "f"},
    cxxxxxx3Slot: {type: "g"},
    cxxxxxxx3Slot: {type: "h"},
};

Playground link
Not ideal, but it works. Keep going for as many characters as you need.
(Perhaps someone better at TypeScript than I am can point out how to use a recursive or mapped type for it.)


text:
Q: On Mac OS X 10.11 nvcc doesn't like complex if used with .cu extension I have a simple code which compiles differently depending whether it's saved with .c or .cu extension:
#include <stdio.h>
#include <complex.h>

int main()
{
    float num;
    float eps_i, eps_s, tau_d, sigma;
    float pi, wave_freq, eps_0;

    eps_i = 43.0;
    eps_s = 2.4;
    tau_d = 0.3;
    sigma = 4.75;
    pi = 3.14;
    wave_freq = 0.015;
    eps_0 = 40.234;

    float complex c1 = 0.0 + 2.0 * pi * wave_freq * tau_d * I;
    float complex c2 = 0.0 + sigma / (2.0 * pi * wave_freq * eps_0) * I;

    num = creal(eps_i + (eps_s - eps_i) / (1.0 + (0.0 + 2.0 * pi * wave_freq * tau_d * I)) -
    (0.0 + sigma / (2.0 * pi * wave_freq * eps_0) * I));

    printf("%g\n", num);
}

If I compile it using nvcc test.c it works exactly how I expected it. However if I run nvcc test.cu I get:
test.cu(18): error: expected a ";"

test.cu(19): error: "complex" has already been declared in the current scope

test.cu(19): error: expected a ";"

test.cu(21): error: identifier "I" is undefined

test.cu(21): error: identifier "creal" is undefined

test.cu(18): warning: variable "complex" was declared but never referenced

test.cu(19): warning: variable "complex" was declared but never referenced

5 errors detected in the compilation of "/var/folders/3z/8bl4b3yx0c3_5tgf35dr_z180000gp/T//tmpxft_00015a75_00000000-9_test.cpp1.ii".

I understand that .cu is treated as code containing CUDA code and .c is just host code, but I would expect them to behave the same in this instance. Notice that it doesn't complain about #include <complex.h> at all. What am I missing?

A: From comments, this problem would appear to be specific to CUDA 7.5 on OS X El Capitan with the latest XCode. The provided repro case seems to work on every other platform it was tested on. It has been recommended that a bug report be raised with NVIDIA.
[This answer has been added as a community wiki entry to get this question off the unanswered list]


text:
Q: Qt plugandpaint example. Zoom in and out I am trying to modify the qt plug and paint example. I would like to zoom the photo in and out. All object need to be resized with the photo. (I am going to draw an image, points and polygons.)
Currently I made a zoomIn(), zoomOut() and scaleView() methods.
void PaintArea::scaleView(qreal scaleFactor)
{
    qreal factor = transform().scale(scaleFactor, scaleFactor).mapRect(QRectF(0, 0, 1, 1)).width();      //this line give the error that there is no transform()
    if (factor < 0.07 || factor > 100)
        return;

    this->scaleView(factor);
}

void PaintArea::zoomIn()
{
    scaleView(qreal(1.2));
}

void PaintArea::zoomOut()
{
    scaleView(1 / qreal(1.2));
}


text:
Q: Active UI Datepicker for Rails I am relative new to Rails. I am using Rails 3, simple form with UI Datepicker, a wrapper for jquery datetime selector.
In the readme at https://github.com/kristianmandrup/ui_datepicker-rails3, there are lines
Activate it like this:

UiDatePickerRails3.activate :simple_form

This can be done fx from inside an initializer. You can pass either :simple_form, :formtastic or :active_admin to the #activate method.

I don't know where to put or run UiDatePickerRails3.activate :simple_form to activate it.
My view code
%h2
 Create new task
= simple_form_for @task do |f|
 = f.input :name, :wrapper_html => { :id => 'name' }
 = f.input :description, :wrapper_html => { :id => 'description' }
 = f.input :price, :wrapper_html => { :id => 'price' }
 = f.association :task_type
 = f.input :content, :as => :ckeditor, :label => "Nội dung task", :input_html => {:toolbar => 'Full' }
 = f.input :expired_at, :wrapper_html => {:id => 'expired_at', :class => 'ui-date-picker'}
 -#= f.input :expired_at, :as => :date_picker
 = f.button :submit

Here is my application.js file
// This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a  relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// the compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery-ui
//= require jquery_ujs
//= require bootstrap
//= require_tree .
//= require ckeditor/init

A: The initializer should be in your config/initializers directory.
This .rb file is created when you run the install generator (rails generate jquery:install --ui)
Update: Alright, the reason you got that message is because your rails version is 3.1 which uses asset pipeline to compress, concatenate your javascript and css.
For rails 3.1 asset pipelining is enabled by default.
So you got two options:
Option 1: Disable asset pipelining
   Go to config/environments/development.rb (do the same for production.rb as and when required) and set config.assets.digest to false.

Option 2: Follow the workaround as mentioned in the documentation:
(excerpts from the repository's readme page)
In Rails 3.1 when using the asset pipeline, this generator is deprecated, so you'll need to add a line to your app/assets/javascripts/application.js file:
//= require jquery-ui
More Updates
Before you jump into fancier ajax stuff, you got to understand the basics of Ajax and how to implement it with rails.  Check out  this railscasts episode. It's a good tutorial to start with.
As for your issue, you missed quite a few things:
To get jquery working you need the appropriate JQuery CSS and Javascript files, which can be downloaded from here: jquery-ui.
Next, you need to inform your application what action to take when it encounters this:
:class => 'ui-date-picker'
However, to understand this concept, you need to know how Ajax and jquery work.
For now,
just create a new .js, name it datepicker.js and add the following
$(document).ready(function(){
$('input.ui-date-picker').datepicker();
$('input.ui-datetime-picker').datetimepicker();
});
These steps are mentioned in the configuration section here.
I would suggest you to install rails 3.0.9, it's relatively simpler.  Also, it's better to use built-in form builder when you are a beginner, get used to it before starting with simple_form or formtastic.


text:
Q: Openpyxl - find hidden rows in ReadOnlyWorksheet I have a problem with detecting which rows are hidden when I open workbook in read-only mode.
It works flawlessly when I set read_only parameter to False while loading workbook, because then I can iterate over row_dimensions to check which rows are hidden - but opening workbook in read-write mode takes much longer (~2 mins vs ~20 secs in read-only mode) and consumes over 1GB of RAM.
Unfortunately read-only worksheets don't have row_dimensions attribute.
Any help is welcome.

A: The underlying issue is that the parser is used once and discarded after iterating over all the rows. This is how read_only mode can optimize memory allocation and generate rows upon request. Interestingly enough, the parser itself is still creating the row_dimensions with the row attributes in it!
There are a couple of work arounds you could attempt. In lieu of forking and creating an official fix that exposes the ReadOnlyWorksheet parser, I went with monkey patching:
from openpyxl.worksheet._read_only import ReadOnlyWorksheet, WorkSheetParser, EMPTY_CELL

# The override:
class MyReadOnlyWorksheet(ReadOnlyWorksheet):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.parser = None

    def row_is_hidden(self, row_index):
        str_row_index = str(row_index)
        if self.parser and str_row_index in self.parser.row_dimensions:
            return self.parser.row_dimensions[str_row_index].get('hidden') == '1'
        if self.parser is None or row_index > self.parser.row_counter:
            raise RuntimeError('Must generate the row before calling')
        return False

    def _cells_by_row(self, min_col, min_row, max_col, max_row, values_only=False):
        """
        The source worksheet file may have columns or rows missing.
        Missing cells will be created.

        Logically the same but saves the parser to "self" during row iteration

        """
        filler = EMPTY_CELL
        if values_only:
            filler = None

        max_col = max_col or self.max_column
        max_row = max_row or self.max_row
        empty_row = []
        if max_col is not None:
            empty_row = (filler,) * (max_col + 1 - min_col)

        counter = min_row
        idx = 1
        src = self._get_source()
        parser = WorkSheetParser(src, self._shared_strings,
                                 data_only=self.parent.data_only, epoch=self.parent.epoch,
                                 date_formats=self.parent._date_formats)
        ### Cache parser in order to check generated row attrs ###
        self.parser = parser
        for idx, row in parser.parse():
            if max_row is not None and idx > max_row:
                break

            # some rows are missing
            for _ in range(counter, idx):
                counter += 1
                yield empty_row

            # return cells from a row
            if counter <= idx:
                row = self._get_row(row, min_col, max_col, values_only)
                counter += 1
                yield row

        if max_row is not None and max_row < idx:
            for _ in range(counter, max_row+1):
                yield empty_row

        src.close()

# the monkey patch:
import openpyxl.reader.excel
openpyxl.reader.excel.ReadOnlyWorksheet = MyReadOnlyWorksheet

# the test drive:
from openpyxl import load_workbook
file_location = ''  # load your file
workbook = load_workbook(file_location, data_only=True, keep_links=False, read_only=True)

for worksheet in workbook.worksheets:
    row_gen = worksheet.rows
    for i, row in enumerate(row_gen, start=1):
        if worksheet.row_is_hidden(i):
            continue  # do not process hidden rows.

This does what you need, but beware! I would add sufficient test coverage before using in production (think things like future version re-keying row_dimension dict, removing row_dimensions from read_only parsing, etc). You can similarly add your own accessors to the worksheet that exposes other row attrs (or return the entire dict).
Happy coding!


text:
Q: .htaccess to redirect the root to a subfolder Using .htaccess I am trying to redirect requests for the root of a site to a subdir. The three approaches I have tried either fail or leave something to be desired.
This fails with indefinite recursion:
Redirect / http://example.org/sub

These don't seem to work for a defaulted index.html:
Redirect / http://example.org/sub/index.html
Redirect /index.html http://example.org/sub/index.html

This works, but leaves the directory at the top level, which necessitates rewriting relative links in the html file:
DirectoryIndex http://example.org/sub/index.html

So, is there any straightforward way just redirect the root totally to a subfolder and have everything work there? I am trying to avoid the fancier features of .htaccess -- I'd probably just prefer the third alternative if it gets too complicated.

A: In the DocumentRoot of old site have this rule:
RewriteEngine On

RewriteCond %{HTTP_HOST} !example\.org$ [NC]
RewriteRule ^ http://example.org/sub%{REQUEST_URI} [L,NE,R=301]