Media Player is a null object, when made from an activity which was launched from a BroadCastReceiver

Question: I am trying to play a MediaPlayer from a activity, which was OPENED BY A BROADCAST RECEIVER. This works fine, if I play an internal file from the R.raw folder. But if I try to access a Mp3 file via a URI, it doesn't work anymore.
public class AlarmScreen extends AppCompatActivity {
MediaPlayer mediaPlayer;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_alarm_screen);
    mediaPlayer = new MediaPlayer();
    startMusic();
    }

private void startMusic() {
    String stringUri = element.getUri();

    if (!(stringUri.equals(""))){
        Uri uri = Uri.parse(stringUri);
        mediaPlayer = MediaPlayer.create(this, uri);
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mediaPlayer.start();
            }
        }, 1000);
    }
}

The Error I get looks like this:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.media.MediaPlayer.start()' on a null object reference

I also tried to make the Media Player the following way, but it led to the same result:
Uri uri = Uri.parse(stringUri);
        try {
            mediaPlayer.setDataSource(this, uri);
        } catch (IOException e) {
            e.printStackTrace();
        }
        mediaPlayer.prepareAsync();
        Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                    mediaPlayer.start();
            }
        }, 300);

I guess that the problem lies somewhere within the permissions, because as far as I know the BroadCastReceivers don't have the same permissions as the normal apps.
If you need more code, please let me know.
EDIT:
I have narrowed down the problem by making the following test-project:
Here 2 Uris are created. For Uri1, I use the data from the chooser. For Uri2 I use the Uri-String from a previous round. Then these Uris are played in the start(). If I play Uri1, it works always. But if I play Uri2, it only works if Uri1 is equal to Uri2. This is only the case if the same music-file is chosen in the chooser again, as in the round where I originally copied Uri2.
I really don't understand what I'm doing wrong. Is there another way, to access music-files from your device?
private void play(){
    mediaPlayer = new MediaPlayer();
    try {
        mediaPlayer.setDataSource(this, uri2);
    } catch (IOException e) {
        e.printStackTrace();
    }
    mediaPlayer.prepareAsync();
    mediaPlayer.start();
}

@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    uri2 = Uri.parse("content://com.android.providers.media.documents/document/audio%3A17207");
    uri1 = data.getData();

    String str = uri.toString();

}

private void start(){
    Intent intent = new Intent();
    intent.setAction(Intent.ACTION_GET_CONTENT);
    intent.setType("audio/*");
    startActivityForResult(Intent.createChooser(intent, "choose:"), 1);
}

Comment: Probably your `Uri` is a `null` and that is why you are getting `null pointer exception`. If you didn't manage permission for accessing phone storage and uri exposed exception that could be some of the reasons why `Uri` is a `null` when you try to play it.
Comment: @Yupi The Uri is working fine. This should not be the problem. Any other ideas?
Comment: Is that whole code you have?
Comment: @Yupi no thats just a small fraction. But there is no more code about the MediaPlayer. Is something missng?
Answer: I think your problem is because of permissions.
Try to add the READ_EXTERNAL_STORAGE to your manifest.
Something like this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
          package="com.example.snazzyapp">
     ...
     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
     ...
    <application ...>
        ...
    </application>
</manifest>

Comment: Thanks for your answer, but it didn't solve my problem. I still get the null point exeption. Do you have any other ideas? In the documentation, they mention Restricting Broadcast with Permission, but I don't understand it. Might this be the problem? here is the [link](https://developer.android.com/guide/components/broadcasts#restrict-broadcasts-permissions)
Comment: I saw the link, but i thik thats not the problem. I think the problem could be the path to the file, where is saved the File?.
Comment: It looks like you are right. I tried to access a music file via an Uri in a normal activity and it didn't work aswell. Unfortunately I still can't fix my problem, but I have added an "edit" in my post, where I described how I isolated the code and what results I got. It would be really kind if you could take a look at it.


Do they mean parallel instead of perpendicular?

Question: This question came in the admission exam of Rajshahi University in 2020-21
Q) If two vectors $2\hat{i}+3\hat{j}+\hat{k}$ and $-4\hat{i}-6\hat{j}-\lambda\hat{k}$ are mutually perpendicular, then what will be the value of $\lambda$?
(A) 2
(B) -2
(C) 0.5
(D) -0.5
None of the options seem correct. The correct value of $\lambda$ will be -26 if the two vectors are perpendicular. Do they mean parallel? If the two vectors are parallel, then the value of $\lambda$ will be (A).
Comment: It does indeed seem like "parallel" was intended. Note that even the use of "mutually" (regardless of "parallel" or "perpendicular") is a bit unusual in the context of just two vectors. There may well be some kind of editing error. Alternatively, maybe there was an error in giving the vectors or the answer options. We can only speculate. ... Since the exam is quite recent, why not contact the University's math department directly and ask for clarification?
Comment: For fun, you could check the previous (and/or subsequent) admission exams for similarly-worded questions. Maybe it'll become clear that the above comes from a recycled template that was modified but perhaps not closely proofread. (These things happen.)
Comment: @tryingtobeastoic  Perpendicular :$\lambda=-26$ , parallel :$\lambda=2$
Comment: For safety  Option (D) should be given  non of the above.
Answer: If the two vectors are perpendicular, then:
\begin{equation*}
 -8-18-\lambda =(2,3,1) \cdot (-4,-6,-\lambda) = 0
\end{equation*}
Therefore, $\lambda = -26$.
If the two vectors are parallel, then:
\begin{equation*}
(-3\lambda+6,2\lambda -4,0) =(2,3,1) \times (-4,-6,-\lambda) = (0,0,0)
\end{equation*}
Therefore, $\lambda = 2$. What you claim is most likely correct.


Modal Não Retorna Banco de Dados

Question: Eu tenho uma tabela no banco de dados chamada patologias. Dentro desta tabela existe uma coluna chamada doenca. Eu criei um modal que deve retornar uma dropdownlist com todas as opções de doenças preenchidas na tabela nesta coluna para seleção do usuário. Entretanto o modal está retornando uma dropdownlist extamanet com o mesmo número de linhas da tabela porém vazios. Segue abaixo o código. Serei eternamente grato a quem ajudar. Estou travado a 4 dias neste problema:

conecta_mysql();

$result = mysql_query($query);
?>

<code><select name="doencaap1" required>
                    <option>Selecione...</option>
                    <?php while($prod = mysql_fetch_array($result)) { ?>
                            <option value="<?php echo $prod['doenca'] ?>"><option style = "color:red"></option>
                     <?php } ?>
            </select>
</code>
Answer: <code>               Ja tentou com foreach ?

                 <select name="category_id" class="form-control">
                        <option value="">CATEGORIA</option>
                        <?php foreach ($medics as $p): ?>
                            <option value="<?php echo $p->id; ?>" <?php
                            if (isset($_GET["category_id"]) && $_GET["category_id"] != "") {
                                echo "selected";
                            }
                            ?>><?php echo $p->name; ?></option>
                                <?php endforeach; ?>
                    </select>
</code>

Modal Não Retorna Banco de Dados


How to avoid rounding with using of strtold

Question: I tried this:
<code>#include <cstdlib>
#include <iostream>

int main ()
{
    char *p;
    long double l = strtold("12312.12345", &p);
    std::cout << l << std::endl; //prints 12312.1
}
</code>
demo
How to avoid that kind of rounding?
Comment: It´s not `strtold`s fault. See http://stackoverflow.com/questions/3923202/set-the-digits-after-decimal-point
Answer: Your string is correctly parsed. You can verify it in this way:
<code>// Remove the integer part ...
std::cout << (l - 12312) << std::endl;
// ... and you get the fractional part correctly displayed:
// 0.12345
</code>
So the reported problem is just a matter of output formatting.


NSImage : Change brightness

Question: I want to change the "brightness" of an NSImage.
I've searched a bit around but I found nothing really helpful...
So, what is the easiest, Cocoa-friendly way to do that?
Comment: tint the image with more white balance?  http://stackoverflow.com/questions/1413135/tinting-a-grayscale-nsimage-or-ciimage
Comment: the silly way to do it would be to increase the rgb values of each pixel (not going over 255) but I bet there are Quartz filters to do this.
Answer: You can do it with Core Image Filters. But You need to use CIImage not NSImage so You will need to convert it. Here is CIFilter Reference with all filters. Take a look at "CIColorControls" it will let You achieve what You want.

CIColorControls
Adjusts saturation, brightness, and contrast values.
Parameters
inputImage (A CIImage class whose display name is Image).
inputSaturation (An NSNumber class whose attribute type is CIAttributeTypeScalar and whose display name is Saturation.
  Default value: 1.00 Minimum: 0.00 Maximum: 2.00 Slider minimum: 0.00 Slider maximum: 2.00 Identity: 1.00)
inputBrightness (An NSNumber class whose attribute type is CIAttributeTypeScalar and whose display name is Brightness.
  Default value: 0.00 Minimum: -1.00 Maximum: 1.00 Slider minimum: -1.00 Slider maximum: 1.00 Identity: 0.00)
inputContrast (An NSNumber class whose attribute type is CIAttributeTypeScalar and whose display name is Contrast.
  Default value: 1.00 Minimum: 0.00 Maximum: 4.00 Slider minimum: 0.00 Slider maximum: 4.00 Identity: 1.00)
Comment: Justin - did they change the documentation? What you have listed above is different from what's in the documents, IE it doesn't list the minimum and maximum values. Or did you get that from somewhere else?
Comment: @CoDEFRo I get it from Apple developer library from link to reference. They have changed documentation.
Answer: You can use coreImage. Take a look at Core Image Fun House application code.

NSImage : Change brightness


How to understand tcl's return

Question: I wanted to get the number of parameters of a proc from tcl and didn't want it to be printed in tclsh, so I used return
When I execute the following statement in the c environment
string tclCmd = "info args " + tclProcName + ";return";
    Tcl_Eval(interp, tclCmd.c_str());
    string res = Tcl_GetStringResult(interp);

The result of the execution is not printed in tclsh, but at the same time it is not possible to get the correct value
So I tried to write it like this:
string tclCmd = "info args " + tclProcName;
    Tcl_Eval(interp, tclCmd.c_str());
    string res = Tcl_GetStringResult(interp);
    Tcl_Eval(interp, "return");

This works, but I don't understand why it doesn't print out immediately when Tcl_Eval is executed, and the return statement is still valid afterwards
Comment: Looks like you're embedding tcl in a C++ program. tclsh has nothing to do with that, and stuff will only get printed if you do it yourself.
Comment: And why are you trying to use `return` at all? It only really makes sense inside a `proc`, code block or when `source`ing a file
Comment: The results of the command execution are printed when the code is run, I'm interested in when they are printed
Answer: The return command is not helpful at all there. It triggers an exception condition that comes out of Tcl_Eval as a return code of TCL_RETURN instead of TCL_OK (that is converted by the outer structure of a procedure, if that is relevant). Instead, you should call Tcl_ResetResult(interp); after you have finished with the return value (or have taken another reference to it) to put things back to how they were before your command implementation was invoked.

How to understand tcl's return


tabs not showing

Question: I know this question have been answered many times but i realy do not know what i'm doing wrong. I want a config page of my module with 2 tabs in it. But it won't show a thing.
here is the hook_menu();
function drupangelsToolbar_menu() {
    $items = array();
    $items['admin/config/drupangelsToolbar'] = array(
        'title' => 'drupangels toolbar module settings',
        'description' => 'configuration of your drupangels toolbar',
        'page callback' => 'drupal_get_form',
        'page arguments' => array('drupangelsToolbar_admin'),
        'access arguments' => array('administer drupangelsToolbar settings'),
        'type' => MENU_NORMAL_ITEM,
          );
    $items['admin/config/drupangelsToolbar/add'] = array(
        'title' => 'add',
        'type' => MENU_DEFAULT_LOCAL_TASK,
        'weight' => 0
         );
    $items['admin/config/drupangelsToolbar/delete'] = array(
    'title' => 'delete',
        'type' => MENU_LOCAL_TASK,
        'page callback' => 'drupal_get_form',
        'page arguments' => array('drupangelsToolbarTab3_admin'),
        'weight' => 2
        );
    return $items;
}

this is the hook_admin()
function drupangelsToolbar_admin() {
    drupangelsToolbarTab1_admin();
    drupangelsToolbarTab3_admin();
}

in drupangelsToolbarTab1_admin() and drupangelsToolbarTab3_admin() I built the forms, ending with  return system_settings_form($form);
What am I dong wrong ??
thanks in advance!
Answer: Couple of things wrong:
add needs a callback. E.g:
$items['admin/config/drupangelsToolbar/add'] = array(
    'title' => 'add',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 0,
    'page callback' => 'my_callback_function',
);

Otherwise it has no action when it is clicked.
add and delete both need either an "access callback" or "access arguments". E.g:
$items['admin/config/drupangelsToolbar/add'] = array(
    'title' => 'add',
    'type' => MENU_DEFAULT_LOCAL_TASK,
    'weight' => 0,
    'page callback' => 'my_callback_function',
    'access callback' => TRUE,
);
$items['admin/config/drupangelsToolbar/delete'] = array(
    'title' => 'delete',
    'type' => MENU_LOCAL_TASK,
    'page callback' => 'drupal_get_form',
    'page arguments' => array('drupangelsToolbarTab3_admin'),
    'weight' => 2,
    'access callback' => TRUE,
);

Without this Drupal does not know whether or not to grant access to your tab so that is why they are not appearing.
Comment: but FYI, I only need to aply this to the delete tab because the add tap inherits this from the root item. Correct me if I'm wrong ;)
Comment: Ar ha - yes I believe your right there...

tabs not showing


Do I need to remove or delete HTML elements that I created but didn't attach to the DOM?

Question: I'm implementing client side download of some (High)charts that I have. What I'm doing now is getting the SVG source of the charts, creating a "canvas" element & drawing the SVG to said element, and then downloading the image using toBlob/Filesaver.js. See code below:
// draw the svg to a canvas
var c = document.createElement("canvas");
canvg(c, file);

// scrape the image from the canvas as png or jpg and download it in full quality
c.toBlob(function (blob) {
  saveAs(blob, fileName);
}, contentType, 1);

Right now the download works fine as expected, but it seems that the canvas element I created, c, has been attached to the window and sticks around even after the download finishes.
Calling c.remove() doesn't help. c.parentNode and c.parentElement are null (obviously since I haven't attached c to the DOM) so I can't call removeChild(c) on anything.
I'm wondering how can I remove/delete element c? Is c = undefined/null good enough? Is there a more elegant way?
Answer: Once c goes out of scope, it should get garbage collected automatically, so as long as canvg doesn't keep an unnecessary reference to it.
To ensure c eventually becomes not referenceable anymore, put the whole code in an IIFE:
(() => {
  // draw the svg to a canvas
  var c = document.createElement("canvas");
  canvg(c, file);

  // scrape the image from the canvas as png or jpg and download it in full quality
  c.toBlob(function (blob) {
    saveAs(blob, fileName);
  }, contentType, 1);
})();

(otherwise, it'll stick around as window.c)
Comment: This did the trick!

I agree that `c` should have been garbage collected as long as canvg is not keeping a reference. But why would putting the logic inside an IIFE prevent that unnecessary reference?
Comment: @nal88 Because variables initialized with `var` on the top level (eg inside a `
Answer: Yes previous answer is right but you can also clear canvas, by setting the smallest size of it
(() => {
     var c = document.createElement("canvas");
      canvg(c, file);
      c.toBlob(function (blob) {
              saveAs(blob, fileName);
              c.width = c.height = 0;
      }, contentType, 1);
})()

Comment: Smallest size is 0. Setting the size of a canvas which has an active context does trigger a lot of garbage (basically a new context  + a new baking buffer). The GC will only kick when it will have to anyway. You won't win anything by doing this, quite the contrary.
Comment: Is there an added benefit to clearing the canvas before letting the garbage collector remove it?
Comment: @Kaiido if i will draw a white rectangle on it?) GC just will remove from memory after some time, and while it not be removed this canvas will be less sized
Comment: White is 255,255,255,255 => the worse in terms of raw size... and once again, changing the size of your canvas just creates new trashes that should get collected too. Just leave the canvas as it is, makes sure no reference holds and let the browser do its job.


How can I test if given samples are taken from a Poisson distribution?

Question: I know of normality tests, but how do I test for "Poisson-ness"?
I have sample of  ~1000 non-negative integers, which I suspect are taken from a Poisson distribution, and I would like to test that.
Answer: First of all my advice is you must refrain from trying out a Poisson distribution just as it is to the data. I suggest you must first make a theory as to why should Poisson distribution fit a particular dataset or a phenomenon.
Once you have established this, the next question is whether the distribution is homogeneous or not. This means whether all parts of the data are handled by the same poisson distribution or is there a variation in this based on some aspect like time or space. Once you have convinced of these aspects, try the following three tests:

likelihood ratio test using a chi square variable
use of conditional chi-square statistic; also called poisson dispersion test or variance test
use of the neyman-scott statistic, that is based on a variance stabilizing transformation of the poisson variable

search for these and you will find them easily on the net.
Comment: "whether the distribution is homogeneous or not... Once you have convinced of these aspects" Could you comment a little how to determine this?
Answer: Here is a sequence of R commands that may be helpful. Feel free to comment or edit if you spot any mistakes.
set.seed(1)
x.poi<-rpois(n=200,lambda=2.5) # a vector of random variables from the Poisson distr.

hist(x.poi,main="Poisson distribution")

lambda.est <- mean(x.poi) ## estimate of parameter lambda
(tab.os<-table(x.poi)) ## table with empirical frequencies

freq.os<-vector()
for(i in 1: length(tab.os)) freq.os[i]<-tab.os[[i]]  ## vector of emprical frequencies

freq.ex<-(dpois(0:max(x.poi),lambda=lambda.est)*200) ## vector of fitted (expected) frequencies

acc <- mean(abs(freq.os-trunc(freq.ex))) ## absolute goodness of fit index acc
acc/mean(freq.os)*100 ## relative (percent) goodness of fit index

h <- hist(x.poi ,breaks=length(tab.os))
xhist <- c(min(h$breaks),h$breaks)
yhist <- c(0,h$density,0)
xfit <- min(x.poi):max(x.poi)
yfit <- dpois(xfit,lambda=lambda.est)
plot(xhist,yhist,type="s",ylim=c(0,max(yhist,yfit)), main="Poison density and histogram")
lines(xfit,yfit, col="red")

#Perform the chi-square goodness of fit test
#In case of count data we can use goodfit() included in vcd package
library(vcd) ## loading vcd package
gf <- goodfit(x.poi,type= "poisson",method= "MinChisq")
summary(gf)
plot(gf,main="Count data vs Poisson distribution")

Comment: This line: freq.ex<-(dpois(0:max(x.poi),lambda=lambda.est)*200) produces errors with some real world data, because the length of freq.ex won't match freq.obs on this line acc <- mean(abs(freq.os-trunc(freq.ex))).  I adapted this line to freq.ex<-(dpois(seq(0,max(x.poi))[seq(0:max(x.poi)) %in% x.poi],lambda=lambda.est)*200) but something still isn't quite right because goodfit produces warnings.
Comment: Using your code I receive a goodess of fit index of 121. But it's relative, isn't? So it should be between 0 an 100, right?
Answer: For a Poisson distribution, the mean equals the variance.  If your sample mean is very different from your sample variance, you probably don't have Poisson data.  The dispersion test also mentioned here is a formalization of that notion.
If your variance is much larger than your mean, as is commonly the case, you might want to try a negative binomial distribution next.
Comment: And so if the mean is the same as the variance, could you conclude that the data was Poisson? Hardly!
Comment: True. Necessary but not sufficient.
Answer: I suppose the easiest way is just to do a chi-squared Goodness of fit test.
In fact here's nice java applet that will do just that!
Answer: You can use the dispersion (ratio of variance to the mean) as a test statistic, since the Poisson should give a dispersion of 1. Here is a link to how to use it as a model test.
Comment: 404 NOT FOUND!!
Comment: Archived link added @Rodrigo.
Comment: +1 thank you. often I get some "weired" results, for example, a normal distribution gets a higher p-value then a poisson one, where lambda is relatively small (so by looks only the normal and poisson are not similiar at all)
Comment: @User1865345-solidarityMods Great, thank you!
Answer: Yet another way to test this is with a quantile quantile plot.  In R, there is qqplot. This directly plots your values against a normal distribution with similar mean and sd
Answer: You can draw a single figure in which the observed and expected frequencies are drawn side by side. If the distributions are very different and you also have a variance-mean ratio bigger than one, then a good candidate is the negative binomial. Read the section Frequency Distributions from The R Book. It deals with a very similar problem.
Answer: I think the main point is the one sidmaestro raises...does the experimental setup or data generation mechanism support the premise that the data might arise from a Poisson distribution.
I'm not a big fan of testing for distributional assumptions, since those tests typically aren't very useful. What seems more useful to me is to make distributional or model assumptions that are flexible and reasonably robust to deviations from the model, typically for purposes of inference. In my experience, it is not that common to see mean=variance, so often the negative binomial model seems more appropriate, and includes the Poisson as a special case.
Another point that is important in going for distributional testing, if that's what you want to do, is to make sure that there aren't strata involved which would make your observed distribution a mixture of other distributions. Individual stratum-specific distributions might appear Poisson, but the observed mixture might not be. An analogous situation from regression only assumes that the conditional distribution of Y|X  is normally distributed, and not really the distribution of Y itself.
Comment: Your last point about regression would only be true if X is random. If X is fixed then Y would also be a normal. no?
Comment: Yes, this is true, but for general regression problems (as opposed to anova or designed problems), X really isn't fixed but are observations from the underlying process. However, for the Poisson case, the point still holds, since mixtures of Poissons aren't necessarily Poisson.


Writing images out?

Question: Are the following writing images?  If so, where is it placing it in the DOM?
for (var j = 0; j < portfolio_itemList[i - 1].url.length; j++) {
    $('').attr('src', portfolio_itemList[i - 1].url[j]);
}

Don't you need to specify a function to tell it to write the image?  I am just trying to figure out what that line is doing in the for loop.
Answer: That code forces the browser to preload images without needing to insert it in the DOM. It looks like it's intentionally not displaying it to the user, just shoving files in the browser's cache. That way, when the user views them later, they load basically instantly.
Comment: so anything done like this without a function is done via preload?
Comment: Well, if the code doesn't call some function like appendTo [see HBoss' answer] or at least saving a reference to the , it can't accomplish anything other than preloading the images.
Answer: You're going to want to append that image you create to somewhere on the document
for(var j = 0; j < portfolio_itemList[i-1].url.length; j++) {
    $('').attr('src', portfolio_itemList[i-1].url[j])
        .appendTo("#someTargetSelector");
}

Writing images out?


How to make one field automatically have the date-time of the last change of another field

Question: I need to make one field have the date-time of the last change of another field in a drupal 7 content type.  I tried using a computed field but the calculation is complex and I am having trouble.  Is there an easier way to make one field reflect the date of the last change of one other field?
thanks
Comment: Is there a time stamp field at the field_your_field or field_your_field_revision?

If yes it can be done but if no you may not do.
Comment: fields don't track the time they are altered - revisions are kept, but only as part of a nodes revision, but the timestamp is declared for the node, not the field - this means you will need to create a custom module that tracks changes and the times of those changes to the fields
Answer: You may use hook_node_presave to save time in the field
<code>/**
 * Implements hook_node_presave().
 */
 function jysk_reviews_node_presave($node) {
  if ($node->type == 'my_type') {
    if ($node->my_changed_field[LANGUAGE_NONE][0]['value'] != $node->original->my_changed_field[LANGUAGE_NONE][0]['value']) {
      $node->my_time_field[LANGUAGE_NONE][0]['value'] = time();
    }
  }
}
</code>


Tensorflow C++ Object detection(video)

Question: its my first question in stackoverflow however
my Question how i can use my already trained frozen_graph and label_map from python object detection and use that in my c++ object detection.
i used python for object detection in a video and it wasnt so fast at all 25 fps with mss.sct() and multithreaded
so i want to try it in c++ cause i know that there are more possible and heared that python is little slow.
Someone has an object detection example for an image in c++ or c# ?
Would be awesome
Comment: HI, you might find this of interest https://github.com/lysukhin/tensorflow-object-detection-cpp
Comment: Thank you for the info  i must figure out how to grab the desktop screen and then i try to set it up
Comment: Can i use c++ in 32bit version for tensorflow?? or only 64bit
Answer: Check https://medium.com/jim-fleming/loading-a-tensorflow-graph-with-the-c-api-4caaff88463f,
and you need to build C++ API like https://joe-antognini.github.io/machine-learning/build-windows-tf

Tensorflow C++ Object detection(video)


How to get rightmost characters plus text between double quotes using regular expressions in Python

Question: I have a python list containing something like this:
['"Some-text" {12345-ab123-cd456}', '"Some-Another-text2" {54321-ab123-cd456}]'

The result I wish to get is:
text, 12345-ab123-cd456
text2, 54321-ab123-cd456

So far I've managed to get info from {}, using re module:
re.compile(r'.*{(.*)}

What I want to do is to get the rightmost text after "-" that is inside the double quotes, add comma and get info that is inside curly brackets. Can I do all of this in one step? In one regular expression? Or what could be the best way to do this?
Answer: import re
lst = ['"Some-text" {12345-ab123-cd456}', '"Some-Another-text2" {54321-ab123-cd456}]']

regexp = re.compile(r'"\s*.+-(\S+)\s*"\s+{\s*(\S+)\s*}')
for i in lst:
    line = re.match(regexp, i)
    if line:
        print line.group(1) + ", " + line.group(2)

output:
text, 12345-ab123-cd456
text2, 54321-ab123-cd456

Comment: I would add `\s*` near `{ }` because your regexp will fail if the pattern inside brackets starts with space
Comment: i didnt notice he wanted to cut out that part from the text, so here's the fixed regex
Comment: Thanks a lot ! I'm using subprocess module to read process output into a list and later using regular expression on this list as you showed me. However, at the moment when I print out my list,it is inside of an extra brackets (like this: [['"Text" {12354-45123}', '"Text2" {12345-2435}' ]]). I think I can easily delete these brackets?
Answer: I think regular expressions is a fine way to solve this if you're given this data initially as strings like you posted.
Expanding on what you already have,
>>> import re
>>> pattern = re.compile(r'\-([^\-]*)"\s+{(.*)}')
>>> m = pattern.search('"Some-Another-text2" {54321-ab123-cd456}]')
>>> m.groups()
('text2', '54321-ab123-cd456')

Using this you can just loop through your data and pattern.search each string.
Comment: Another option: m = re.match('".*-(.*)"\s*{(.*)}', '"Some-Another-text" {54321-ab123-cd456}')
Answer: Or, with simpler patterns:
import re
outlist = []
pat = re.compile('".*-(\w+)" {(.*)}', re.I)
for s in ['"Some-text" {12345-ab123-cd456}', '"Some-Another-text2" {54321-ab123-cd456}']:
    m = re.match(pat, s)
    out = m.group(1) + ", "+ m.group(2)
    print(s)
    print(out)
    outlist.append(out)

print(outlist)

Which produces:
"Some-text" {12345-ab123-cd456}
text, 12345-ab123-cd456
"Some-Another-text2" {54321-ab123-cd456}
text2, 54321-ab123-cd456
['text, 12345-ab123-cd456', 'text2, 54321-ab123-cd456']

Comment: Same as @Kasra, I'd like to know what is wrong with this solution.
Comment: Ok, wrote a full answer! Thx
Comment: you need to just keep `text` and `text2`
Comment: Oh missed that! Thanks again!
Comment: why do you re-compile your regex pattern in the loop? thats the point of re.compile function... you can compile it and just use
Comment: You're right: edited. The loop was not present in the first answer I wrote. I forgot to put it out of the loop.


IBM MQ Client running under Windows Docker

Question: I'm looking for a solution to run IBM MQ Client under a Windows Docker container.  I know that Docker Hub only provides Linux implementations of MQ, however, I do not need full MQ Server capability.  Instead, I'm hoping there's a means to install the MQ Client and simply connect to a Channel and Queues defined on another (non-Docker) system.  To approach this, I've done the following:

Spun up a Windows Docker container running under a command prompt (For proof of concept)

Copied in and expanded MQ Client 18.104.22.168-IBM-MQC-Win64.zip

Silently installed MQ Client (e.g. msiexec /i "c:\temp\Windows\MSI\IBM MQ.msi" /l*v c:\temp\install.log /q TRANSFORMS="1033.mst" AGREETOLICENSE="yes" ADDLOCAL="Client").
Note:  The installation was successful and without error

Established required environment variables(MQServer, etc.) and updated paths (classpath, lib, include, etc).

Pinged the MQ server system to verify connectivity.

I attempted to put a message on a working, verified queue using, amqsputc.exe MYDOCKER.DS.Q. The immediate return code is MQCONNX ended with reason code 2195. Unfortunately, 2195 is pretty generic and there are no other logs available to review.
I understand the differences between running MQ under a VM versus a container, however since I only need Client access, I was hoping MQ Client was lightweight enough to be usable.
If MQ Client is not a viable direction, is there an MQ solution which might be doable via a Cloud connection?  My legacy application is Windows-based and relies on MQ for job messaging.
Comment: I would suggest you look at the MQ Redist client for this purpose, you need only unzip the file no install required.  What language is your application written in?  If it is .NET you could move to managed mode which requires only a single dll.  If it is java you can get a jar file, etc,   Please provide some more details to help find a solution.
Comment: Did you ever get this working?
Comment: @DaBozUK I posted a answer with links to the Redist client at mentioned in my comments above along with the requirement for the Microsoft C/C++ runtime libraries.
Comment: There should be an AMQERR01.LOG and possibly an FDC file to detail further what the problem reported in the 2195 (MQRC_UNEXPECTED_ERROR) was.
Comment: Thanks for your thoughts.  The .zip file noted in step 2 is the MQ Redist client, so I think I'm on the right track with it.  My program is an older application written using C/C++ and under direct Windows or even a VM, the MQ client interface works fine.

Setting the actual application aside, I am simply attempting to verify an IBM MQ Client installation under a container by using the IBM "amqsputc.exe" and "amqsgetc.exe" utilities to post a message and then subsequently pop a message off of the Queue Manager.  Sadly, there is no AMQERR*.log created anywhere within my container instance
Comment: The zip file noted is not the redist client unless you renamed it.  Redist zip has `Redist` in the fire name and would not require a MSI install,  you just unzip it, no install required.   Google "MQC9" for fix central download links.
Comment: Please try that first.  AMQERR01.LOG with the real Redist client will get created under the user's `homedrive\homedir\IBM\MQ\data\errors` directory.
Comment: 220.127.116.11-IBM-MQC-Win64.zip is just the client on Windows 64-bit from Fix Central - it is not the redistributable client as @JoshMc says. You say that you have set up the relevant environment variables and paths. Could you tell us what your MQ_DATA_PATH is? You didn't provide DATFOLDER on the install, so I'm not sure what you end up with as the data path if you don't set one. The errors directory will be in your data path, and there should be an AMQERR01.LOG in there.
Comment: Per IBM, the default data path is the install folder, so it was not explicitly set.   For the client I installed, there was no error log created anywhere when running my test.  I will create a "clean" container instance and download the Redist image and work with it.  My apologies for not recognizing the difference between the two.  Note: I will be off project for a few days and may not be able to report results until early next week.  I am very grateful for your input and suggestions.  Thanks!
Comment: @JoshMc @ Morag Hughson - Unpacked Redist image into c:\temp.  Tried running, "c:\temp\bin\setmqenv.cmd -m CSQ3 -p c:\temp -s".  Got an "AMQ7047" error.  Checked the logs and saw:
"02/19/20 13:53:16 - Process(8020.1) Program(crtmqenv.exe) Host(83EB90FAD73F) Installation(MQNI09000004) VRMF(184.108.40.206) - AMQ6119: An internal IBM MQ error has occurred (User name too long : (Arith1) >(Arith2))"
No hits on this at IBM support site.  I am not sending either a Username or Password, as these are not required by the setmqenv.cmd command.  I'm trying to use an IBM supplied utility to confirm the env.
Comment: I noticed there is an APAR out there but if username is longer than 12 characters MQ internally used "UNKNOWN" and causes those errors.  Also since the QM is not local it doesn't really make any sense to specify `-m CSQ3` as a option to the `setmqenv.cmd`.  I'm sure `setmqenv.cmd` is common between client and server installs, on a server install this would tell it to set the env to the one for the install used by that queue manager.  I think you are ok to use just `-p`.
Comment: Looks like the limit is 20 characters per this link: [Why am I getting a MQRC_ENVIRONMENT_ERROR](https://developer.ibm.com/answers/questions/335192/why-am-i-getting-a-mqrc-environment-error-2012-aft/).  Can you confirm that the user you are running `setmqenv.cmd` as is longer than 20 characters?
Comment: @DaBozUK I was attempting to help the OP out but never received answers to some of my questions, can you please answer the same?
Comment: For example, if you are using the IBM MQ classes for Java or the IBM MQ classes for JMS, you simply download the Java-All client or build you app by referencing this via Maven.  If you are using the IBM .NET or XMS.NET libraries in managed mode or the new .NET standard libraries, you can add the required dll (this is available on Nuget).  If you are using a compiled program that uses the C API shared library files then the Redist client can be used,  you simply unzip it and make sure the proper lib directory is in your PATH.
Comment: Without more specifics on what problem you are having it is hard to provide a solution.  2195 is the most generic of errors that is thrown when no specific error has been caught, this means it can have many different causes, the reason the OP was getting appears to be due to the length of the username that was running the command, in your case it may be a different cause.
Comment: @JoshMc I am using C++ (AMQI) libs. What definitely works is installing Windows Server 2016 or 2019 (GUI version) and the MQ Client 220.127.116.11 x64 installer (msiexec or GUI) and then our C++ application attempts a connection and will error with 2058 or similar (can't find QM). But if I use ANY Windows Server docker image, the msiexec does not appear to correctly install as PATH is not updated, and when our application attempts connection we get 2195 unknown error. I've since found that using MQC *redist* zip with 6 VC++ redist packages works. So i'm assuming the 2195 is a DLL dependency issue.
Comment: Any reason not to go with redist if it works?
Comment: No it's what I will go with in the absence of the msiexec working. Seems that the Windows container needs VC 2012 x64 redist (as well as other redists our software needs). I did try this pre-req with msiexec MQC and that didn't work. So I guess the takeaway is that MQC installer flat out doesn't work with Windows containers, and that MQC redist + VC redist is the way forward. When I get time I'll formulate into a more readable answer and submit below.
Comment: Does the 2195 generate a FDC file.  It would be more helpful to understand why that fails if you can provide the top portion summary of the FDC.
Comment: is it working from the docker host itself ? @LumberJack
Comment: @DaBozUK Does the 2195 generate a FDC file. It would be more helpful to understand why that fails if you can provide the top portion summary of the FDC.
Answer: Instead of installing the Full client install using msiexec, I would recommend that you use the IBM MQ Redistributable client install.  This is packaged as a simple zip file for windows which you can extract into any location you choose.

You can find more information about the Redistributable client on the Knowledge Center page Redistributable IBM MQ clients.
You can download the IBM MQ Redistributable clients using the links below:

IBM MQ 9.1 Redistributable client.

IBM MQ 9.2 Redistributable client.
Note: IBM MQ 8.0 is out of support as of April 30th 2020 and IBM MQ 9.0 is going out of support on September 30th 2021.

The IBM Knowledge center page
Limitations and other considerations for redistributable clients gives these requirements:

Windows C runtime libraries
You might have these libraries on your machine already, but if you do not, you need to download and install the following Microsoft C/C++ runtime libraries:

Microsoft Visual C++ Redistributable 2008
Microsoft Visual C++ Redistributable 2012

The download links for the redistributable downloads for each of these libraries can be found at The latest supported Visual C++ downloads.
Comment: Thanks Josh, much appreciate the thought process we went through here. Installing the MQ redist is very easy. Unzip to a folder, add that folder to the system path, install the VC redists (in my case I needed vcredist 2012 x64)
Comment: Thank you for awarding the bounty, I appreciate it.
Answer: A possible alternative (and lighter) approach: Write a Go app using the IBM mq-golang package and deploy that in your Windows docker container.

https://github.com/ibm-messaging/mq-golang
Comment: Go still requires the MQ client (redist).


DNS/DHCP configuration in /config/config.boot vs. /etc/dnsmasq.d

Question: I have an Edgerouter 4 and I am trying to make sense of the configuration areas for DHCP and DNS, when use-dnsmasq enable is set.
I see four places where the configuration can be done:

from the command line (set service dns forwarding ... seems to be the way to provide DNS parameters (but not DHCP?))
by editing (EDIT: a copy of) /config/config.boot and loading it up

These two seem to be tightly linked together, the command line config seems to be written to /config/config.boot

by configuring /etc/dnsmasq.conf
by adding a file to /etc/dnsmasq.d

The configurations follows the dnsmasq configuration file, I have the file /etc/dnsmasq.d/dnsmasq-dhcp-config.conf which was created for me.
Note: I have a strong preference for the approach where /etc/dnsmasq.conf would be all commented out as it is today, and have all my DNS and DHCP cpnfiguration in files living in /etc/dnsmasq.d. I can accept that this configuration will not be visible from the GUI (in the DNS page).
My questions

How do these configuration approaches work together?
Is it possible to only use the approach 3. or 4.?
If yes:

are there drawbacks? (= inconveniences such as the need to backup teh files during an upgrade, lack of visibility in the GUI, etc.)
are there incompatibilities? (= something can be configured exclusively via 1., 2. or 3./4.?)
Answer: 2) generally you would never do, as a reboot would be required to apply config changes. The set commands which ultimately save their changes there should be used instead, outside of specific circumstances like scripting config generation en masse when deploying a lot of systems with similar configs.
3) isn't viable because anything that reconfigures dnsmasq will overwrite changes.
4) will work, but won't survive a firmware upgrade so is inadvisable.
The set commands are preferred. Depending on what you're looking to configure exactly, the dns forwarding custom config may suffice even though it doesn't go into the DHCP portion of the dnsmasq config.
Comment: Thank you, I have a few questions about your answer: in 2) I realized I forgot to add "a copy of" - updated in the question. As for 4): would keeping the file in /config/ and have a link help? Also, `/etc/dnsmasq.d/dnsmasq-dhcp-config.conf` is generated at some point and holds a part of the `dnsmasq` configuration (while another piece is in `/config/config.boot` so the whole thing looks quite messy as it stands.


Diebold-Mariano with multiple predictions over time

Question: I've been trying to use a DM test on my predictive model. I have two different models. Each model is calibrated by using a MSE loss function to estimate the price of 374 different assets each day. I have calibrated my models for 300 days and now I want to test the accuracy of my two models. I have tried using the pricing error of each assets, giving me 374*300=112 200 pricing errors for each model, as input into the DM-test where the first 374 errors is from the first day, the following 374 errors is from the second day and so on. This approach gives me quite unfeasible results since the sample size gets quite big. I have also tried setting my forecast horizon to my number of assets 374 with some improvements but I still think the results are faulty.
Questions:
Can I apply my DM-test to my setting or do I have to rethink my approach of testing pricing accuracy?
Maybe I'm confused on how to apply a correct forecast horizon to my setting? Any help would be highly appreciated.
Answer: The Diebold-Mariano test considers two random variables $e_1$ and $e_2$ that generate pairs of forecast errors $(e_{1,t},e_{2,t})$. Given a sample of $T$ realization of these pairs (i.e. $t=1,\dots,T$), the test assesses whether the expectations of some function (e.g. absolute value or square) of $e_1$ and $e_2$ are equal, i.e. whether $\mathbb{E}|e_1|=\mathbb{E}|e_2|$ or $\mathbb{E}(e_1^2)=\mathbb{E}(e_2^2)$.
In your case, the important thing is what loss function is relevant for you. Would you treat each asset individually or somehow lump them together? I think the latter may be more convenient, if your are fine with ignoring potential differences between assets.
Then you can consider a loss function $L$ such as the sum of absolute values of individual errors across the assets; or the sum of squares. $e_{1,t}$ and $e_{2,t}$ would be vector-valued; each element of the vector would come from a different asset, thus the vector length would be 374. The loss function would transform the vector into a scalar. Thus you would have 300 observations of pairs of losses $(L(e_{1,}),L(e_{2,1}));(L(e_{1,2}),L(e_{2,2}));\dots;(L(e_{1,300}),L(e_{2,300}))$. From this point on applying the Diebold-Mariano test would be straightorward.
Alternatively, you could consider each asset individually and run 374 separate Diebold-Mariano tests. But then you would have a multiple testing problem which should be taken care of.
See also this slightly related answer.


Formatação de Datas em Javascript

Question: poderiam me ajudar por gentileza?
Gostaria de utilizar a função abaixo em uma lógica que estou criando, porém eu precisaria que a função abaixo retornasse para mim apenas a ultima semana do mês, não estou conseguindo entender como realizar as devidas alterações nela para que funcione da forma que eu quero, se puderem me ajudar eu agradeço.

function formataData(data) {
 var diaS = data.getDay();
 var diaM = data.getDate();
 var mes = data.getMonth();
 var ano = data.getFullYear();

 switch (diaS) { //converte o numero em nome do dia
  case 0:
   diaS = "Domingo";
   break;
  case 1:
   diaS = "Segunda-feira";
   break;
  case 2:
   diaS = "Terça-feira";
   break;
  case 3:
   diaS = "Quarta-feira";
   break;
  case 4:
   diaS = "Quinta-feira";
   break;
  case 5:
   diaS = "Sexta-feira";
   break;
  case 6:
   diaS = "Sabado";
   break;
  }

 switch (mes) { //converte o numero em nome do mês
  case 0:
   mes = "Janeiro";
   break;
  case 1:
   mes = "Fevereiro";
   break;
  case 2:
   mes = "Março";
   break;
  case 3:
   mes = "Abril";
   break;
  case 4:
   mes = "Maio";
   break;
  case 5:
   mes = "Junho";
   break;
  case 6:
   mes = "Julho";
   break;
  case 7:
   mes = "Agosto";
   break;
  case 8:
   mes = "Setembro";
   break;
  case 9:
   mes = "Outubro";
   break;
  case 10:
   mes = "Novembro";
   break;
  case 11:
   mes = "Dezembro";
   break;
  }

  if (diaM.toString().length == 1)
      diaM = "0"+diaM;
  if (mes.toString().length == 1)
      mes = "0"+mes;

 return diaS + ", " + diaM + "/" + mes + "/" + ano;
}

var d = new Date();
var anoC = d.getFullYear();
var mesC = d.getMonth();

var d1 = new Date (anoC, mesC, 1);
var d2 = new Date (anoC, mesC+1, 0);

console.log(formataData(d1));
console.log(formataData(d2));
Comment: O que você quer? fazer? Listar as datas da última semana do mês de segunda a sexta?
Comment: Isso mesmo @Marcondes, quero listar somente a ultima semana do mês.
Comment: Pega o último dia do mês e verifica se é uma sexta-feira, se não for decrementa um e testa novamente. Até encontrar a data daquele mês que é. Depois disso tu sabe que daquela ponto -4 será as datas da última semana do mês, serve?
Comment: Diga qual seria a ultima semana de julho esperada por você.
Answer: Veja isso se ajuda.
var datateste = new Date(218,06,27,0,0,0,0); //data, aqui tem que pegar a última data de uma semana cheia do mês atual.
var primeiro = datateste.getDate() - datateste.getDay(); // Primeiro dia é o dia do mês - o dia da semana, contando o Domingo
var ultimo = primeiro + 6; // primeiro dia + 6, para pegar o sábado
var dataInicial = new Date(datateste.setDate(primeiro));//aqui você pode fazer primeiro + 1 se quer iniciar somente pela segunda-feira
dataInicial = "" + (dataInicial.getMonth() + 1) + "/" + dataInicial.getDate() + "/" + dataInicial.getFullYear();
var dataFInal = new Date(datateste.setDate(ultimo));
dataFInal = "" + (dataFInal.getMonth() + 1) + "/" + dataFInal.getDate() + "/" + dataFInal.getFullYear();

Comment: Cara, é isso mesmo que eu estava precisando, obrigado pela força, estarei implementando no meu desenvolvimento.
Comment: De domingo até sábado. Você pode mudar isso para var ultimo = primeiro + 5; ou 4 se iniciar na segunda feira.
Comment: Quem é `last` ?
Comment: ajustado @LeoCaracciolo
Comment: @GabrielPaixãoJustino então se deu boa da um votinho na resposta.

Formatação de Datas em Javascript


React Data Table Component Sort Arrows Always Visible

Question: I have a react data table component (https://www.npmjs.com/package/react-data-table-component) where I would like the sorting icons in the header cells to always be visible. The default behavior is that the sort arrows are hidden until you hover over them or enable one of them.
I have done some investigating and messing around in the browser inspect tool and have found that changing the opacity property for a specific span will acheieve what I want but I don't know how to access it in code.
Here is how I am rendering my data table component
<code>    <DataTable
      customStyles={agentTableCustomStyles}
    />
</code>
And here is my agentTableCustomStyles file
<code>const agentTableCustomStyles = {
  rows: {
    style: {
      minHeight: '72px',
      textAlign: 'right',
      opacity: '1'
    }
  },
  headCells: {
    style: {
      fontSize: '20px',
      fontWeight: 'bold',
      paddingLeft: '0 8px',
      // justifyContent: 'center',
      opacity: '1'
    },
  },
  cells: {
    style: {
      fontSize: '20px',
      paddingLeft: '0',
      // justifyContent: 'center'
    },
  },
};

</code>
How it looks currently:

Here's what I want when I change this opacity property:
Answer: can't find any prop in documentation but you can use this class to hide using CSS.
<code>    .rdt_TableCol_Sortable span {
       display:none
     }
</code>
it will hide span inside rdt_TableCol_Sortable class
Comment: Thank you, this helped me yield what I wanted to achieve. I just changed from display to opacity and set the opacity to 1.


Getting ": Error in VirtualFree():" related error in markLogic

Question: I am using MarkLogic 8
When I checked ErrorLog.txt file I could see the file contains a lot of error text as
<jemalloc>: Error in VirtualFree(): Attempt to access invalid address.

I searched on google but did not find anything.
Not able to understand the reason behind this error. Please help.
Comment: What patch release of MarkLogic exactly? Did you try upgrading to latest if there is a newer one available?
Comment: I am using 8.6-6.3
Comment: Could you try with 8.0-8.1?
Comment: I got this issue in PROD environment. It's won't be easy to update. It would be great a help if you please explain the reason of this error. I would like to understand the cause of this error and try to fix it.
Comment: A core dump issue, something you rarely see. Please reach out to support, they will want to know about this, and they can guide you how best to proceed..
Answer: It seems some issue with the Memory.
Try accessing this link
Probably you will get some hint over the issue.


How to think and deduce optimal strategy move for both Alice and Bob

Question: Question:

Alice and Bob are playing a game on a one-dimensional number line. Initially, Alice is standing at coordinate $x=a$ (integer) and Bob is standing at $x=b$ (integer) .It is guaranteed that $a<b$.
Alice starts the game by playing the first move.
On a turn, a player chooses to move either 0, 2 or 3 units towards their opponent. However, the move must be different from the last move played by them. Both players have all three choices for their first move.
The game ends when either:

A player lands on the spot currently occupied by their opponent. The player is declared the winner in this case.
A player crosses their opponent and lands beyond them. The opponent is declared the winner in this case.

Given the starting positions of Alice and Bob, determine who wins the game if both of them play optimally.

My progress:
What I believed was that there might be a pattern on who might win the game giving a specific distance modulo some number. So let's say distance is $d$.
ALICE mindset: As Alice starts first, she wants to maximise all her chance of winning so she calculates all move possible in the beginning which would give her a better win chance.
As I don't have a way to think of what will happen for all the possible cases, I started with a move by Alice as 0.
BOB mindset:
Now since Bob too wants to maximise his chance of winning, so now he calculates all possible scenarios and consider the best move, I supposed he choosed also 0 .
Now next move by Alice should be either 2 or 3. I now realized that if $d$ was 5, then surely Bob would win since Alice whatever she do, Bob can just do a move of $5-$the move Alice did. So I thought maybe this would be the case for all distances of form $5k$, but I don't have a proof. If $d$ was 4, then I think Bob would win surely since 2 can be the move for A then B would do 2 too. Similarily considering for $d =1 ,2 ,3$ but not sure how to generalize for $d>5$ .
In all, my query is how to think of what's the optimal strategy for each player to follow always and why so? Also explain why the strategy of yours is optimal too.
this problem was a part of this https://codeforces.com/gym/445869/problem/F
i am just asking the mathematical portion.
like for the case of b-a being 1 its given bob wins as well as for the case of b-a being 5 and 6. but for b-a =94 its given that alice wins
the site problem in case anyone needs:

"the move must be different from the last move played by them", this means they must play a move different from the last move played by them only as in if A plays 0 then in next move A can only play 2,3 , similarly for B too . as in if B move 2 then next it can only play among 0,3
**it seems like the answer is this :
for d=1 Bob wins ;
for d==2 Alice wins;
for d>=3 and d is 3, 4congruent mod 5 then Alice wins ;
for d>=3 and rest cases Bob wins . **
can anyone prove this ?
Comment: Try for low values of $d$ to get a grasp of the problem, you will quickly find the winning strategy. Also, you can use strategy stealing here, though it is not constructive and not needed here.
Comment: @caduk what you meant by strategy stealing , can you please apply it here and write a answer based on that it will help me very much to know such methods exist . you may also provide a constructive approach if possible
Comment: also i tried smaller cases whic you said above in the question
Comment: "However, the move must be different from the last move played by them" - does "them" refer to the player or to their opponent. In example if A plays 2 and B responds by playing 3, what moves is A allowed to play next?
Comment: not possible unless a account is created @Apass.Jack ,let me share ss above
Comment: A is allowed to play among 0 , 3 and bob from 0,2 in their next move @shortmanikos
Comment: Alice wins for $d=4$ because she can jump three spaces. Bob must then jump zero spaces to avoid overshooting Alice so Alice moves zero spaces. Bob loses on the next move.
Answer: Disclaimer
This question is poorly written by the author(s), since it leaves room for interpretation of the rules. The first part of this answer is based on the interpretation that "the move must be different from the last move played by them" means that apart from both player's initial moves, no player is allowed to repeat what their opponent did last move. In a second part, I will adress the reading that "the move must be different from the last move played by them" means that apart from both player's initial moves, no player is allowed to repeat what they themselves did last move. Finally, in a third part, I will adress the case where both of these apply.
Part I: no last-move copycat
Spoiler: Alice wins for $d\in \{2,3\}$, Bob wins for $d\in \{1,4,5,...\}.$

1. Implication of rules
The qoq "best" way to think about this specific game is to understand the power of position, i.e. being the person to not act first, paired with the power of moving $0$, which Bob can always do turn 1, and Alice can never repeat as per rules.
This is enough to deduce that Alice must win on turn 1, which is possible iff $d=2$ or $d=3$.

For all other values of $d$, Bob wins. Let's have a look at a few of them.
2. Discussion of first few cases
For $d=1$, Alice either overshoots with an initial $A2$ and $A3$, or prolongs her game by opening $A0$, when Bob in turn elects the play the sequence $\{A0-B0-AX\}$, forcing Alice to overshoot. (Note that from a strategical point of view, all of Alice's opening moves are optimal, as they all loose by force; practically however, $A0$ is preferable since it allows Bob to play suboptimally.)

For $d=4$, we have
$\{A3-B0-AX\},$ where Alice overshoots, or
$\{A2-B2\}$, where Bob lands, or
$\{A0-B2-A0-B2\}$ and $\{A0-B2-AX\}$. Bob wins.

For $d=5$, we have what you described, $\{A0-B0-A2-B3\}$ or $\{A0-B0-A3-B2\}.$

For $d\gt5$, the recurring scheme is that Bob can force Alice into a line described above.

F.e. for $d=6$, we have the simple $\{A3-B3\}$ for opener $A3$, $\{A2-B2-AX\}$ or $\{A2-B2-A0-B2\}$ for opener $A2$, and for opener $A0$ we have $\{A0-B3-A2-B0-AX\}$ or $\{A0-B3-A0-B3\}$. Bob wins.

For $d=7$, we either have prefix $\{A0-B0-A2-B0-\}$ and now $d=5$, with Alice to act and no $0$-move at hand, or we have prefix $\{A0-B0-A3-B0-\}$ and now $d=4$, again with Alice to act and no $A0$-move at hand. Alice may thus not open with $A0$. But opening with $A2$ brings herself directly into $d=5$, which is a win for Bob, since he can play $B0$, and opening $A3$ brings herself into $d=4$, which we saw earlier is also a win for Bob.

For $d=8$, which should be the last case of interest, since it's Alice's $d=3(+5)$, we have straight away that both $A3$ and $A2$ lead to $d=5$ and $d=6$ respectively, where Bob has a win as seen before. Again however, Alice cannot force Bob into such lines with roles reversed with $A0$, since Bob can answer with $B0$, effectively re-reversing roles.

3. Conclusion
Alice can thus never force Bob into "her" two winning cases $d=2$ and $d=3$, because Bob can prevent this by playing $B0$. In fact, Bob can continuously play $B0$ and let Alice close the distance with $A2$ and $A3$ until $4\le d\le 6$ when Bob either snaps the win or forces Alice to overshoot as seen above. This is in line with the observation that Alice must win with her initial move, otherwise Bob has a win. So in short, Bob in last position can always move when they are in a Bob's endgame line and always pass otherwise, effectively revearsing roles, or strategy-stealing.

Part II: no second-to-last-move copycat
Spoiler: Alice wins for $d\in \{2,3,4\}$ and in $(d\equiv 4\mod5).$ Bob wins for $d\in \{1,5,6,7,8,10...\}.$

This game is what the author(s) must have had in mind, since $d=94$ is indeed a win for Alice. Interestingly, it comes with a new strategic option for Bob, which is to reduce to $d\in \{2,3\}$ when Alice is prevented from finishing due to her last move having been what is required. This allows Bob to steer into wins when $(d\equiv 2 \mod5, d\gt5)$. Notably for $(d\equiv 3,4\mod 5)$ however, Alice wins.

1. Discussion of first few cases

For $d=1$, we have again $\{A0-B0-AX\}$, and Bob wins.

For $d \in \{2,3\}$, Alice wins turn $1$.

For $d=4$, Alice wins with $\{A3-B0-A0-BX\}$ where she forces Bob into overshooting.

For $d=5$, again no changes, still $\{A0-B0-A3-B2\}$ and $\{A0-B0-A2-B3\}$ for a win for Bob.

For $d=6$, we have the trivial $\{A3-B3\}$, so Alice can't open $A3$. For $A2$, we have $\{A2-B3-A0-B0-AX\}$ where Bob brings $d$ down to $1$ and forces Alice to overshoot. For $A0$ lastly, Bob repeats with $B0$, denying the revearsing of roles and forcing Alice to open into $d \in \{3,4\}$. Note that Bob didn't play $B0$ turn $2$ before, which validates the prefix $\{A0-B0-...\}$.

For $d=7$, we have $\{A3-B3-A0-B0-AX\}$ where Bob reduces to $d=1$, and $\{A2-B3-A0-B2\}$, where Bob reduces to $d=2$ at a time when Alice can't close the game with $A2$, as this was her last move. This is the above-mentioned strategical play for Bob in position, and it highlights the power of position. For the $A0$ opening, note again that Bob is safe playing $B0$, since his follow-up do not need him to play a second turn $B0$ again, validating the prefix $\{A0-B0-...\}$. So $\{A0-B0-A2-B3-A0-B2\}$ and $\{A0-B0-A3-B3-A0-B0-AX\}.$

For $d=8$, Alice wins with $A2$, reducing to $d=6$ while holding the option of $A0$ next turn. Against $A2$, if Bob plays $B2$ and reduces to $d=4$, Alice can force Bob to overshoot in sequence $\{A2-B2-A3-B0-A0-BX\}.$ Against Bob's $B3$, Alice wins immediately with $\{A2-B3-A3\}.$ Lastly, should Bob reply with $B0$, Alice is now in position to re-revearse with $\{A2-B0-A0-B2-A3-B0-A0-BX\}$ or $\{A2-B0-A0-B3-A3\}.$ So, Alice wins for $d=8$ and for all $(d\equiv 3\mod5,d \gt5)$

For $d=9$ and in fact all $(d\equiv 4\mod 5)$, Alice wins.

2. Conclusion
The interpretation that the players may not repeat their own last move, i.e. the second to last move overall, helps Bob in position, in that it opens Bob up to reduce to $d \in \{2,3\}$ exactly when Alice is forced by the rules to play a move different from what's required to land on Bob's spot. However, Alice wins for initial $(d\equiv 3,4\mod 5)$, as well as initial $d \in \{2,3\}$ where Alice wins turn $1$.

This result is in line with your assumption.
Part III: neither second-to-last-move nor last move copycat
Spoiler: Alice wins for $d\in\{2,3\}$ and for $(d\equiv 1,2 \mod 5, d\gt5)$.

It should be clear that the game is the same as the first one for $d \in \{1,2,3,4,5\}$. So, what about $d\gt5$?

For $d=6$, trivial is $\{A3-B3\}$. Against $A2$ however, Bob loses by force with all his replies, $\{A2-B3-A0-B2\},\{A2-B2-A0-B3\},\{A2-B0-A3-B2\}.$
This now highlights that starting with Bob's first move, we have repeating $3$-cycles, reducing to $d-5$ over three plies. Alice wins games where $(d \equiv 1 \mod 5, d \ge 2).$

For $d=7$, we have the same when Alice reduces to $d=4$ again, now with $A3$. We have $\{A3-B3-A0-B2\}$ and Bob overshoots, $\{A3-B2-A0-B3\}$ also overshooting, $\{A3-B0-A2-B3\}$ again overshooting. Alice wins games where $(d \equiv 2 \mod 5, d \ge 5).$

For $d=8$, Bob wins by completing to $5$ in $\{A3-B2-A0-B3\}$ and in $\{A2-B3-A0-B2-A3\}$ where Alice overshoots. Alice also loses with an initial $A0$ on the base of prefix $\{A0-B0-...\}$. Bob wins games where $(d \equiv 3 \mod 5, d \ge 5).$

For $d=9$, Bob wins with $\{A3-B3-A2-B0-AX\}$ and $\{A3-B3-A0-B2-AX\}$ against $A3$, and against $A2$ with $\{A2-B3-A0-B2-AX\}.$ The prefix case $\{A0-B0\}$ splits into the trivial tail against $A2$ with $\{A0-B0-A2-B3-A0-B2-AX\}$ and into the restricted case of $\{A0-B0-A3-B2-A0-B3-AX\}$ where Bob could not play $B3$ turn $2$ as opposed to above, but still wins. Bob wins games where $(d \equiv 4 \mod 5, d \ge 5).$

Bob also wins games where $d \equiv 0 \mod 5, d \ge 2$, since he can simply complete to $5$ or play our double pass-prefix.

2. Conclusion
Since the game turns into cycles from turn $2$, Bob can no more prevent Alice from revearsing roles; instead, Alice now has options to steer the game into favourable endgames. That is, Alice wins for $d\in\{2,3\}$ and for $(d\equiv 1,2 \mod 5, d\gt5)$, Bob wins the rest.
Comment: what do you mean by qoq ? in  first line?\
Comment: https://codeforces.com/gym/445869/problem/F also in this site for the case of alice at 6 and bob at 100  , its given that alice will win , is it wrong then ?
Comment: Regarding your edit: Bob cannot continuously play B0 according to the rules.
Comment: where i said that @Piita?
Comment: oh my mistake it was a typo mistake
Comment: bob can do moves whatever he wants just he cannot make the move he made lastly t and is not depending on what alice do and similarly for alice can make any move independent of bob but yeah it should be different from alice last move.
Comment: @Piita For d=4 A3 wins it for Alice
Comment: d=8 is a win for Alice... A3 - B2 will continue with A2 leaving Bob to play with d=1 (obviously A2 - B3 -A3 wins it for Alice
Comment: thanks  i finally able to get it
Comment: @Piita Your part I (no last move copycat) is filled with examples that copy the last move (i.e. in d4 you mention A2 - B2). Actually in this variant Alice is guaranteed to win (strategy stealing - covered in another answer). You also need to be more careful in the 3rd variant, Alice can force a win in a lot more cases - i.e. 3 mod 5. ( for d=8 have Alice start with A0)
Comment: @shortmanikos TY yet again for pointing out repetitions where no ought to be! However, no, Bob wins $d=4$ in part I. As for $d=8$ in part III, A0 is met with B0, the prefix, and now either A2 or A3, with B3 or B2 resp. as given there. However, you've spotted half a dozen mistakes and mishaps, so I'll double check right now! ;)
Answer: I'd suggest a solution but I'm not sure if it's correct as I'm just a 13 year old interested in maths.
Let's make this game easier to understand:
The distance between Alice and Bob is b-a, each time Alice or Bob moves, the distance shrinks by either 0, 2, or 3. Now, we can think of this as a Nim-based game, but with some modifications: if the move played makes the value b-a negative, it's a loss. And, if Alice plays a move, Bob can't play it, vice versa. So, we try to analyze this from the last move of the game till the first one. We get subcases: primarily, if the move played before was 0 or not. If a player finds themselves at 1, they can only play 0 to win, that is if their opponent hasn't played it before. Meaning whoever gets to 1 first automatically wins. This is true for 2 and 3 too. But for 4, we see that whoever reaches there first wins, because they can play 0, forcing their opponent to play either 2 or 3, which guarantees a win. Notice that whoever moves once by 2 or 3 loses, because their opponent can spam 0's and they'd be forced to move by 2 or 3, until they reach 1,2 or 3 where we can move accordingly to win. thus, reviewing the rules, both players have all the choices for their first move, thus when bob plays 0, Alice has to play 2 or 3 which makes her lose. Thus Bob wins for all $b-a\in \{1,4,5\cdots\}$. For $b-a=2,3$ first one to move wins by picking 2 or 3, thus Alice wins.
Comment: well explained @john smith , but still i believe some more justification is needed since for b-a being 94 its being said that alice wins
Comment: I've told my programmer friend about it and he programmed the game to find that for 94 Bob wins. It's really obvious, since bob can always play 0 and Alice is forced to move, and since they can't move more than 3, then we get three cases, if bob finds him self at two or three, he plays that number, or else, if he finds him self at 1, he plays 0.
Comment: actually john you said that if alice playes a move , bob cannot play it , but thats  not what question says , the questions means that if alice or bob plays a move then in next turn they are not allowed to play that same move .
Answer: Alice always wins.
Let's note a position $(d, i)$ where $d$ is the distance $b-a$ and $i$ is the last move. The losing positions are of the form $(2k, 2)$, $(2k+1, 0)$ except that $(3, 0)$ is winning and $(3, 3)$ is losing.
By inspection, we clearly can't get from a losing position to a losing position, and from each winning position, we can get to a losing position (For each winning position $(d, x)$, just do the forbidden move of the corresponding losing position).
We could see that Alice always wins by strategy stealing. Basically, moving by $0$ is like passing its turn, but the opponent has one less choice of movement.
Suppose by contradiction that Bob has a winning strategy. Alice starts by moving by $0$, and observes Bob's responses for every sequence of moves she does. So Alice can learn the winning strategy of Bob, and use it against him, which is a contradiction since only one of them can have a winning strategy. See strategy stealing for more details.
Comment: will not the losing and winning depends on  (d,i,j) where i is the last move played by first and j is the last move played by second ? as in the game it clearly matters what the players move are now possible they can make
Comment: Yes, the statement of the problem was really unclear, but it appears I misunderstood it


How to do this (check requests status codes) in Python concurrently or in parallel?

Question: Here's what I'm doing:

Get words from a text file - every word is on a separate line.
Add http://www. and .com to words to create a url.
Get the URL with requests.
Find out if it's a free domain or not (based on status codes and
error in connection/other error).
Add free domains to a text file.
Time it all.

I've kind of made it work so far but it's very slow. The text file has 350 000 words. How would I go about doing this concurrently or in parallel? Also which would be a better choice for this task?
Here's my code:
import requests, time

start = time.time()

with open('words1.txt','r') as f:
    words = []
    for item in f:
        words.append(item.strip())

for w in words:
    url = 'http://www.'+w+'.com'
    try:
        header = {'User-Agent': 'Mozilla/5.0'}
        r = requests.get(url, headers=header)
        codes = [200,201,202,203,204,205,206,300,301,302,303,307,308,400,401,402,403,404,405,406,500,501,502,503]
        if r.status_code in codes:
            print(url,': Known Status Code > Unavailable')
        else:
            print(url,': Unknown Status Code > Probably Free')
            with open('available.txt','a') as myfile:
                myfile.write(url+'\n')
    except requests.exceptions.ConnectionError:
        print(url,' : Connection Error > Probably Free')
        with open('available.txt','a') as myfile:
            myfile.write(url+'\n')
    except requests.exceptions.HTTPError:
        print('http error')
    except requests.exceptions.Timeout:
        print('timeout error')
    except requests.exceptions.TooManyRedirects:
        print('too many redirects')

end = time.time()
print('\n')
print(end-start, 'seconds')
print((end-start)/60,'minutes')
print(((end-start)/60)/60,'hours')

Thanks!
EDIT: I got it to work. Thanks for the help Kendas and DeepSpace!
Here's a quick test:
100 words - 22 sec
1000 words - 285 sec
Not too fast but way faster than my first try.
Seems like gevent + socket is the way to go.
Please let me know if you have any tips on making this better/faster.
Here's the code:
import gevent,time
from gevent import socket

start = time.time()

words = []
with open('words1000.txt','r') as f:
    for item in f:
        words.append(item.strip())

urls = ['www.{}.com'.format(w) for w in words]

jobs = [gevent.spawn(socket.gethostbyname, url) for url in urls]

gevent.joinall(jobs)

values = {url:job.value for (url,job) in zip(urls,jobs)}
freeDomains = []
for (v,job,url) in zip(values,jobs,urls):
    if job.value == None:
        freeDomains.append(url)
        with open('availableds.txt','a') as myFile:
            myFile.write(url+'\n')

print(freeDomains)
end = time.time()
print(end-start,'seconds')
print((end-start)/60,'minutes')
print((end-start)/3600,'hours')

Comment: If you're only interested in whether the domain is registered or not, another approach might be something like this: https://stackoverflow.com/questions/2805231/how-can-i-do-dns-lookups-in-python-including-referring-to-etc-hosts
Comment: Yes, that's what I need - availability. What are you suggesting - dnspython?
Comment: no, the `socket` solutions should be fine
Comment: Will look into this. Thank you.
Comment: @Kendas I'm testing this now. Any tips on making this run concurrently/ in parallel?
Answer: grequests (the concurrent version of requests) makes this pretty easy.
It will also help to use .format and not redefining header every iteration
import grequests

def exception_handler(request, exception):
    print(exception)

with open('words1.txt','r') as f:
    words = []
    for item in f:
        words.append(item.strip())
urls = ['http://www.{}.com'.format(w) for w in words]

header = {'User-Agent': 'Mozilla/5.0'}

requests = [grequests.get(url) for url in urls]

responses = grequests.map(requests, exception_handler=exception_handler)

for resp in responses:
    if resp:
         print(resp.status_code)

Comment: Thanks for the idea. However, I'm getting: AttributeError: 'module' object has no attribute 'get'
Comment: @Thisplaynaymm Post the full stacktrace
Comment: Traceback (most recent call last):
  File "C:\Users\roae\Desktop\wswp\grequests.py", line 1, in
    import grequests
  File "C:\Users\roae\Desktop\wswp\grequests.py", line 14, in
    requests = [grequests.get(url) for url in urls]
  File "C:\Users\roae\Desktop\wswp\grequests.py", line 14, in
    requests = [grequests.get(url) for url in urls]
AttributeError: 'module' object has no attribute 'get'
Comment: @Thisplaynaymm Don't name your own script `grequests.py`. It imports itself.
Comment: That was silly. Sorry about that. So, the script is running but I'm not getting anything (updates). Also, how would I time this and write the free domains to a text file?


Cardinal sine envelop

Question: I am looking for an envelope of the function $t\mapsto \mbox{sinc}^2(t)$, or at least an approximation of such an envelope. Is there a known envelope function?
Here's an illustration of $\mbox{sinc}^2(t) = \frac{\sin^2(\pi t)}{(\pi t)^2}$ (blue), and of one of its envelopes (red), which I drew by hand.

More generally, I was wondering, how does one calculate an envelope?
Comment: The function $1/\pi^2t^2$ is an envelope (probably not the one you are dreaming of).
Comment: @FlorianT: Did you mean  one smoth and continuous envelope?
Comment: yes, I was dreaming of such an envelope!
Answer: An envelope is defined for a parametric family of functions and not for a single member. It is obtained by eliminating the parameter between the function equation and that obtained by differentiating over the parameter.
For example, consider the family
$$y=\frac{\sin^2\lambda t}{t^2}.$$ The aformentioned derivative is
$$0=\frac2t\sin\lambda t\cos\lambda t,$$ which implies $\sin^2\lambda t=0$ or $1$.
Hence the two envelopes
$$y=\frac1{t^2},\\y=0.$$
Comment: That's not exactly the answer I expected, I had rather [this in mind](https://en.wikipedia.org/wiki/Envelope_(waves)), but that's because I didn't know the exact definition of an envelope in mathematics... But now I do, and as we're here in the maths kingdom, that's an accepted answer!
Comment: @FlorianT: I have tried to find a parametric family that would yield your red curve, but that seems uneasy.
Answer: Only a single parameter curve can have a unique envelope obtained by $ c, p$ discriminant  methods.
Your sketch includes a parameter which you have not identified, but implied.
For example a sine curve needs to be associted with parameter $c$ in $ y= A \sin c x,  $ so that an elimination of parameter $c$ leads to envelope $y=\pm A.$
Following example is given for the curve $$ y=\frac{ \sin cx} {x},$$ the sinc squared curve could follow with the same procedure.
By partial differentition with $c$ one obtains
$$ \cos cx = 0 , \quad \sin cx  = \pm 1, \rightarrow \, y=\frac{\pm1}{x} $$  which are hyperbolae curves are exactly sketched below.
Comment: If I'm not mistaken, by partial differentition with $c$ you obtain $0=cos(cx)$ and not $tan(cx)=cx$. And thus you obtain the $1/x$ function by eliminating the parameter $c$. And that seems to be confirmed by your drawing: the two envelopes you drew seem to be really close to $\pm1/x$.
Comment: Thanks for the drawing, which made me understand better what exactly an envelope is.

Cardinal sine envelop


Python: Execução do código lenta e outros problemas

Question: Caros colegas,
Alguém pode me esclarecer o que pode estar ocorrendo?
Em resumo, trata-se de um código para ler células de uma planilha, ordenar e transportar para uma nova planilha.
O problema: O código não executa e não apresenta nenhum erro. Estou usando o PyCharm. Passei o dia de ontem e de hoje testando e, o interessante é que o DEBUG não apresenta erro e executa o código tranquilamente.
Para entenderem o que eu estou criando: Eu peguei os resultados da LOTOFACIL (jogo loteria) e coloquei numa planilha excel. A planilha foi nomeada de lotofacil.xlsx. A planilha tem 1664 linhas e 15 colunas.
Veja um exemplo da planilha...
Pois bem, o meu código está assim...
    import openpyxl

wb = openpyxl.load_workbook('lotofacil.xlsx') #abre o arquivo
nome_plan = wb.sheetnames[0] #identifica o nome da planilha de indice zero
planilha = wb[nome_plan] #entra na planilha indicada

linhas = planilha.max_row #qtd de linhas
colunas = planilha.max_column #qtd de colunas

lista = [] #valores de cada linha são adicionados e depois excluídos

novo_arquivo = openpyxl.Workbook() #abre novo arquivo excel
nome_planNova = novo_arquivo.sheetnames[0] #identifica o nome da planilha de indice zero
planilhaNova = novo_arquivo[nome_planNova] #entra na planilha indicada
novo_arquivo.save('loto_python.xlsx') #salva a planilha nova

#cria um loop.
x=1
while linhas >= x: #enquanto o número de linhas da planilha (1664), for maior ou igual a 'x' o programa executa.
    y1=1
    while y1 <= colunas: #enquanto o número de colunas da planilha(15), for maior ou igual a 'y' o programa executa.
        celula = planilha.cell(row=x, column=y1).value #recebe o conteudo da celula.
        lista.append(celula) #adiciona o conteúdo da célula na lista. A lista terá o tamanho de 15 posições.
        y1+=1

    lista.sort() #ordena a lista, do menor para o maior.

    y2=1
    while y2 <= colunas:
        planilhaNova.cell(row=x, column=y2).value = lista[y2-1] #pega cada item da lista
        novo_arquivo.save('loto_python.xlsx') #salva novamente a planilha nova
        y2+=1

    lista = [] #esvazia a lista. Isso permite manter o loop e seguir para a linha seguinte.

    x+=1

Veja a saída, já na nova planilha... pelo DEBUG.
Lembrando: a execução normal não funciona.
Comment: A "execução normal não funciona", você diz que não executa e não dá erro. Se não executa necessariamente dará erro; ou executa, só não gera o resultado esperado. Pode esclarecer melhor? Você precisa ordenar cada linha de forma crescente?
Comment: Claro Anderson, esclareço. Eu disse: "O código não executa e não apresenta nenhum erro." A execução normal não gera nenhum tipo de alerta de erro e também não gera o resultado esperado. Qual é o resultado esperado? Resposta: A saída apresentada na imagem anexada. O interessante é que o DEBUG executa o programa sem apresentar erro e gera o resultado esperado, porém, isso não me ajuda. Gostaria que o programa fosse automático e não necessitasse de eu ter que executar pelo DEBUG e ficar apertando a tecla "F8" mais de 53.248 vezes.
Comment: Consegue disponibilizar um exemplo de arquivo xlsx de entrada que reproduza o erro?
Comment: Oi Anderson. O arquivo excel de entrada não é o problema, uma vez que desse só é lido os valores. Até aí tudo bem. A questão é que quando executo o código, o PyCharm não apresenta nenhuma mensagem de erro, mas cria o arquivo excel de saída. O excel de saída não abre, pois dá erro.
Comment: A ideia de disponibilizar o arquivo é justamente podermos executar o código e tentar reproduzir o erro. Acredito que você consiga fazer inclusive um [mcve] no https://repl.it
Comment: Ah sim. Claro. Vou fazer isso agora...
Comment: Pronto. Segue o link do Google Drive. --> https://drive.google.com/open?id=1YKf-8OtIej_Oqpz2lrHBt5oQgOlHbplD
Comment: Oi Anderson. Nossa! Assim que terminei de falar com você, coloquei o código para rodar e fiquei aguardando, aguardando, aguardando e, mais de  1 (uma) hora depois o código finalizou a execução, sem erros. O programa funcionou! Porém achei extremamente demorado. Há alguma solução para isso?!
Comment: Sim, tenta colocar o `novo_arquivo.save` somente no final do arquivo, fora dos laços de repetição.
Comment: Fiz o que você disse... Executou em segundos. Obrigado mesmo! Aliás, vamos ficar rico, Anderson! hahahahaha Um grande abraço!
Answer: Apenas para iterar a solução dada, da maneira que você fez, chamando o método save() dentro do laço de repetição, você estará salvando o arquivo em disco múltiplas vezes (15 x 1664 = 24.960 vezes precisamente). Leitura e escrita em disco é uma das tarefas mais lentas que há em um computador, imagina fazer isso quase 25 mil vezes com um arquivo de 15 colunas e 1664 linhas. Obviamente que você não precisa fazer isso. O seu objeto novo_arquivo já representa seu arquivo inteiro, então basta você modificá-lo, persistindo todas as mudanças apenas em memória e apenas no final da execução persistí-las em disco uma única vez.
Para tal, basta colocar a linha de código:
novo_arquivo.save('loto_python.xlsx')

No final do programa, fora de todos os laços de repetição.


Calculate correct dose for pet

Question: if I have a solution that contains 750 mg of curcumin in 10 ml of water and I want to give a dose that is equal to 25 mg curcumin How many ml do I give?
Need to medicate my cat and I need to be sure to give correct dose. Thanks
Comment: If your statements are all correct, you need to give your cat 25 of the 750 mg; that's 1/30 of the total. That'll be a good deal less than 1ml -- not much at all ... indeed, such a small amount that it's hard to believe you could reliably give your cat exactly that amount.  But **you'd be crazy to trust me**; I'm just a random person on the internet who happens to think he knows about numbers! I recommend that you ask the person who prescribed the medication, who might be able to speak with real authority (and about whom you can complain if s/he tells you something wrong).
Comment: I can confirm the math (less than 1ml, specifically $\frac13$ of a ml) for what it's worth it, but I am also a random person on the internet... I just hope your cat will be ok.
Comment: Please don't trust us with your cat's health.  **None of the information you obtain from this site should be interpreted as medical advice.**  We are not vets and are not qualified to advise you medically on how to medicate your cat.  You should always seek advice from someone that is qualified to give it -- in this case, that would be the vet that prescribed the medication.
Answer: We apply the related ratios
$$\frac{750\,\,\text{mg}}{10\,\,\text{m}\ell}=\frac{25\,\,\text{mg}}{x}$$
whereupon solving for x gives
$$\bbox[5px,border:2px solid #C0A000]{x=\frac{10\,\,\text{m}\ell\times 25\,\,\text{mg}}{750\,\,\text{mg}}=\frac13\,\,\text{m}\ell}$$
Comment: And I hope that your cat gets well!!
Comment: Please let me know how I can improve my answer.  I really want to give you the best answer I can.

Calculate correct dose for pet


Erro "[ ] cannot be converted to JSON" ao tentar criar JSONObject a partir de String

Question: Estou utilizando a linguagem Kotlin juntamente com a biblioteca GSON para realizar criação/parse de objestos JSON.
Eu tenho a seguinte string que aramazena um objeto JSON retornado de um server
val jsonString = "{"age":22,"height":1.8,"profession":"Student","at_room":false,"gender":"male","pictures":[ ]}"

Quando tento converter essa string para um JSON Object, fazendo
val jsonData = JsonParser().parse(jsonString).asJsonObject

eu recebo o seguinte erro: [] cannot be converted to JSON
Acho que o erro se deve ao fato de pictures ser um JSONArray e não um tipo primitivo, mas de qualquer forma eu gostaria de saber como converter essa string para um JSON Object corretamente.
Answer: Achei o erro, e infelizmente, não tinha a ver com a transformação da String em um JSON Object, mas sim na conversão das propriedades da classe User para um JSON String
A minha função que fazia essa conversão era a seguinte
override fun userToJson(user: User): String {

    return jsonObject(

            AGE_FIELD to user.age,
            HEIGHT_FIELD to user.height,
            EDUCATION_FIELD to user.education,
            WORK_FIELD to user.work,
            ABOUT_FIELD to user.about,
            GENDER_FIELD to user.gender,

            /* O erro era lançado nesta última linha */
            PICTURES_FIELD to jsonArray(user.albumPics)

    ).toString()
}

A analisar a função jsonArray() vi que ela recebe como parâmetro um conjunto de valores ( e.g. jsonArray("a","b","c") ), porém, eu estava passando um user.albumPics, que é um objeto do tipo MutableList<String>.
Portanto, o que eu deveria fazer era converter user.albumPics para uma representação em String fazendo user.albumPics.toString(), dessa forma, a chamada da função ficava jsonArray("[]") , o que é válido.
Assim, a solução final foi realizar uma pequena alteração na linha
PICTURES_FIELD to jsonArray(user.albumPics)

substituindo por
PICTURES_FIELD to jsonArray(user.albumPics.toString())


granting local account software install permission

Question: I have a stand alone W2K8 server used by our vendor. I created them a local account and made part of Power User group. This group is insufficient, they are not allowed to install any software. How can I allow the local account to install software besides local admin group.
I checked the local security policy, user rights assignment but nothing there to me would allow this. I also check UAC, but no luck. Maybe i'm doing something wrong, can anybody guide me?
Thanks
Comment: Power users has been [depricated](http://blogs.technet.com/b/steriley/archive/2008/02/11/plan-now-to-eliminate-power-users-from-your-domains.aspx) since Vista/2008 was released.
Comment: AppLocker, not exactly a quick fix though. http://technet.microsoft.com/en-us/library/dd723678(WS.10).aspx
Answer: They will need to be members of the Administrators group, or you will need to give their user accounts r/w access to the registry branches and local filesystem where each app that you want them to install needs to write to.
Power users is useless now, and only exists for legacy reasons.


Spring webflow : Move through view states

Question: Within a spring webflow, i need to implement a navigation bar that will allow to "step back" or resume the flow to one of the previous view.
For example :

View 1 = login
View 2 = My informations
View 3 = My messages
View 4 = Close session

For this example, i would like to return back to view 2 from the view 4 page.
Comment: So...what's the question?  Is there a specific problem you're running into?
Answer: It depends how you're going about doing this.  If you're doing this within a single flow, you'll have something like this:
<code><view-state id="loginView" view="login.jsp">
    <action-state bean="someBean" method="login" />
    <transition on="success" to="informationView" />
</view-state>

<view-state id="informationView" view="information.jsp">
    <render-actions>
        <action-state bean="someBean" method="retrieveInformation" />
    </render-actions>
    <transition on="forward" to="messageView" />
    <transition on="back" to="loginView" />
</view-state>

<view-state id="messageView" view="message.jsp">
    <render-actions>
        <action-state bean="someBean" method="retrieveMessage" />
    </render-actions>
    <transition on="forward" to="closeView" />
    <transition on="back" to="informationView" />
</view-state>

<view-state id="closeView" view="logout.jsp">
    <transition on="jumpBack" to="informationView" />
</view-state>
</code>
The "jumpBack" transition on "closeView" will jump you back to view state #2, which is your information view.
With sub-flows it is tricky.  You'd need to chain it: call a subflow, and if an event is signaled that states you need to end your flow with a specific state, immediately do so.
For example, say that your flow chain is login->information->message->close.
On the close flow, the end-state would be "returnToInformation".
The message flow has a transition on="returnToInformation" to="returnToInformation".
"returnToInformation" is also an end-state in the message flow.
Then, the information flow has a transition on="returnToInformation" to="displayInformationPage", which would then re-display the information page.
Answer: I did this by defining some global flow that represented the tabs.  I then defined an object that represented the tabs on the flows and indicated if the current tab was active.  When the user moved through the tabs I updated the tab object as appropriate.
When the user went to click on one of the tabs it used the global flows to allow them to move between the tabs (for my implementation I found it easier to call actions rather than view states because you may find the views may change depending on the user interaction to get there so you may need to recalculate them).
For the tab bar itself, I put it in a single JSP that I then placed at the top of each form, this made updating it easier.
Its not the nicest solution, but it does work.
Good luck.


Infinite sum convergence test.

Question: I have to tell if the sum $$\sum_{n=1}^{\infty} (-1)^{n} \frac{1}{n + (-1)^{n+1}}$$
Converges or not. Can i use a comprasion test here? To assume that my sum is bigger than $\sum_{n=1}^{\infty} (-1)^{n} \frac{1}{n + 1}$? I dont think that's OK, but that's the only way I can think of right now.
Answer: How about this? Write out the series:
$$-1(\frac{1}{1 + 1}) + 1(\frac{1}{2-1})-1(\frac{1}{3 + 1})+1(\frac{1}{4-1})-1(\frac{1}{5+1})....$$
$$=\frac{-1}{2} + 1 -\frac{1}{4}+\frac{1}{3}-\frac{1}{6}+\frac{1}{5}-\frac{1}{8}....$$
Then reorder terms...
$$1 - \frac{1}{2} + \frac{1}{3}-\frac{1}{4}+\frac{1}{5}-\frac{1}{6}...$$
And it was the alternating harmonic series all along! Which has been proven to equal
$$\sum_{n=1}^{\infty}(-1)^{n+1}\frac{1}{n}=ln(2)$$
Comment: Since the series is not absolutely convergent, you need to be careful reordering terms.  Here it works, but other times it may not
Comment: Well, i like this one! But I'm new into calculus, so i would also use a version with some classic covergence tests :D Can you explain why does the hint below imply the convergence?
Comment: Kabo is using Big O notation, which is out of the scope of most 1st and 2nd level Calculus courses. The second part says sequence of partial sums itself approaches 0, which you can think of as the final term in the series is 0, so the last thing you add is nothing, which is a necessary characteristic of a convergent series. I would recommend the ratio or root test, though, which you can read about here: http://tutorial.math.lamar.edu/Classes/CalcII/SeriesStrategy.aspx
Comment: Thank you for the information, Henry! What is an instance in which this wouldn't work?
Answer: Hint: $a_{n+1}-a_n=O(\frac 1 {n^{2}})$. This and the fact that $a_n \to 0$ imply that the series is convergent.
Comment: I agree on that. But could you explain why does it imply the convegence of the series?
Comment: Show that the partial sums form a Cauchy sequence.

Infinite sum convergence test.


double factorial series problem

Question: In the problem the sum is given as $$\sum\limits_{n=1}^\infty \frac{(2n-1)!!}{(2n)!!}$$
and then when I try to solve it using Gauss's test I get
$$\frac{a_{n}}{a_{n+1}}=\frac{2n+2}{2n+1}$$
but in the solution there is given:
$$\frac{a_{n}}{a_{n+1}}=\frac{2n}{2n-1}$$
my reasoning was:
$$\frac{a_{n}}{a_{n+1}}=\frac{\frac{(2n-1)!!}{(2n)!!}}{\frac{(2n+1)!!}{(2n+2)!!}}=\frac{1\cdot3\cdot...\cdot(2n-1) \times 2\cdot4\cdot...\cdot2n\cdot(2n+2)}{2\cdot4\cdot...\cdot2n \times 1\cdot3\cdot(2n-1)\cdot(2n+1)}=\frac{2n+2}{2n+1}$$
I believe that I made a mistake, but I don't know where?
Comment: What is it you are trying to do?
Comment: Your calculation of the ratio $\frac{a_n}{a_{n+1}}$ is correct. The one you quote seems to have an index off by one issue. The ratio is unfortunately not directly useful in dealing with the issue of convergence.
Comment: To see is my reasoning true or not, because from that point I can solve the  rest of the problem...
Comment: As an aside, $\displaystyle\sum_{n=0}^\infty \bigg[\frac{(2n-3)!!}{(2n)!!}\bigg]^2~=~\frac4\pi$
Answer: $$\frac{(2n-1)!!}{(2n)!!} = \frac{(2n)!}{(2n)!!^2} = \frac{1}{4^n}\binom{2n}{n} $$
but the RHS behaves like $\frac{1}{\sqrt{\pi n}}$, hence the series is diverging. Also without the exact asymptotics:
$$ \left(\frac{(2n-1)!!}{(2n)!!}\right)^2 = \prod_{k=1}^{n}\left(1-\frac{1}{2k}\right)^2 = \frac{1}{4}\prod_{k=1}^{n}\left(1-\frac{1}{k}\right)\prod_{k=2}^{n}\left(1+\frac{1}{4k(k-1)}\right) \geq \frac{1}{4n}.$$

double factorial series problem


Copy HTML file with respective folder automatic

Question: I m facing problem regarding to copy html file respective folder automatic, it was works till day before yesterday, But I tried to copy file & folder using CMD command & after that not working.
I was tried below code
copy "C:\Test\AIR AND FLUE GAS SYSTEM1.htm" "C:\Test\Done\AIR AND FLUE GAS SYSTEM1.htm"
Xcopy "C:\Test\AIR AND FLUE GAS SYSTEM1_files" "C:\Test\Done\AIR AND FLUE GAS SYSTEM1_files" /s

But now if I copy html file then only copy selected file, but before that respective folder was also copied.
Comment: Not able to understand the last part 'But now if I copy html file then only selected file copy, but earliest respective folder also copy.'
Answer: Probably you need to use /s not \s
Comment: Ya it's \S, typo mistake
Answer: if this doesn't work for you then show us the error message.
copy "C:\Test\AIR AND FLUE GAS SYSTEM1.htm" "C:\Test\Done\"
Xcopy "C:\Test\AIR AND FLUE GAS SYSTEM1_files\*.*" "C:\Test\Done\AIR AND FLUE GAS SYSTEM1_files\" /s


Image style results in wrong image

Question: I had a very odd error where the image showed as style'ed but was using the wrong source image. When I deleted the style'ed image and reloaded the page, the correct image displayed and was style'ed.
I haven't figured out how to reproduce the error, but I am positive the source image didn't change.
Answer: This was likely a file-naming conflict of sorts. ImageCache (the module responsible for generating the image styles) generates a file name for each image style, and then checks for the presence of that file. If the file exists, it is served to the browser, otherwise it is generated and then served.
If you had a file called fruit.jpg that resulted in an image style of /files/styles/some/folder/fruit.jpg, and then deleted the source file, it is possible that the derivative style file wasn't removed (keep in mind, this a theory). If you then uploaded a different image with the same fruit.jpg filename and tried to generate the same image style again, ImageCache would find the previous /files/styles/somes/folder/fruit.jpg and serve that, resulting in the confusion you're seeing.
That said, I do believe derivative image styles get deleted when the source image is deleted, but I'm not sure of the specifics (ex. timing - it may happen during a cron run which wasn't ran).
For the most part, I wouldn't worry about it. Sounds like a onece in a million edge-case.

Image style results in wrong image


Flask - Setting root directory

Question: I have a folder structure that looks like so:
myproject/
    - flask_app/
        - app.py
        - templates/
    - module1.py
    - module2/
        - db.py
        - models/

I'm running into ImportErrors in my Flask application when trying to do the following:
from module2 import db
# or something else like
import module1

from flask import Flask
app = Flask(__name__)

if __name__ == "__main__":
    app.run(debug=True)

This is obviously because the Flask app is running from its own subdirectory "flask_app". I normally would try and get around this by running it like so:
python -m flask_app.app

But this doesn't seem to solve the problem.
Is there a way I run my flask app from the root folder without resorting to relative imports (using older version of Python)
Answer: When you run python -m flask_app.app, most likely sys.path won't include the myproject path.
Easiest would be to put a top-level script in the myproject directory; lets call it runsite.py:
from flask_app.app import app
app.run(debug=True)

and run that with Python:
$ python runsite.py

Flask - Setting root directory


How to get taxonomy term values?

Question: In my user entity, I have a term reference. In that vocabulary, I have a regular field. How can I fetch that field's value? I tried the below in  devel/php to no avail.
$user = Drupal\user\Entity\User::load(17);
$dept = $user->field_department->entity;
\dpm($dept->field_administrator_e_mail->value);

My end goal is to send the email to the department's administrator when a user is created.
UPDATE: I also tried the below:
$user = Drupal\user\Entity\User::load(17);
$dept = $user->field_department;
\dpm($dept->name);

Answer: Your missing link is the entity function, which returns the referenced entity object:
$host_entity->host_field->entity->remote_field->value
Comment: I tried `entity` as well, no luck - updating question
Comment: It wasn't working because of the way I added the taxonomy term to the entity.  It works correctly now, thanks.

How to get taxonomy term values?