text:
Q: How to tell this Java method to execute itself again under a certain condition? Please refer to this UVa OJ problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=27&page=show_problem&problem=2595
It's working for a single test case. However, there is no given input for the number of test cases, which means that the program should know when to continue and when to stop just by reading the input for the variables of the problem
I'm think about using the scanner.hasNextLine()method as a conditional; and if it's true, make main start again, but I'm not sure how to do it. Any clue?
public static void main(String[] args) {
    Scanner scanner = new Scanner (System.in);
    int N = scanner.nextInt();
    int B = scanner.nextInt();
    int H = scanner.nextInt();
    int W = scanner.nextInt();
    int [] priceArray = new int [H];
    int [] availableBeds = new int [W];
    int cheapestStay = 999999999;
    for (int i=0; i<H; i++){
        priceArray[i] = scanner.nextInt();

        for (int j=0; j<W; j++){
            availableBeds[j] = scanner.nextInt();
            if (availableBeds[j] >= N && priceArray[i]*N <= B && priceArray[i]*N < cheapestStay){
                cheapestStay = priceArray[i]*N;
            }

        }

    }

    if (cheapestStay != 999999999){
        System.out.println(cheapestStay);
    }else{
        System.out.println("stay home");
    }
    /*if (!scanner.hasNextLine)
        repeat*/
}

A: You could use a while loop to repeat the instructions of your main method as long as hasNextLine() evaluates to true.
public static void main(String[] args) {
    while(scanner.hasNextLine()){
        ...
    }
}

A: You can wrap all the code in your main(...) method into a while(scanner.hasNextLine()) loop

A: This is a best usecase of do-while
public static void main(String[] args) {
    Scanner scanner = new Scanner (System.in);
    do {

        int N = scanner.nextInt();
        int B = scanner.nextInt();
        int H = scanner.nextInt();
        int W = scanner.nextInt();
        int [] priceArray = new int [H];
        int [] availableBeds = new int [W];
        int cheapestStay = 999999999;
        for (int i=0; i<H; i++){
            priceArray[i] = scanner.nextInt();

            for (int j=0; j<W; j++){
                availableBeds[j] = scanner.nextInt();
                if (availableBeds[j] >= N && priceArray[i]*N <= B && priceArray[i]*N < cheapestStay){
                    cheapestStay = priceArray[i]*N;
                }

            }

        }

        if (cheapestStay != 999999999){
            System.out.println(cheapestStay);
        }else{
            System.out.println("stay home");
        }
        /*if (!scanner.hasNextLine)
            repeat*/
    } while (scanner.hasNextLine());
}


text:
Q: Importance of large gaps between zeros of zeta function? I have noticed that there are quite a few publications, many of them recent, on trying to determine the supremum of the gaps (normalized) between zeros of $\zeta \left(\frac{1}{2} + i t \right)$. Several make use of Wirtinger's inequality. I've been studying some of these papers in an attempt to broaden my knowledge of the zeta function.
My question is this - why are people interested in determining information about the gaps? I assume that there must be some information encoded in the gap sizes about the distribution of prime numbers. Is there a publication or book in which I could read about the reasons for studying the gaps?
Thanks,
Tom

A: Here are two papers that show a connection between the spacing of the zeros of the zeta function and the class number problem for imaginary quadratic fields:
Conrey, J. B., and H. Iwaniec, "Spacing of zeros of Hecke L-functions and the
class number problem."
Montgomery, H. L., and P. J. Weinberger, "Notes on small class numbers."
And of course the study of the pair correlation of the ordinates of the zeros of the zeta-function inspired the connection between the zeta function and random matrix theory. I believe some results about the gaps are ways to check that the zeros are spaced according to predictions that come from random matrix theory.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Iterate through multidimensional arraylist to hashMap in java I have a table as follows
                     Total  Upright  Supine  Meal  PostPr  ChestP     Other
Duration of Period   22:38  14:30   08:08  01:02   06:54   00:48     00:28
Number of Refluxes    5       4       1      0       3       2         0

From this I have created a multidimensional array Arr_ReflDay1_table2d as follows:
 [[Total, Upright, Supine, Meal, PostPr, ChestP, Other], [Duration of Period , 22:38, 14:30, 08:08, 01:02, 06:54, 00:48, 00:28], [Number of Refluxes, 5, 4, 1, 0, 3, 2, 0]]

I want to get it into a HashMap such that the Key is the row and column name a value came from. For example the hashMap might read:
Total_DurationOfPeriod=22:38,Upright_DurationOfPeriod=14:30,Supine_DurationOfPeriod=08:08 etc.
I tried doing this:
Map<String,String> mapReflDay1= new LinkedHashMap<String,String>();
    ArrayList<List<String>> Arr_ReflDay1_table2d = new ArrayList<List<String>>();
        for (int ff=0;ff<Arr_ReflDay1_table2d.size();ff++){
               for (int fg=0;fg<Arr_ReflDay1_table2d.size();fg++){
                  for (int fx=0;fx<Arr_ReflDay1_table2d.get(0).size();fx++){
                            mapReflDay1.put("ReflDay1"+Arr_ReflDay1_table2d.get(0).get(ff)+Arr_ReflDay1_table2d.get(fg).get(0)+","Arr_ReflDay1_table2d.get(ff).get(fx));
        }
                }
                      }

which gives the key fine but the value seems to only be taken from the final column

A: Solved it in the end. Just added an extra element to the first inner ArrayList so I was iterating over the same number of elements in each inner ArrayList


text:
Q: como encerrar o input quando usar o .hasNext() em java? Estou usando um código que utiliza Scanner (que dei o nome de input) e utiliza while(input.hasNextLine()), porém ele não pára de pedir entradas, sei que tem um comando especifico para isso (algo como /n) mas não consigo me recordar.
Alguém poderia me ajudar?

A: Olá você pode fazer algo assim:
Scanner ler = new Scanner(System.in);
//seu código de entrada
if (ler.equals("")) {
        ler.close();
    }
}


text:
Q: Let $R$ be a ring with unit $1$ and $\phi: \mathbb Z \implies D$ be defined as $\phi(n) = n1$. Show this is an homomorphism I'm wondering what does it mean to multiply $n\in \mathbb Z$ by a member of $R$? Shouldn't $\mathbb Z$ be a subring of $R$ in order for me to do it? What is this exercise really doing?
I'm supposed to prove that $\phi(n+k) = (n+k)1$? What does it mean?
Then the exercise asks me to prove that $\{m \in \mathbb Z: m1 = 0 \in R\}$ is an ideal of $\mathbb Z$
I can't understand


text:
Q: Automatically select configurable attributes I'm configuring a magento webshop for one of our clients. They've got colorcodes and due to that I have to set up configurable products. However, before the configurable products are being shown on the webshop I need to select an attribute to assign to it...
Now this is really unhandy if I have to import an entire catalog of +/- 800 products...
I already found the next script to make this automatically but I have no clue where to put it... I've already tried using it in the configurable.php file, didn't work. Please help me out!
    foreach($configAttrCodes as $attrCode){

        $super_attribute= Mage::getModel('eav/entity_attribute')->loadByCode('catalog_product',$attrCode->code);
        $configurableAtt = Mage::getModel('catalog/product_type_configurable_attribute')->setProductAttribute($super_attribute);

        $newAttributes[] = array(
           'id'             => $configurableAtt->getId(),
           'label'          => $configurableAtt->getLabel(),
           'position'       => $super_attribute->getPosition(),
           'values'         => $configurableAtt->getPrices() ? $configProduct->getPrices() : array(),
           'attribute_id'   => $super_attribute->getId(),
           'attribute_code' => $super_attribute->getAttributeCode(),
           'frontend_label' => $super_attribute->getFrontend()->getLabel(),
        );
        echo "test ";
    }
 echo "test2 ";
    if(empty($existingAtt) && !empty($newAttributes)){
        $configProduct->setCanSaveConfigurableAttributes(true);
        $configProduct->setConfigurableAttributesData($newAttributes);
        $configProduct->save();

A: This script is best used a shell script to assign the config attributes to products.  Its not complete thou.  I had to add alot to this script, like the ability to feed it product ids, and attribute codes to configure along with the configurable attributes.
Its hard to show you whats missing from it, since you need alot more than just this script to assign the attributes.  I run one script that grabs all the ids of the configurable products and then makes a cache file with them.  I them use another script to feed those ids to the above script so that it may configure them.  So in total, 3 scripts.  I then use a shell script to run that process.
This was posted by another user to help point you in the direction you need to be heading, but is no way a standalone script.  I can email you my source files for all three scripts and you can reverse them down to see what I did if that helps.


text:
Q: How to avoid need for User code knowing and instantiating concrete Strategy in Strategy Pattern Strategy pattern decouples the context code and strategies (or algorithm or policy) being used by it. It has an advantage over Template Pattern as it enables dynamic behavior change and uses composition with delegation to achieve it. Below is such example.
public class Context{
    private Policy policy;

    public void setPolicy(Policy policy){
        this.policy = policy;
    }

    public performTask(){
        policy.apply(); // delegate policy apply to separate class
        this.contextualWOrk();
    }
}

public interface Policy{
    void apply();
}

public class PolicyX{
     public void apply(){
         //Policy X implementation
     }
}

public class PolicyY{
     public void apply(){
         //Policy Y implementation
     }
}

Now the Code using above code
public class User{
    public void init(Context context){
         context.setPolicy(new PolicyX());
         context.performTask();
    }
}

Above we see the user code has to know and supply concrete Policy to Context. We can use Creational Pattern like Factory method pattern but still in such a case user code will have to know the concrete Factory class. This requires user code to instantiate and know about existence of such concrete implementations.
To prevent this a simple solution can be having a static method taking input as string or enum and using 'switch-case' or multiple 'if-else' statements deciding which class to instantiate and provide the implementation to user code. But again this violates 'OCP' as in case of addition of a new type will require the code to be modified.
How this can be made to follow principles in simple application (I am not sure may be with some configurations Spring and other frameworks solves such issues).
Any hints or key points to solve this in simple application will be helpful.

A: This drawback of the Strategy Pattern is mentioned on page 318.

Clients must be aware of different Strategies. The pattern has a potential drawback
  in that a client must understand how Strategies differ before it can
  select the appropriate one. Clients might be exposed to implementation issues.
  Therefore you should use the Strategy pattern only when the variation
  in behavior is relevant to clients.

As you've noted, the strategy selection mechanism can be hidden behind other layers of code, or moved to a configuration file; but the underlying selection must still be made somewhere. This is simply a drawback of the pattern to be aware of when choosing to apply it.


text:
Q: Syncfusion PDF viewer using SignaturePad in Xamarin? I'm trying to make Syncfusion PDF viewer work with Syncfusion SignaturePad to add a stamp to a PDF file, is there any documentation besides SyncFusions on how to do this? There's doesn't appear to go into enough detail on how to get the program to work.
Thanks in advance


text:
Q: PHP not receiving AJAX POST from js File I have been trying to work this out for hours now and cannot find any answer that helps me.
This is the code in my javascript file
function sendMovement(cel) {
  var name = "test";
  $.ajax({
      type: 'POST',
      url: '../game.php',
      data: { 'Name': name },
      success: function(response) {
          console.log("sent");
      }
  });
}

This is the code from my PHP file (it is outside the js file)
if($_SERVER["REQUEST_METHOD"] == "POST") {
  $data = $_POST['Name'];
  console_log($data);
}

When debugging I can see that AJAX is sending a POST and it does print in the console "SENT" but it does not print $data
update: the function console_log() exists in my PHP file and it works

A: Try getting response in JSON format, for that your js should have dataType:'JSON' as shown below
JS Code:-
function sendMovement(cel) {
  var name = "test";
  $.ajax({
      type: 'POST',
      dataType:'JSON',   //added this it to expect data response in JSON format
      url: '../game.php',
      data: { 'Name': name },
      success: function(response) {
          //logging the name from response
          console.log(response.Name);
      }
  });
}

and in the current server side code you are not echoing or returning anything, so nothing would display in ajax response anyways.
changes in php server code:-
if($_SERVER["REQUEST_METHOD"] == "POST") {

  $response = array();
  $response['Name'] = $_POST['Name'];
  //sending the response in JSON format
  echo json_encode($response);

}

A: I fixed it by doing the following:
To my game.php I added the following HTML code (for debugging purposes)

Also added in my game.php the following
if($_SERVER["REQUEST_METHOD"] == "POST") {

  $gameID = $_POST['gameID'];
  $coord = $_POST['coord'];
  $player = $_POST['player'];

  echo "gameID: " . $gameID . "\nCoord: " . $coord . "\nPlayer: " . $player;

}

AND in my custom.js I updated
function sendMovement(cel) {
  var handle = document.getElementById('response');
  var info = [gameID, cel.id, current_player];

  $.ajax({
    type: 'POST',
    url: '../game.php',
    data: {
      gameID: info[0],
      coord: info[1],
      player: info[2]
    },
    success: function(data) {
      handle.innerHTML = data;
    },
    error: function (jqXHR) {
      handle.innerText = 'Error: ' + jqXHR.status;
    }
  });
}


text:
Q: How to make a function start only after another function fully completed in JavaScript? In the below code I'm tried create a game .when user press the button every time  it will generate a random number between 1 to 3 and add it with the previous score ( 9 is the finishing point ). There also have two function pump() and demotive() .if the user  reach total point 6 pump() will make it to the 8. if user reach 7 the demotive() make it 3.

var k = 0;
document.getElementById("btn").addEventListener("click", function () {

    var num = Math.floor(Math.random() * 100);
    num = num % 3; /*generate a random no between 0 to 2*/
    num = num + 1; /*generate a random no between 1 to 3*/
    //alert(num);/* check the no*/
    document.getElementById("currnt-value").innerHTML = "you get" + num;
    k = k + num;
    var parent = document.getElementById('a' + k);
    var circle = document.getElementById('crcl');
    parent.appendChild(circle);
    pump(k);
    demotive(k);
});

function pump(val) {
    if (val == 6) {
        alert("you get pumped");
        k = 8;
        var parent = document.getElementById('a' + k);
        var circle = document.getElementById('crcl');
        parent.appendChild(circle);
    }
}

function demotive(val) {

    if (val == 7) {
        alert("oh..!!!you are demotived");
        k = 3;
        var parent = document.getElementById('a' + k);
        var circle = document.getElementById('crcl');
        parent.appendChild(circle);
    }
}
html,body{
  width:100%;height:100%;
  }

#board{
  width:300px;
  height:300px;
  border:1px solid #000;

  }
#one,#two,#three{
  width:100%;
  height:100px;
  float:left;
  }
.flag-point{
  width:100px;
  float:left;
  height:100%;
  }
#a8,#a2,#a4,#a6 {
  background-color:green;
  }

#crcl{
  width:30px;
  height:30px;
  background-color:red;
  border:1px solid #000;
  border-radius:50%;
  }

 <button id="btn">move circle</button>

9

8

7

6

5

4

3

2

1

But if I'm standing on 4 and if I get a score "two" then directly moved to the 8 instead of 6 => 8 . How can I fix that?.I want to demonstrate both movements(first move from 4 to 6 and then the pumped move from 6 to 8 one by one).How can I achieve that?

A: To show the movement by pump() as 2 steps, you'll have to give the UI time to redraw in between the 2 movements. Currently, it won't redraw until the end of the click event, when k and the circle are already at 8.
You can give it that time with a brief setTimeout().
function pump(val) {
    if (val == 6) {
        setTimeout(function () {
            alert("you get pumped");
            k = 8;
            var parent = document.getElementById('a' + k);
            var circle = document.getElementById('crcl');
            parent.appendChild(circle);
        }, 10);
    }
}

The delay doesn't have to be long; the alert() will hold the user's attention while the circle shows on square 6.

Combined with your example:

var k = 0;
document.getElementById("btn").addEventListener("click", function () {

    var num = Math.floor(Math.random() * 100);
    num = num % 3; /*generate a random no between 0 to 2*/
    num = num + 1; /*generate a random no between 1 to 3*/
    //alert(num);/* check the no*/
    document.getElementById("currnt-value").innerHTML = "you get" + num;
    k = k + num;
    var parent = document.getElementById('a' + k);
    var circle = document.getElementById('crcl');
    parent.appendChild(circle);
    pump(k);
    demotive(k);
});

function pump(val) {
    if (val == 6) {
        setTimeout(function () {
            alert("you get pumped");
            k = 8;
            var parent = document.getElementById('a' + k);
            var circle = document.getElementById('crcl');
            parent.appendChild(circle);
        }, 200);
    }
}

function demotive(val) {

    if (val == 7) {
        alert("oh..!!!you are demotived");
        k = 3;
        var parent = document.getElementById('a' + k);
        var circle = document.getElementById('crcl');
        parent.appendChild(circle);
    }
}
html,body{
  width:100%;height:100%;
  }

#board{
  width:300px;
  height:300px;
  border:1px solid #000;

  }
#one,#two,#three{
  width:100%;
  height:100px;
  float:left;
  }
.flag-point{
  width:100px;
  float:left;
  height:100%;
  }
#a8,#a2,#a4,#a6 {
  background-color:green;
  }

#crcl{
  width:30px;
  height:30px;
  background-color:red;
  border:1px solid #000;
  border-radius:50%;
  }

 <button id="btn">move circle</button>

9

8

7

6

5

4

3

2

1

A: There are many ways you can decide weather you want to execute function in parallel or in serial. You can also decide order of execution in case one function is dependent in another.

*

*call back function:
As mentioned above, the call back function will execute once the parent function complete its execution.

*Promise:
It is more advanced then callback and you can set dependent function
like
promise.all(fun1,  fun2, ...).then(fun3)
promise.when(fun1).then(fun2)

*Observable:
RxJs observable is also provides such mechanism and can be explore
Other option you can explore if exist.

A: Actually you can add callback to your javascript function so it will be executed in order.
for example

function pump(param, callback){
    //do something here with your param

    callback();
}

function demotive(param){
    //do something
}

//call the function in order pump, then demotive after pump finishes
pump(1, function(){
    demotive(4);
});

this link here also will help


text:
Q: Sometimes, scaling down a bitmap generates a bigger file. Why? I'm trying to write a method to reduce the size of any image 50% each time is called but I've found a problem. Sometimes, I end up with a bigger filesize while the image is really just half of what it was. I'm taking care of DPI and PixelFormat. What else am I missing?
Thank you for your time.
public Bitmap ResizeBitmap(Bitmap origBitmap, int nWidth, int nHeight)
{
    Bitmap newBitmap = new Bitmap(nWidth, nHeight, origBitmap.PixelFormat);

    newBitmap.SetResolution(
       origBitmap.HorizontalResolution,
       origBitmap.VerticalResolution);

    using (Graphics g = Graphics.FromImage((Image)newBitmap))
    {
        g.InterpolationMode = InterpolationMode.HighQualityBicubic;

        g.DrawImage(origBitmap, 0, 0, nWidth, nHeight);
    }

    return newBitmap;
}

Edit:
Here's the missing code:
int width = (int)(bitmap.Width * 0.5f);
int height = (int)(bitmap.Height * 0.5f);
Bitmap resizedBitmap = ResizeBitmap(bitmap, width, height);
resizedBitmap.Save(newFilename);

Edit 2:
Based on your comments, this is the solution I've found:
private void saveAsJPEG(string savingPath, Bitmap bitmap, long quality)
{
    EncoderParameter parameter = new EncoderParameter(Encoder.Compression, quality);
    ImageCodecInfo encoder = getEncoder(ImageFormat.Jpeg);
    if (encoder != null)
    {
        EncoderParameters encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = parameter;
        bitmap.Save(savingPath, encoder, encoderParams);
    }
}

private ImageCodecInfo getEncoder(ImageFormat format)
{

    ImageCodecInfo[] codecs = ImageCodecInfo.GetImageDecoders();
    foreach (ImageCodecInfo codec in codecs)
        if (codec.FormatID == format.Guid)
            return codec;

    return null;
}

A: You are most probably saving the jpeg image with a low compression ratio (high quality).

A: Recompressing a JPEG image is something you ought to avoid.  But the real problem here is the InterpolationMode, a high quality one produces a lot of subtly shaded pixels, making it harder to compress the image.  Using InterpolationMode.NearestNeighbor should avoid that, but at the cost of getting a lower quality image.

A: The problem isn't situated in the code you posted, but where you save the JPEG. What compression ratio are you using?

A: I would say that you are saving it as a high quality jpeg (less compression == more space)

A: Seeming as your bitmaps are actually saved as jpegs, and knowing how c# likes to do things for you, it is probably saving with a default compression level that is fairly low.  The original jpeg must have a decent compression level on it. Even if it was the same compression level, the way the jpeg format works may mean that you have found a fluke image that dose bloat at a lower resolution.
A bit map though is an exact size, if it is ten pixels wide and ten high, it is 100 pixels, in say 16 bit (2 byte) colour that's 200 bytes, plus a bit of header.
lower the resolution to 5 by 5, you have 50 bytes plus a bit of header, should be the same amount of header though.

A: Try this code to save the JPEG you have. It will allow you setting the compression quality. Experiment and see if it helps your size problem:
private void saveJpeg(string path, Bitmap img, long quality)
{
    EncoderParameter parameter = new EncoderParameter(Encoder.Quality, quality);
    ImageCodecInfo encoder = this.getEncoderInfo("image/jpeg");
    if (encoder != null)
    {
        EncoderParameters encoderParams = new EncoderParameters(1);
        encoderParams.Param[0] = parameter;
        img.Save(path, encoder, encoderParams);
    }
}

private ImageCodecInfo getEncoderInfo(string mimeType)
{
    ImageCodecInfo[] imageEncoders = ImageCodecInfo.GetImageEncoders();
    for (int i = 0; i < imageEncoders.Length; i++)
    {
        if (imageEncoders[i].MimeType == mimeType)
        {
            return imageEncoders[i];
        }
    }
    return null;
}

A: It seems like the original is the output from a digital camera. I think the camera producers use proprietary super optimized compression algoritms, while a common library may have a less effective implementation. (And of course you're probably not using the same compression level as the camera.)
In addition the camera uses the raw data (possibly doing some "magic" preprocessing on it first) from its sensors as input. While when you re-compress it, the input has compression and rescaling artifacts in it which may cause the compression to be less effective.
Actually i think if you compress an image several times with the same jpg algoritm at the same level, it could grow in size because the artifacts from the previous compressions adds "details" that is harder to compress (and it becomes uglier too).
(The camera compression algoritm may also be optimized for the fact that the input is always a photo, while a general purpose algoritm may do some less effective stuff to work reasonably well both for photos and line art mixed images containing both photo and generated graphical elements.)


text:
Q: Running the same code but with two different datasets (inputs) I have a code in JupyterLab that consists of several functions spread in several cells. The first function generates a dataset that is used in all other functions after it.
What I have to do is run the same code twice but with one of the functions modified. So it would look like this:
data_generating_function() # this function should only be ran once so it generates the same dataset for both trials
function_1() # this is the function that is to be modified once, so there are two version of this function
function_2() # this function and all functions below it stay the same but should be ran twice
function_3()
function_4()
function_5()

So I would run data_generating_function() once and generate the dataset. Then I would run one version of function1() and all the functions below it, then I would run another version of function1() and all the other functions below it.
What would be a good way to implement this? I could obviously duplicate the code and just change some function names, I could also put it all into a single cell and create a for loop. However is there a better way that would ideally preserve multiple cells too?
Thank you

A: Simply iterate over your two choices for the first function:
data_generating_function()
for func1 in (function1a, function1b):
    func1()
    function_2()
    function_3()
    function_4()
    function_5()

A: Apologies if I misunderstood the question, but could you not do the following:
Cell 1:
# define all functions

Cell 2:
dataset = data_generating_function()

Cell 3:
# Run version 1 of function 1 on dataset
result_1_1 = function_1_v1(dataset)
result_2_1 = function_2(result_1_1)
result_3_1 = function_3(result_2_1)
function_4(result_3_1)

Cell 4:
# Run version 2 of function 1 on dataset
result_1_2 = function_1_v2(dataset)
result_2_2 = function_2(result_1_2)
result_3_2 = function_3(result_2_2)
function_4(result_3_2)

This solution assumes that:

*

*you define functions with return values

*that passing around the results is not "expensive"

You can also persist the results in a file if the latter is not the case.
To reduce code duplication in function_1, you can add a parameter that switches between the two versions.

A: You should try to avoid modifying or directly iterating over functions whenever possible. The best thing to do in this case would be to add a boolean parameter to function1 specifying which version of the function you want to run. It would look something like this:
def function1(isFirstTime):
  if isFirstTime:
    # do stuff the first time
    pass
  else:
    # do stuff the second time
    pass

You could then iterate over the functions:
data_generating_function()
for b in (True, False):
  function1(b)
  function2()
  function3()
  # ...


text:
Q: How to fill gaps between dated entries in table I have a set of dated records in @dailylogs.
Lets say I have a row(dailylog) for the 1st of the month.  When I add a new record for say the 15th how can I add a blank entry for each day in between please so that every day of the month has an entry.
I can work out the number of days between the two dates so some sort of loop through @dailylogs to check if the days in between have an entry....but I just cant't work it out.
Thanks

A: If you have two Date objects is very simple.
require 'date'

from = Date.new(2017, 1, 1)
to   = Date.new(2017, 1, 5)

from.step(to).to_a
 => [#<Date: 2017-01-01 ((2457755j,0s,0n),+0s,2299161j)>, #<Date: 2017-01-02 ((2457756j,0s,0n),+0s,2299161j)>, #<Date: 2017-01-03 ((2457757j,0s,0n),+0s,2299161j)>, #<Date: 2017-01-04 ((2457758j,0s,0n),+0s,2299161j)>, #<Date: 2017-01-05 ((2457759j,0s,0n),+0s,2299161j)>]

A: I did it like this in the end:
x = 1
day_range.times do
  if Dailylog.search_day(date_today.month, date_today.year, x, user).blank?
    create_date = DateTime.new(date_today.year, date_today.month, x)
    Dailylog.create(date: create_date, miles: "0", locations: "nil", user_id: user)
  end
  x+=1
end

which used:
def Dailylog.search_day(month, year, day, user)
where("cast(strftime('%m', date) as int) = ?", month)
.where("cast(strftime('%Y', date) as int) = ?", year)
.where("cast(strftime('%d', date) as int) = ?", day)
.where("user_id = ?", user)

end
It works but as a beginner happy to be corrected if can be done better.
Thx.


text:
Q: python 3+ with tkinter: modal window not appearing I'm new to python. I'm trying to set up a GUI with a main window and a modal window to receive the database credentials. The main window has to be in the background when the modal window appears and the user should not interact with it. Actually the application should terminate in case the user fails to provide a valid username and password. I'm presenting part of the code here. What I get is the main window (the modal window does not appear at all) and I can't do anything but shut the program down - not directly; only through visual studio.
'''
import tkinter as tk

class login:

   def checkDbCredentials(self, user, password):
       if (len(user)<4 or len(password)<4):
           return 0
       return 1

   def ok(self):
       us = self.user.get()
       pw = self.password.get()
       if self.checkDbCredentials(us, pw)==0:
           tk.messagebox.showinfo("Error", "Username and Password do not match")
           sys.exit(0)
       self.dic['user']=us
       self.dic['pass']=pw
       self.win2.destroy()

   def cancel(self, event=None):
      self.parent.focus_set()
      self.destroy()

   def widgets(self):
      x = self.win2.winfo_screenwidth()
      y = self.win2.winfo_screenheight()
      xx = int((x-270)/2)
      yy = int((y-85)/2)
      geo = "270x85+" + str(xx) + "+" + str(yy)
      self.win2.geometry(newGeometry=geo)
      self.tempLab= tk.Label(self.win2, text="Username:", pady=5)
      self.tempLab1 = tk.Label(self.win2, text="Password:")
      self.iuser = tk.Entry(self.win2, textvariable = self.user, width=30)
      self.ipass = tk.Entry(self.win2, textvariable = self.password, width=30, show="*")
      self.tempLab.grid(column=0, row=0)
      self.tempLab1.grid(column=0, row=1)
      self.iuser.grid(column=1, row=0)
      self.ipass.grid(column=1, row=1)
      self.bt = tk.Button(self.win2, text="Submit", command=lambda: self.ok())
      self.bt.grid(column=0, row=2, columnspan=2, pady=5)
      self.win2.bind("<Return>", self.ok)
      self.win2.bind("<Escape>", self.cancel)

   def __init__(self, dic, parent):
      self.win2 = tk.Toplevel(parent)
      self.parent=parent
      self.dic = dic
      self.user = tk.StringVar()
      self.password = tk.StringVar()
      self.win2.overrideredirect(1)
      self.widgets()
      self.win2.transient(parent)
      self.win2.grab_set()
      self.win2.protocol("WM_DELETE_WINDOW", self.cancel)

      self.parent.wait_window(self.win2)

And the main class code is the following:
import tkinter as tk
from tkinter import ttk, X, Y, BOTH
from tkinter import messagebox
import sys
import login

class mainWindow:

   def connect(bt, fr):
       notImplementedYet()

   def notImplementedYet():
       msg = tk.messagebox
       msg.showinfo("Warning", "Not Implemented yet!")

   btX = 20
   btY = 5
   btSunken = '#aec2c2' # sunken button color
   btRaised = '#85adad' # normal button color
   rw = 0 # starting row for buttons
   cl = 0 # starting column

   dbCredentials = {"user":"", "pass":""}

   win = tk.Tk()
   win.title("Title")
   win.geometry(newGeometry="1366x700+00+00")
   win.iconbitmap(bitmap="bitmap.ico")

   fr1 = tk.Frame(win, width=1366, height=50, background='beige')
   fr1.grid(column=cl, row=rw, rowspan=5)
   fr2 = tk.Frame(win)
   fr2.grid(column=0, row=1)
   lb2 = tk.Label(fr2, text="frame         2", background=btRaised)
   btConnect = tk.Button(fr1, text="Connect", background = btRaised ,command=lambda: connect(btConnect, fr1), width=btX, height=btY)
   btConnect.grid(column=0, row=0)

   log = login.login(dbCredentials, win)
   win.wait_window(log.win2)
   print(dbCredentials)

   win.mainloop()

win = mainWindow()

The question is why is the modal window not appearing? I've tried placing the 'wait_window' in the other class as well but it's still not working.


text:
Q: Devise undefined method `build' for nil:NilClass I am currently enrolled in a online course in ruby on rails and im learning everything from scratch so pardon me if Im not clear in my questions. Here is my delima, I am trying to create a LINK between two Models in the rails application and here is what I have so far. However when I try to access localhost3000/business/new it returns the error mentioned it the title. I have come to the conclusion that it is because of me using a "has_one :model" type of association, rather than the "has_many :model". I hope someone can point me in the right direction here as I have spent hours searching to no solutions.
class BusinessesController < ApplicationController
  before_action :set_business, only: [:show, :edit, :update, :destroy]
  //edited for clarity
  def new
    @business = current_user.business.build  //The line that returns a undefined method for nil class
  end

  def edit
  end

  def create
    @business = current_user.business.build(business_params)

    if @business.save
      redirect_to @business, notice: 'Business was successfully created.'
    else
      render "new"
    end
  end

Devise User Model
class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :buzzs, dependent: :destroy
  has_one :business, dependent: :destroy
end

Business Model
class Business < ActiveRecord::Base
    belongs_to :user
end

A: Take a look at this http://guides.rubyonrails.org/association_basics.html#has-one-association-reference.
You should use build_business instead of business.build
4.2.1 Methods Added by has_one
When you declare a has_one association, the declaring class automatically gains five methods related to the association:
association(force_reload = false)
association=(associate)
build_association(attributes = {})
create_association(attributes = {})
create_association!(attributes = {})

A: One to One Association:
class User < ActiveRecord::Base
  has_one :business
end

current_user.build_business

Or if One to Many:
class User < ActiveRecord::Base
  has_many :businesses
end

current_user.businesses.build


text:
Q: PostgreSQL: Foreign key between composite type and independent columns Minimal definitions:
CREATE TYPE GlobalId AS (
  id1 BigInt,
  id2 SmallInt
);

CREATE TABLE table1 (
  id1 BigSerial NOT NULL,
  id2 SmallInt NOT NULL,
  PRIMARY KEY (id1, id2)
);

CREATE TABLE table2 (
  global_id GlobalId NOT NULL,
  FOREIGN KEY (global_id) REFERENCES table1 (id1, id2)
);

In short, I use a composite type for table2 (and many other tables), but for the primary table (table1), I don't directly use the composite type because composite types don't support the use of Serial.
The above produces the following error due to the ostensible mismatch between global_id and id1, id2: number of referencing and referenced columns for foreign key disagree.
Alternatively, if I define the foreign key as FOREIGN KEY (global_id.id1, global_id.id2) REFERENCES table1 (id1, id2), I get a syntax error on using an accessor on global_id.
Any ideas on how to define this foreign key relationship? Alternatively, if there's a way for table1 to use the GlobalId composite type while still getting serial/sequence behavior for id1, that works also.

A: You can define table1 using your composite type and fill the value using a BEFORE trigger:
CREATE TABLE table1 (id globalid PRIMARY KEY);

CREATE SEQUENCE s OWNED BY table1.id;

CREATE FUNCTION ins_trig() RETURNS trigger LANGUAGE plpgsql AS
$$BEGIN
   NEW.id = (nextval('s'), (NEW.id).id2);
   RETURN NEW;
END;$$;

CREATE TRIGGER ins_trig BEFORE INSERT ON table1 FOR EACH ROW
   EXECUTE PROCEDURE ins_trig();

INSERT INTO table1 VALUES (ROW(NULL, 42));

SELECT * FROM table1;
   id
--------
 (1,42)
(1 row)


text:
Q: fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib' Seem I can't get this to work. I made a simple console application (which depend on websocket++ library) which need Boost libraries.. but when I try to compile I get:

fatal error LNK1104: cannot open file 'libboost_system-vc110-mt-gd-1_51.lib'

However, I did the bjam which created the lib in (boost_root)/stage/libs and I linked the path to the libs to the compiler C++/Additionnals includes.
If I look in (boost_root)/stage/libs the file  libboost_system-vc110-mt-gd-1_51.lib is not there. It is called libboost_system-vc110-mt-sgd-1_51.lib instead.
Any idea?

A: The C++ → General → Additional Include Directories parameter is for listing directories where the compiler will search for header files.
You need to tell the linker where to look for libraries to link to. To access this setting, right-click on the project name in the Solution Explorer window, then Properties → Linker → General → Additional Library Directories. Enter <boost_path>\stage\lib here (this is the path where the libraries are located if you build Boost using default options).

A: Yet another solution:
I was stumped because I was including boost_regex-vc120-mt-gd-1_58.lib in my Link->Additional Dependencies property, but the link kept telling me it couldn't open libboost_regex-vc120-mt-gd-1_58.lib (note the lib prefix).  I didn't specify libboost_regex-vc120-mt-gd-1_58.lib.
I was trying to use (and had built) the boost dynamic libraries (.dlls) but did not have the BOOST_ALL_DYN_LINK macro defined.  Apparently there are hints in the compile to include a library, and without BOOST_ALL_DYN_LINK it looks for the static library (with the lib prefix), not the dynamic library (without a lib prefix).

A: I had the same problem. It was caused because I compiled the Boost with the Visual C++ 2010(v100) and I tried to use the library with the Visual Studio 2012 (v110) by mistake.
So, I changed the configurations (in Visual Studio 2012) going to Project properties -> General -> Plataform Toolset and change the value from Visual Studio 2012 (v110) to Visual Studio 2010 (v100).

A: I had the same problem and my mistake was that I had installed the binary boost_1_55_0-msvc-11.0-32.exe to use with visual c++ 2010 which has the version v100  (project properties->ConfiguratioProperties->General->platformTooset) not v110 as visual c++ 2012. So I dowloaded boost_1_55_0-msvc-10.0-32.exe and now everything is ok so far.

A: I had a similar problem when trying to use boost unit testing in Visual Studio 2015 (Community Edition):

fatal error LNK1104: libboost_unit_test_framework-vc140-mt-1_57

so I thought I'd share my solution.
You can create a boost unit testing project in of of two ways (and this solution works for both):

*

*using the Boost Unit Test Adapter

*or by creating a Win32 Console Application (steps here), and substituting the main function with a boost unit testing function (steps here).

Here are the steps I followed to get both projects to work:
First, download the desired boost version (for example, boost_1_57_0). You can either download boost with the correct binaries (compiled using msvc v140), or extract the binaries yourself by running the following commands from command line:

*

*bootstrap.bat

*"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat" x86

*bjam --clean

*bjam -j4 --debug-symbols=on --build-type=complete toolset=msvc-14.0 threading=multi runtime-link=shared
address-model=32

Where msvc-14.0 specifies that we require the Visual Studio 2015 version (VS 2015 = v14.0 = v140), and address-model=32 specifies that we require platform 32 (but the same can be done for 64 bit).
Once you have the binaries, go to Visual Studio, select the Boost Unit Testing project you have created. Go to Project properties > configuration (from the main menu) and make the following choices:

*

*Set the "General > Platform Toolset" to Visual Studio 2015 (v140).

*Include the path to the boost folder (e.g. C:\boost_1_57_0) and the path to the subfolder containing the binary files (e.g. C:\boost_1_57_0\stage\lib) in:

*

*"C\C++ > Additional Include Directory"

*and "Linker > Additional Library Directories".

A: In case you have trouble building boost or prefer not to do that, an alternative is to download the lib files from SourceForge.  The link will take you to a folder of zipped lib and dll files for version 1.51.  But, you should be able to edit the link to specify the version of choice.  Apparently the installer from BoostPro has some issues.

A: b2 -j%cores% toolset=%msvcver% address-model=64 architecture=x86 link=static threading=multi runtime-link=shared --build-type=minimal stage --stagedir=stage/x64
Properties → Linker → General → Additional Library Directories
$(BOOST)\stage\x64\lib

A: This is the simplest way for an amateur like me who is studying C++ on their own:
First Unzip the boost library to any directory of your choice. I recommend c:\directory.

*

*Open your visual C++.

*Create a new project.

*Right click on the project.

*Click on property.

*Click on C/C++.

*Click on general.

*Select additional include library.

*Include the library destination. e.g. c:\boost_1_57_0.

*Click on pre-compiler header.

*Click on create/use pre-compiled header.

*Select not using pre-compiled header.

Then go over to the link library were you experienced your problems.

*

*Go to were the extracted file was c:\boost_1_57_0.

*Click on booststrap.bat (don't bother to type on the command window just wait and don't close the window that is the place I had my problem that took me two weeks to solve. After a while the booststrap will run and produce the same file, but now with two different names: b2, and bjam.

*Click on b2 and wait it to run.

*Click on bjam and wait it to run. Then a folder will be produce called stage.

*Right click on the project.

*Click on property.

*Click on linker.

*Click on general.

*Click on include additional library directory.

*Select the part of the library e.g. c:\boost_1_57_0\stage\lib.

And you are good to go!

A: If you are using Visual Studio, have you tried using Tools / NuGet Package Manager to install boost_program_options-vcXXX? This is an easy way of installing boost.

A: I had same issue reported here.
I solved the issue moving the mainTest.cpp from a subfolder src/mainTest/ to the main folder src/
I guess this was your problem too.

A: 2>LINK : fatal error LNK1104: cannot open file 'libboost_regex-vc120-mt-sgd-1_55.lib
In my case, bootstrap/bjam was not available (libraries were precompiled and committed to SCM) on old inherited project. Libraries did not have VC or BOOST versioning in their filenames eg: libboost_regex-mt-sgd.lib, however Processed /DEFAULTLIB:libboost_regex-vc120-mt-sgd-1_55.lib was somehow triggered automatically.
Fixed by manually adding the non-versioned filename to:
<AdditionalDependencies>$(DK_BOOST)\lib64\libboost_regex-mt-sgd.lib</AdditionalDependencies>

and blacklisting the ...vc120-mt-sgd-1_55.lib in
<IgnoreSpecificDefaultLibraries>libboost_regex-vc120-mt-sgd-1_55.lib</IgnoreSpecificDefaultLibraries>

A: I had the similar error on my Visual Studio 2012 with boost 1.60: fatal error LNK1104: cannot open file 'libboost_filesystem-vc110-mt-gd-1_60.lib'
I fixed this issue  by downloading boost binaries:

*

*Download boost binary from https://sourceforge.net/projects/boost/files/boost-binaries/. For example: https://master.dl.sourceforge.net/project/boost/boost-binaries/1.60.0/boost_1_60_0-msvc-11.0-32.exe?viasf=1

*Save the file at a directory. e.g. C:\boost_1_60_0

*Run the downloaded exe file

*In Visual Studio, modify Additional Include Directories for the project to  include the boost directory. e.g. C:\boost_1_60_0

*In Visual Studio, modify additional library directory for the project to include the lib directory. e.g. C:\boost_1_60_0\lib32-msvc-11.0


text:
Q: TRIGGER não funciona no MYSQL Estou tentando fazer uma TRIGGER que insira dados numa tabela, assim que sejam inseridos dados em outra tabela.
Tabela Original:
    CREATE TABLE tbGuia (
  codigo_guia INT NOT NULL AUTO_INCREMENT,
  descricao_guia VARCHAR(100) NOT NULL,
  data_vencimento_guia DATE NOT NULL,
  ambito_guia VARCHAR(45) NOT NULL,
  status_guia VARCHAR(45) DEFAULT "Pendente",
  codigo_cliente INT NOT NULL,
  CONSTRAINT pk_tbGuia PRIMARY KEY (codigo_guia),
  CONSTRAINT fk_tbGuia_client
    FOREIGN KEY (codigo_cliente)
    REFERENCES tbCliente (codigo_cliente)
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

Tabela que desejo povoar com a TRIGGER:
CREATE TABLE tbClienteGuia (
  codigo_cliente INT NOT NULL,
  codigo_guia INT NOT NULL,
  data_visualizacao DATE NOT NULL DEFAULT "0000-00-00",
  data_postagem DATE NOT NULL,
  CONSTRAINT pk_TbClienteGuia PRIMARY KEY (codigo_cliente, codigo_guia, data_visualizacao, data_postagem),
  CONSTRAINT fk_tbClienteGuia
    FOREIGN KEY (codigo_cliente)
    REFERENCES tbCliente (codigo_cliente)
    ON DELETE CASCADE
    ON UPDATE CASCADE,
  CONSTRAINT fk_tbGuiaCliente
    FOREIGN KEY (codigo_guia)
    REFERENCES tbGuia (codigo_guia)
    ON DELETE CASCADE
    ON UPDATE CASCADE)
ENGINE = InnoDB;

A Trigger:
DELIMITER $$
CREATE TRIGGER vincular_guia_cliente AFTER INSERT ON tbguia
FOR EACH ROW
BEGIN
    INSERT INTO tbclienteguia (codigo_cliente, codigo_guia, data_visualizacao, data_postagem)
    VALUES (NEW.codigo_cliente, NEW.codigo_guia, "0000-00-00", CURDATE());
END$$
DELIMITER ;

Alguma sugestão?
OBS: não dá erro, apenas não aciona a trigger quando faço a inserção na tbGuia.

A: Você precisa garantir que ao executar a trigger, os dados de referencia estejam disponíveis.
tanto para:
REFERENCES tbCliente (codigo_cliente)

Onde o codigo_cliente precisa ser garantido estar cadastrado.

Quanto para:
REFERENCES tbGuia (codigo_guia)

Onde o codigo_guia precisa garantir estar cadastrado.

Se estas duas contrainsts não forem garantidas ssua trigger vai falhar na execução.


text:
Q: Use a link button command argument as a panel refernce I are trying to dynamically reference a Panel in the code behind file using a command argument from a linkbutton. The linkbutton and panel code is:
<asp:Panel ID="pnlLeaseControls" runat="server">
        <asp:LinkButton ID="btnLessorEmail" CssClass="btn btn-default" runat="server" CommandArgument="pnlLessorEmail" OnCommand="displayEmailSection">Lessor</asp:LinkButton>
        <asp:LinkButton ID="btnLesseeEmail" CssClass="btn btn-default" runat="server" CommandArgument="pnlLesseeEmail" OnCommand="displayEmailSection">Lessee</asp:LinkButton>
</asp:Panel>

The method to reference the panel is as follows:
public void displayEmailSection(object sender, EventArgs e)
    {
        LinkButton ButtonCommandArg = (LinkButton)sender;
        string TheCommand = ButtonCommandArg.CommandArgument.ToString();
        Panel thePanel;
        thePanel = Page.FindControl(TheCommand) as Panel;
        thePanel.Visible = true;
    }

When I run the code, it tells me the the panel has a null object reference.
Thanks, any help would be great.


text:
Q: Proximity Marketing API Currently I'm using AWS-S3 to create URL's for documents & shorten the URL's to suit the Eddystone format.
I'm using Kontakt beacons & use their UI to edit the beacons with shortened
URL's. This works fine, but the displayed link (as seen using the Physical
Web App) is too long & there is no link description.
I'm hoping to do all the above & more by using the Proximity Marketing API,
but the trouble is I'm an API Newbie & looking for some guidance.
I've created a Project & Browser Key & have a beacon, but not sure what to
do next (sorry).
I'm guessing I'll have to input the beacon details
somewhere together with the required URL & hopefully a link description.
Is there an idiots guide to doing this or what can you advise?

A: The way the Physical Web App and Chrome's Physical Web support work is:

*

*The app discovers Eddystone-URLs nearby.

*The app sends the URL to a Physical Web Service.

*The Physical Web Service fetches the web page from that URL (following all the redirects, e.g., those introduced by the link shorteners).

*The Physical Web Service extracts the title, description, icon, and linked data from the web page.

*The Physical Web Service returns the extracted data to the app.

*The app uses the metadata to show the URL as it sees fit.

In other words, the only way to control how a Physical Web URL is displayed in Physical Web App or Chrome for iOS/Android is to manipulate the page's meta tags. But if you're linking directly to non-HTML files, then you naturally can't do that.
The best workaround I can think of would be to link to an HTML page with a JavaScript redirect (so that it's not followed by the service) to the actual document. You can then manipulate the content of the HTML page so that it's shown by Physical-Web–enabled apps as you'd like it to be shown. And when the user taps on the link, it'll open the page, which will then redirect the user to the document, initiating the download.


text: Q: Render a sqaure in LWGL I am making a game using LWGL and when I wanted to render a square it failed. I have reverted back to a working version but, I still need to load a square. All the tutorials I watch are to new or do it a different way than me. For example, they a the Window class as their window while I use a long. Can someone help me render a square with LWGL stable build 13?


text:
Q: How many bytes would a string occupy, initialized for less letters I need to know how many Bytes would this array occupy:
char s[10] = "test";

Will it be 10 Bytes or 5 Bytes because of "test" + "\0" ?

A: Just to clear things out a bit
 char s[10] = "test";

here s will occupy 10 bytes, as you have explicitly supplied the size.
OTOH, a definition like
 char s[ ] = "test";

s will occupy 5 bytes, as the size of the array will be determined based on the supplied initializer (4 elements plus one null-terminator.)
In case of a char array, the second one is considered a better approach, as at times, it may save you from the trouble by forgetting to count the space for null-terminator while defining the size.
Consider the scenario,
 char arr[5] = "Hello";

here, arr will be of size 5 and is not null terminated. But if you use
 char arr[ ] = "Hello";

compiler will automatically determine the size including the null terminator. So, arr will be of size 6 and include the null-terminator.

A: In your question there are in fact two separate questions. The first one  corresponds to the title of the original question

How many bytes would a string occupy, initialized for less letters

and the second one is in the body of the original question

how many Bytes would this array occupy:

char s[10] = "test";

The answer to the first question sounds like the string occupies exactly 5 elements of the array. That is the string occupies the following elements of the array
s[0] = 't', s[1] = 'e', s[2] = 's', s[3] = 't', s[4] = '\0'

all other characters of the array in the range [5, 9] will be initialized by zero '\0'
And the answer to the second your question sounds like the array occupies exactly the size that equal to 10 * sizeof( char ) that is exactly 10 bytes because sizeof( char ) is always equal to 1.
If you would write instead
char s[] = "test";
      ^^

then the size of the array would be equal to the size of the string literal (including the terminating zero) that is to 5 characters.


text:
Q: How can I generate an array of float values of a given length in a given range and of a pre-defined mean value using Python I ran into an issue when trying to generate jittered interstimulus intervals for an fMRI project and I couldn't find any resources online to generate these times. For those that don't know, within fMRI research, we often use fixation crosses between stimuli as baseline measures and we need these to be of varying lengths so that the presentation is surprising, but of a reliable mean, so that we can predict the length of the task.
As such, how can I get Python to generate arrays of float values of a given length in a given range and of a pre-defined mean value? As a relatively new python users, I didn't find any accessible solutions, so I figured one out and wanted to share it.
EDIT: The purpose of this post is to share a solution to the above issue. I searched for awhile and didn't find any solutions that worked for me, so I wanted to post the question with the solution I worked out incase others stumble upon it. Michael Szczesny was nice enough to point me towards an alternative solution which is more sound. While perhaps fine for the very specific purpose of generating ISIs, it is not sound for generating arrays for more general purposes. I flagged this post as a duplicate, so you should be able to find the better solution through that.

A: I wanted to share my solution, should anyone else run into this issue and not find any publicly available solutions.
## Dependencies ----
import numpy as np
import random

## Conveniently modifiable variables ----
# Completely arbitrary; just choosing values to demonstate
seed = 101
ISI_n = 100
ISI_mean = 2.000
ISI_lower = 0.500
ISI_upper = 4.000

## Function -----
def generate_jitter(seed, ISI_n, ISI_mean, ISI_lower, ISI_upper):
    # A tracker to track which iteration we are currently on
    tracker = 1

    # A seed to be able to create the same simulation reliably
    random.seed(seed)

    # Creating an array to house the jitter values
    jitters = []

    # Iterate through this loop ISI_n times
    while tracker <= ISI_n:

        # If this is the first iteration
        if tracker == 1:

            # Add a random value with 3 digits that's between ISI_lower and ISI_upper to the array.
            jitters.append(round(random.uniform(ISI_lower, ISI_upper), 3))

        # If this is any other iteration
        if tracker > 1:

            # Calculate the value that would make the mean of array Jitters equal to ISI_mean
            balance = (ISI_mean * tracker) - sum(jitters)

            # Calculate how many iterations are left in this loop
            progress = ((ISI_n - tracker)/ISI_n)

            # Calculate an upper bound centered around the balance value, but not the balance value.
            # As the loop grows closer to the final iteration, this value will be closer to the balance value.
            upper = balance + ((ISI_upper - balance) * progress)

            # If on the off chance upper is greater than ISI_upper
            if upper > ISI_upper:

                # Make upper equivalent to ISI_upper
                upper = ISI_upper
            lower = balance - ((balance - ISI_lower) * progress)

            # If on the off chance upper is greater than ISI_upper
            if lower < ISI_lower:

                # Make upper equivalent to ISI_upper
                lower = ISI_lower

            # Then generate a new float between upper and lower
            jitters.append(round(random.uniform(lower, upper), 3))

        # Add 1 to the tracker in preparation for the next iteration
        tracker += 1

    # Randomly shuffle the array
    random.shuffle(jitters)

    return jitters

# Demonstrating that the function works using the values defined above.
array = generate_jitter(seed = seed,
                        ISI_n = ISI_n,
                        ISI_mean = ISI_mean,
                        ISI_lower = ISI_lower,
                        ISI_upper = ISI_upper)

print(np.mean(array))
print(np.min(array))
print(np.max(array))
print(len(array))

My output:
# Slightly off, but our MRI clock won't register
# 0.0000000000000002 seconds. This will get rounded to 2.000
# so close enough for my purposes
>>> print(np.mean(array))
1.9999999999999998
>>> print(np.min(array))
0.702
>>> print(np.max(array))
3.83
>>> print(len(array))
100
>>>


text:
Q: How to use .append on a jQuery .load() function I'm trying to append the data being called rather than replacing it but I'm not sure why .append isn't working.
      $('.incoming3').load('t3.html #test3').append;

A: Well first of all .append() is a function - you need to use parentheses after it, and supply it with a parameter telling it what to append. Second, you can't just change the way .load() works by chaining .append() onto the end of it.
Try this instead:
$.get("t3.html", function(data) {
    $('.incoming3').append($(data).filter("#test3"));
});

That is, use the $.get() method to retrieve the data, wrap the data in a jQuery object and use the .filter() method to extract the bit you need, and append that bit to your element.

A: $('.incoming3').append($('<div>').load('t3.html #test3'));

or
$.get('t3.html', function(data) {
    $('.incoming3').append($(data).find('#test3'));
});

A: load() method by design replaces the html of the selector. You will need to create your own filtering AJX method.
$.get( 't3.html', function(response){
   var contentDesired=$(response).find( '#test3')/* or filter instead of find if no body tag wrapping html*/
   $('.incoming3').append( contentDesired)

})

This is virtually identical to one solution I gave you on same situation in your last question for same issue


text:
Q: drupal webform - credit card resubmit on admin edit I have a client who has a drupal website installation. On the site there is a form that allows unauthorized/anonymous users to submit a request for some official data of which there is a charge.
The problem is when the admin goes in to the website and fills in the some additional fields (used for office processing) the credit card charged again.
Is there a way to provide a save button for admins that does NOT charge? or have it only charge once - if it fails on web then admins can run it via other means.

A: I'm not sure to exactly understand issue but you can change form with an hook_form_alter : https://api.drupal.org/api/drupal/modules%21system%21system.api.php/function/hook_form_alter/7.x
So, it will allow you to modify form before rendering and maybe delete credit card service callback with condition on current user logged.
Something like
function MYMODULENAME_form_alter(&$form, &$form_state, $form_id){
    global $user;
    if($form_id == 'my_credi_card_form_id' && $user->uid == 1){
         //superadmin or use user_has_role function for group of user with permissions
        // dump form structure to identify callback and after unset it from form
    }
}


text:
Q: How to clear variables in ipython? Sometimes I rerun a script within the same ipython session and I get bad surprises when variables haven't been cleared. How do I clear all variables?
And is it possible to force this somehow every time I invoke the magic command %run?

A: EDITED after @ErdemKAYA comment.
To erase a variable, use the magic command:
%reset_selective <regular_expression>

The variables that are erased from the namespace are the one matching the given <regular_expression>.
Therefore
%reset_selective -f a

will erase all the variables containing an a.
Instead, to erase only a and not aa:
In: a, aa = 1, 2
In: %reset_selective -f "^a$"
In: a  # raise NameError
In: aa  # returns 2

see as well %reset_selective? for more examples and https://regexone.com/ for a regex tutorial.
To erase all the variables in the namespace see:
%reset?

A: In iPython you can remove a single variable like this:
del x

A: The get_ipython().magic() method raises a DeprecationWarning in ipython 8.1. Here is the new version of Carl's answer
 from IPython import get_ipython
 get_ipython().run_line_magic('reset', '-sf')

Add these lines to a file you are editing. Then at the ipython command prompt you can type,
%run file_you_are_editing.py

A: %reset seems to clear defined variables.

A: I tried
%reset -f

and cleared all the variables and contents without prompt. -f does the force action on the given command without prompting for yes/no.
Wish this helps.. :)

A: Adding the following lines to a new script will clear all variables each time you rerun the script:
from IPython import get_ipython
get_ipython().magic('reset -sf')

To make life easy, you can add them to your default template.
In Spyder: Tools>Preferences>Editor>Edit template

A: Apart from the methods mentioned earlier. You can also use the command del to remove multiple variables
del variable1,variable2

A: An quit option in the Console Panel will also clear all variables in variable explorer
*** Note that you will be loosing all the code which you have run in Console Panel


text:
Q: How to download privat pastebin paste via curl (cmd/bat) Hey i want to download my private paste via a batch/cmd file with using curl as it is privat i have to login with my api dev key but this does not work output is some html code
I already tried but it did not worked i dont know why.
curl -s -o sdggsd.txt -d "api_dev_key=key" https://pastebin.com/raw/link
Edit : Now I also tried this but it says no url specified.
curl -d 'api_dev_key=key' -d 'api_user_name=name' -d 'api_user_password=pass' -o sdggsd.txt "https://pastebin.com/raw/url"

Edit : So this code works but it outputs in the file only html code :( not the code that is on the website
curl -o st.txt -d 'api_dev_key=key' -d 'api_user_name=user' -d 'api_user_password=pass' https://pastebin.com/raw/url

st.txt file result for command :
curl -o st.txt -d 'api_dev_key=key' -d 'api_user_name=user' -d 'api_user_password=pass' "https://pastebin.com/raw/url"

result in st.txt :
    <!DOCTYPE html>

    <meta name="viewport" content="width=device-width, initial-scale=0.75, maximum-scale=1.0, user-scalable=yes" />

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Pastebin.com - Bad Request (#400)</title>
    <link rel="shortcut icon" href="/favicon.ico" />
    <meta name="description" content="Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time." />
    <meta property="og:description" content="Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time." />
            <meta property="fb:app_id" content="231493360234820" />
    <meta property="og:title" content="Pastebin.com - Bad Request (#400)" />
    <meta property="og:type" content="article" />
    <meta property="og:url" content="https://pastebin.com/raw/url" />
    <meta property="og:image" content="https://pastebin.com/i/facebook.png" />
    <meta property="og:site_name" content="Pastebin" />
    <meta name="google-site-verification" content="jkUAIOE8owUXu8UXIhRLB9oHJsWBfOgJbZzncqHoF4A" />
    <link rel="canonical" href="https://pastebin.com/raw/url" />
        <meta name="csrf-param" content="_csrf-frontend">
<meta name="csrf-token" content="BBCH6PRTqsfFEJnQk2n_8j6Jfe7FUMIOP34snpj8SidSQe69sD_JiapZzZX5G8eHDucP24MfqHx7HXWt_pQhRQ==">

<link href="/assets/c80611c4/css/bootstrap.min.css" rel="stylesheet">
<link href="/assets/a25015e7/dist/bootstrap-tagsinput.css" rel="stylesheet">
<link href="/themes/pastebin/css/vendors.bundle.css?d9b75a0225d98a07f54f" rel="stylesheet">
<link href="/themes/pastebin/css/app.bundle.css?d9b75a0225d98a07f54f" rel="stylesheet">

<svg style="height: 0; width: 0; position: absolute; visibility: hidden" xmlns="http://www.w3.org/2000/svg">
    <symbol id="add" viewBox="0 0 1024 1024"><path fill="#ccc" d="M512 16C238 16 16 238 16 512s222 496 496 496 496-222 496-496S786 16 512 16z m288 552c0 13.2-10.8 24-24 24h-184v184c0 13.2-10.8 24-24 24h-112c-13.2 0-24-10.8-24-24v-184h-184c-13.2 0-24-10.8-24-24v-112c0-13.2 10.8-24 24-24h184v-184c0-13.2 10.8-24 24-24h112c13.2 0 24 10.8 24 24v184h184c13.2 0 24 10.8 24 24v112z"/></symbol>
    <symbol id="search" viewBox="0 0 512 512"><path fill="#ccc" d="M354.2,216c0-38.2-13-70.7-40-97.7c-27-27-59.6-40-97.7-40s-70.7,13-97.7,40s-40,59.6-40,97.7 s13,70.7,40,97.7s59.6,40,97.7,40s70.7-13,97.7-40C340.2,285.8,354.2,253.2,354.2,216z M511.5,472c0,10.2-3.7,19.5-12.1,27.9 c-8.4,8.4-16.8,12.1-27.9,12.1c-11.2,0-20.5-3.7-27.9-12.1L339.3,393.8c-37.2,26.1-78.2,38.2-122.9,38.2 c-29.8,0-57.7-5.6-83.8-16.8c-27-11.2-50.3-27-68.9-46.5s-34.4-42.8-46.5-68.9C6.1,272.8,0.5,244.8,0.5,216s5.6-57.7,16.8-83.8 c11.2-27,27-50.3,46.5-68.9s42.8-34.4,68.9-46.5C159.7,5.6,187.6,0,216.4,0s57.7,5.6,83.8,16.8c27,11.2,50.3,27,68.9,46.5 c18.6,19.5,34.4,42.8,46.5,68.9c11.2,27,16.8,54.9,16.8,83.8c0,44.7-13,85.6-38.2,122.9L499.4,444 C507.8,451.5,511.5,460.8,511.5,472z"/></g></symbol>
</svg>

                    Pastebin

                                        API
                    tools
                    faq

                    paste

                                            <form id="w0" class="search_form" action="https://pastebin.com/search" method="get">

<input type="text" id="q" class="search_input" name="q" maxlength="128" placeholder="Search...">

                            <button type="submit" class="search_btn"><svg class="icon search"><use xlink:href="#search"></use></svg></button>
                        </form>

                        Login
                        Sign up

Bad Request (#400)

            Unable to verify your data submission.

        Public Pastes

                BTC Wallet Credentials have been reset

                                            GetText |

                    3 min ago
                    | 0.24 KB

                Link crash

                                            Java |

                    22 min ago
                    | 2.37 KB

                Untitled

                                            Lua |

                    44 min ago
                    | 3.51 KB

                Untitled

                                            Python |

                    47 min ago
                    | 2.60 KB

                Dig

                                            Lua |

                    1 hour ago
                    | 2.28 KB

                bot.lua

                                            Lua |

                    1 hour ago
                    | 1.27 KB

                Quirk Command

                                            JavaScript |

                    1 hour ago
                    | 3.30 KB

                bot.lua

                                            Lua |

                    1 hour ago
                    | 1.25 KB

                create new paste  /
                                syntax languages  /
                archive  /
                faq  /
                tools  /
                night mode  /
                api  /
                scraping api  /
                news  /
                pro

                privacy statement  /
                cookies policy  /
                terms of serviceupdated  /
                security disclosure  /
                dmca  /
                report abuse  /
                contact

    By using Pastebin.com you agree to our cookies policy to enhance your experience.

    Site design & logo © 2023 Pastebin

            We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy.             OK, I Understand

                Not a member of Pastebin yet?

                Sign Up, it unlocks many cool features!

A: You need to curl the raw text, not the site. A raw paste (or github file) will be only the text, no tags.


text:
Q: Should all dict params in python decorated by asterisks def accept(**kwargs):
    pass

If I defined accept and I expect it be called by passing a param which is dict.  Are the asterisks necessary for all dict params?
What if I do things like:
def accept(dict):
    pass

dict = {...}
accept(dict)

Specifically speaking, I would like to implement a update method for a class, which keeps a dict as a container. Just like the dict.update method, it takes a dict as a param and modify the content of the container. In this specific case should I use the kwargs or not?

A: ** in function parameter collects all keyword arguments as a dictionary.
>>> def accept(**kwargs): # isinstance(kwargs, dict) == True
...     pass
...

Call using keyword arguments:
>>> accept(a=1, b=2)

Call using ** operator:
>>> d = {'a': 1, 'b': 2}
>>> accept(**d)
>>> accept(d)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: accept() takes exactly 0 arguments (1 given)

See Python tutorial - Keyword argument and Unpacking Argument Lists.
BTW, don't use dict as variable name. It shadows builtin function/type dict.

A: See f below. The function f has two parameters, a positional one called name and a keyword argument message. They are local variable in the frame of the function call.
When you do f("John", **{"foo": "123", "message": "Hello World"}), the function f will unpack the dictionary into local variable by its key/value pair. In the end you have three local varaibles:  name, foo=123, and message=Hello World.

The purpose of **kwargs, double asterisks is for uknown keyword arguments.
Contrast this:
def f(name, message=None):
    if message:
        return name + message
    return name

Here I am telling user if you ever want to call f, you can pass a keyword argument message. This is the only kwarg I will ever accept and expect to receive if there is such one. If you try f("John", foo="Hello world") you will get unexpected keyword argument.
**kwargs is useful if you don't know ahead of time what keyword arguments you want to receive (very common for dispatching to lower-level functions/methods), then you use it.
def f(name, message=None, **kwargs):
    if message:
        return name + message
    return name

In the second example, you can do f("John", **{"foo": "Hello Foo"}) while omitting message. You can also do f("John", **{"foo": "Hello Foo", "message": "Hello Message"}).

*

*Can I ignore it?

As you see yes you can ignore it. Here f("John", **{"foo": "Hello Foo", "message": "Hello Message"}) I still only use message and ignore everything else.
Don't use **kwargs unless you need to be careless about the inputs.

*

*What if my input is a dictionary?

If your function simply takes the dictionary and modifies the dictionary, NOT using individaul key, then just pass the dictionary. There is no reason to make a dictionary item into variables.
But here are two main usages of **kwargs.
Supposed I have a class and I want to create attributes on the fly. I can use setattr to set class attributes from input.
class Foo(object):
    def __init__(**kwargs):
        for key, value in kwargs.items():
            setattr(self, key, value)

If I do Foo(**{"a": 1, "b": 2}) I will get Foo.a and Foo.b at the end.
This is particularly useful when you have to deal with legacy code. However, there is a big security concern. Imagine you own a MongoDB instance and this is a container for writing into a database. Imagine this dict is a request form object from user. The user can shovel ANYTHING and you simply save it in the database like that? That's a security hole. Make sure you validate (use a loop).
The second common usage of kwargs is that you don't know things ahead of times which I have covered (it's actually sort of the first common usage anyway).

A: If you want to pass a dictionary as input to a function, you can simply do it like this
def my_function1(input_dict):
    print input_dict

d = {"Month": 1, "Year": 2}

my_function1(d)     # {'Month': 1, 'Year': 2}

This is straight forward. Lets see the **kwargs method. kwargs stands for keyword arguments. So, you need to actually pass the parameters as key-value pairs, like this
def my_function2(**kwargs):
    print kwargs

my_function2(Month = 1, Year = 2)

But if you have a dictionary and if you want to pass that as a parameter to my_function2, it can be done with unpacking, like this
my_function2(**d)


text:
Q: DNN PageLoadException with no stack trace We have a custom module on a dnn page that throws a Page_Load_Exception but does not include a stack trace in the EventLog*.  The exception occurs apparently before our module is loaded, and our module works fine in other environments.

*

*Is there a setting somewhere the disables or enables getting stack traces?

*Now, in development, if I force Page Load Exceptions, I do get a stack trace, but in trying to figure out why I looked at the DNN code and noticed this in PageBase.cs
protected override void OnError(EventArgs e)
    {
        base.OnError(e);
        Exception exc = Server.GetLastError();
        Logger.Fatal("An error has occurred while loading page.", exc);
From what I've read, there's evidently some cases in asp.net where Server.GetLastError() will return null.  A technique for avoiding this is to deal with Server.GetLastError() in global.asax and then stash it for later use by pages.  Do you think this could be a cause in DNN of us ultimately not getting a stack trace?

A: Just as one piece of information. The DNN log was not including the stack trace because the AddLog stored procedure was not updated. As one commentator wrote, you can check /portals/_default/Logs.  There you'll see a bunch of files and have exceptions for the DNN log.  In there was an exception for AddLog.  Once we determined the table structures matched the upgrade, all we had to do was apply the new stored procedure.


text:
Q: How to solve this design problem: Inheriting from class that is abstracted to a interface? I'm having a hard time to grasp a solution for the following problem.
I am decoupling the classes with their correspondent interface but I need to extend the class for a new change instead of changing the original implementation in order to be compliant with open close principle.
This the base class HttpRequest implementing IHttpRequest
public class HttpRequest : IHttpRequest
{
    public string RawUrl { get; protected set; }

    public HttpRequest(string rawUrl)
    {
        RawUrl = rawUrl;
    }

    public string GetJsonFromUrl(string url)
    {
        //
    }
}

public interface IHttpRequest
{
    string GetJsonFromUrl(string url);
}

and the extended class is UrlMetadataResolver:
public class UrlMetadataResolver : HttpRequest
{
    public UrlMetadataResolver(string rawUrl) : base(rawUrl)
    {
        //
    }
}

What should I do? should I created an interface for UrlMetadataResolver (IUrlMetadataResolver)?
If that's the case it becomes even more confusing.
Thanks

A: It is true that since you don't provide any description on what you want to accomplish, there can't be any complete or specific answer.
But here is a hint or two:
If you're already using the HttpRequest class then probably the best thing is not to change it; in order to be compliant with open close principle, as you said. So yes create a new class.
If the new fuctionality of UrlMetadataResolver class is indeed extending the functionality of the HttpRequest class; meaning it uses the methods of HttpRequest and some additional too, then yes, you should inherit from HttpRequest, to be able to use its methods, and add your new methods in the new class.
And in this case yes, you should create a new interface that inherits from IHttpRequest and extends it. The meaning of an interface is to allow a change in the way the things are implemented, without changing the way the things are done. I.e. you can later use another approach and implement the UrlMetadataResolver functionalities in another way, by another class. Using an interface will allow you to change only that, without changing anything in your business layer, in the references of the IUrlMetadataResolver interface.
Composition is a good practise too, as suggested, but makes more sense in cases where we want to inherit from more than one classes. C# and .NET clearly favors composition over inheritance (and they do well) by not allowing inheritance of more than one class.
If, on the other hand, the new functionality, doesn't extend, but rather overrides the functionality of HttpRequest, then the way to go is to mark the HttpRequest methods as virtual, inherit and override in UrlMetadataResolver.
You can assume of course that you can go both ways; override and extend the HttpRequest class.
You can always of course create a new class UrlMetadataResolver with no relation to the HttpRequest.
Hope I could help,
merry coding!

A: I recommend creating a base class that implements all methods the classes have in common:
public abstract class HttpBaseRequest : IHttpRequest
{
    protected HttpBaseRequest(string rawUrl)
    {
        RawUrl = rawUrl;
    }

    public string RawUrl{ get; protected set; }

    public string GetJsonFromUrl(string url)
    {
        return "";
    }
}

public class HttpDataRequest : HttpBaseRequest
{
    public HttpDataRequest(string rawUrl) : base(rawUrl) { }
}

public class UrlMetadataResolver : HttpBaseRequest
{
    public UrlMetadataResolver(string rawUrl) : base(rawUrl) { }
}

If required you can still create an interface IUrlMetadataResolver.


text:
Q: How do I pause the app completely when there is no activity? I use this -
 if (timeSinceLastClick > 60)
  {
            Time.timeScale = 0;
  }

But that doesn't freeze either the ar camera/ar tracking or audio. Besides the animation, everything else seems to keep running.
I'd like to pause the app completely so the users can save their batteries and avoid heating

A: If you want to save battery/avoid heating I'd recommend either cull as much as you can or lower the target framerate.
Settings TimeScale to 0 will affect Rigidbodies and all scripts that multiply their movements by Time.deltaTime (which is highly recommended to achieve framerate-independency). It still computes every frame, as often as possible. So see above.
If you have occlusion culling baked, you could move the camera to an area that doesn't point at any renderable objects. A dynamic cube in front of the cam will probably not work as it's not baked into Occlusion Culling. But you could disable the main Camera and render the pause-menu on a second camera that is UI only for example.


text:
Q: How to send an email with powershell How the heck do you send an email with powershell? I have the following code:
$Username = "test@yahoo.com"
$Password = "testpassword"

$SecurePassword = $Password | ConvertTo-SecureString -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential -ArgumentList $Username, $SecurePassword

$RcptTo = "somebody@mailserver.com"
$Subject = "Yahoo Test"
$Body = "This is a test message"
Send-MailMessage -From $Username -To $RcptTo -Subject $Subject -Body $Body -SmtpServer smtp.mail.yahoo.com -Port 587 -UseSsl -Credential $Credentials

But am receiving the following error:
Send-MailMessage : Unable to read data from the transport connection: net_io_connectionclosed.

A: You must set the security for the connection. Add this to the top of your script.
[Net.ServicePointManager]::SecurityProtocol = [Net.ServicePointManager]::SecurityProtocol -bor [Net.SecurityProtocolType]::Tls12

ServicePointManager.SecurityProtocol Property
Point of note:

Send-MailMessage is obsolete and no longer supported. Microsoft says
this cmdlet does not guarantee a secure connection to SMTP
servers.


text:
Q: Does multitail follow the inode or the file name by default? For logrotated files one usually uses tail -F instead of tail -f to follow the log file contents. Does multitail(1) automatically follow the name instead of the inode (which likely changes with the log rotation)?
I sifted through the documentation and also searched on the web, but wasn't able to come up with a conclusive answer.

Thanks to the accepted answer I found that the man page does mention the option I wanted, but uses the term "descriptor" instead of "inode". So this question and the answer should be the glue for the next person researching the topic.
-f Follow the following filename, not the descriptor.

--follow-all
  For all files after this switch: follow the following filename, not the descriptor.

A: According to the multitail manual:
There are a few other options not fitting elsewhere, these are:
-f  This makes MultiTail follow the file. In case the original file gets
    renamed and a new file is created with the original filename, MultiTail
    will start watching the file with the original filename (the one you
    entered).

To me, this implies that by default it follows by inode / file descriptor rather than filename.
A cursory reading of the source bears this out; in exec.c:79, the follow_filename var (set in cmdline.c:889 or ui.c:966) defines whether the follow-by-filename flag (-F, --follow=name, etc.) is passed to tail.


text:
Q: FileDownload Component of primefaces causes exception NullPointerException in report generation with JasperReports I have an application for reporting. When I deploy and run locally, it generates the report and it downloads perfectly, no problems. (Creates the file in the application reports and file download is done)
However, when I deployed the application on the company server, I tried to print the report and the exception occurred NullPointterException.
Here's the stack trace:
Aug 21, 2013 5:26:01 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [FacesServlet] in context with path [/WebMap] threw exception [javax.servlet.ServletException] with root cause
java.lang.NullPointerException
    at org.primefaces.component.filedownload.FileDownloadActionListener.processAction(FileDownloadActionListener.java:53)
    at javax.faces.event.ActionEvent.processListener(ActionEvent.java:84)
    at javax.faces.component.UIComponentBase.broadcast(UIComponentBase.java:773)
    at javax.faces.component.UICommand.broadcast(UICommand.java:296)
    at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:781)
    at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1246)
    at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:77)
    at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
    at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
    at javax.faces.webapp.FacesServlet.service(FacesServlet.java:310)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:305)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at web.web.filter.ConexaoHibernateFilter.doFilter(ConexaoHibernateFilter.java:31)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:344)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:110)
    at org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:84)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
    at org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:98)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
    at org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:95)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
    at org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:79)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
    at org.springframework.security.web.authentication.rememberme.RememberMeAuthenticationFilter.doFilter(RememberMeAuthenticationFilter.java:120)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
    at org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:55)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
    at org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:36)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
    at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:188)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
    at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:106)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
    at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:80)
    at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:356)
    at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:150)
    at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:237)
    at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:167)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:243)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:210)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:222)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:123)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:99)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:953)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:118)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1023)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:589)
    at org.apache.tomcat.util.net.AprEndpoint$SocketProcessor.run(AprEndpoint.java:1852)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at java.lang.Thread.run(Thread.java:722)

The code portion of this application is the one below:
Download Page
<?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <ui:composition template="/templates/interno.xhtml">
        <ui:define name="titulo">
            Módulo de Relatórios
        </ui:define>

        <ui:define name="corpo">

                        <h:form>
                             Para realizar o download do relatório, clique em uma das
                                opções de arquivo abaixo:

                            <h:messages id="excecoes"
                                style="list-style-type: decimal; font-size: 14px; padding-left: 5px;"
                                title="Erros de preenchimento encontrados" />

                            <h:commandLink title="Relatório em PDF">
                                <f:setPropertyActionListener target="#{relatorioBean.tipoRelatorio}"
                                    value="1" />

                                <h:graphicImage library="imagens" name="pdf.png" />
                                Arquivo PDF
                            </h:commandLink>

                        </h:form>

    </ui:define>
</ui:composition>

RelatorioBean
import java.util.HashMap;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.FacesContext;

import org.primefaces.model.StreamedContent;

import web.util.RelatorioUtil;
import web.util.UtilException;

@ManagedBean(name = "relatorioBean")
@RequestScoped
public class RelatorioBean {

    private StreamedContent arquivoRetorno;
    private int tipoRelatorio;

    public StreamedContent getArquivoRetorno() {
        FacesContext context = FacesContext.getCurrentInstance();
        String nomeRelatorioJasper = "relatorio";
        String nomeRelatorioSaida = "Relatório_torres_de_transmissão";
        RelatorioUtil relatorioUtil = new RelatorioUtil();
        HashMap parametrosRelatorio = null;

        try {
            this.arquivoRetorno = relatorioUtil.geraRelatorio(
                    parametrosRelatorio, nomeRelatorioJasper,
                    nomeRelatorioSaida, this.tipoRelatorio);
        } catch (UtilException e) {
            context.addMessage(null, new FacesMessage(e.getMessage()));
            return null;
        }
        return this.arquivoRetorno;
    }

    public void setArquivoRetorno(StreamedContent arquivoRetorno) {
        this.arquivoRetorno = arquivoRetorno;
    }

    public int getTipoRelatorio() {
        return tipoRelatorio;
    }

    public void setTipoRelatorio(int tipoRelatorio) {
        this.tipoRelatorio = tipoRelatorio;
    }

}

RelatorioUtil
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.HashMap;

import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRExporter;
import net.sf.jasperreports.engine.JRExporterParameter;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.export.JRPdfExporter;

import net.sf.jasperreports.engine.util.JRLoader;

import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;

import web.util.UtilException;

public class RelatorioUtil {

    public static final int RELATORIO_PDF = 1;

    public StreamedContent geraRelatorio(HashMap parametrosRelatorio,
            String nomeRelatorioJasper, String nomeRelatorioSaida,
            int tipoRelatorio) throws UtilException {
        StreamedContent arquivoRetorno = null;

        try {
            FacesContext context = FacesContext.getCurrentInstance();
            Connection conexao = this.getConexao();
            String caminhoRelatorio = context.getExternalContext().getRealPath(
                    "relatorios");

            String caminhoArquivoJasper = caminhoRelatorio + File.separator
                    + "relatorioTorres" + ".jasper";

            String caminhoArquivoRelatorio = null;

            JasperReport relatorioJasper = (JasperReport) JRLoader
                    .loadObject(caminhoArquivoJasper);
            JasperPrint impressoraJasper = JasperFillManager.fillReport(
                    relatorioJasper, parametrosRelatorio, conexao);
            JRExporter tipoArquivoExportado = null;
            String extensaoArquivoExportado = "";
            File arquivoGerado = null;

            switch (tipoRelatorio) {
            case RelatorioUtil.RELATORIO_PDF:
                tipoArquivoExportado = new JRPdfExporter();
                extensaoArquivoExportado = "pdf";
                break;
            default:
                tipoArquivoExportado = new JRPdfExporter();
                extensaoArquivoExportado = "pdf";
                break;
            }
            caminhoArquivoRelatorio = caminhoRelatorio + File.separator
                    + nomeRelatorioSaida + "." + extensaoArquivoExportado;
            arquivoGerado = new java.io.File(caminhoArquivoRelatorio);
            tipoArquivoExportado.setParameter(JRExporterParameter.JASPER_PRINT,
                    impressoraJasper);
            tipoArquivoExportado.setParameter(JRExporterParameter.OUTPUT_FILE,
                    arquivoGerado);
            tipoArquivoExportado.exportReport();
            arquivoGerado.deleteOnExit();

            InputStream conteudoRelatorio = new FileInputStream(arquivoGerado);
            arquivoRetorno = new DefaultStreamedContent(conteudoRelatorio,
                    "application/" + extensaoArquivoExportado,
                    nomeRelatorioSaida + "." + extensaoArquivoExportado);
        } catch (JRException e) {
            throw new UtilException("Não foi possível gerar o relatório.", e);
        } catch (FileNotFoundException e) {
            throw new UtilException("Arquivo do relatório não encontrado.", e);
        }
        return arquivoRetorno;
    }

    private Connection getConexao() throws UtilException {
        java.sql.Connection conexao = null;
        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext
                    .lookup("java:/comp/env/");
            javax.sql.DataSource ds = (javax.sql.DataSource) envContext
                    .lookup("jdbc/WebConection");
            conexao = (java.sql.Connection) ds.getConnection();
        } catch (NamingException e) {
            throw new UtilException(
                    "Não foi possível encontrar o nome da conexão do banco.", e);
        } catch (SQLException e) {
            throw new UtilException("Ocorreu um erro de SQL.", e);
        }
        return conexao;
    }
}

Can anyone help me to solve this error? Why this locally generating the file and performing the download, but this problem occurs on the server?

A: Based on PrimeFaces 2.1 source code, a NPE on line 53 of FileDownloadActionListener suggests that #{relatorioBean.arquivoRetorno} actually returned null. Let's look there:
} catch (UtilException e) {
    context.addMessage(null, new FacesMessage(e.getMessage()));
    return null;
}

It look like that it's returning null when an UtilException is been thrown. That adding of faces message is by the way completely pointless on a file download request. It won't appear anywhere. You'd better print/log the stack trace
} catch (UtilException e) {
    e.printStackTrace();
    return null;
}

or, better, just remove that whole try-catch and throw that exception directly.
public StreamedContent getArquivoRetorno() throws UtilException {
    // ...
}

This way you'll face the real exception instead of a NullPointerException which is hiding the real problem.

A: After a long time without looking at stackoverflow, I realized that I needed to put the solution to this problem, which occurred a long time ago. So here it is:
In this case I made the report template based on a database table structure, which had a nomenclature pattern.
When I took the code to the server, there was a database table structure, which had a different naming pattern.
In this way, the report was not generated and could not be downloaded, generating NullPointerException.
After noticing that there were minimal changes to the database table structure of the server, I had to redo the report template with iReport Designer, based on the new table structure, which followed a different naming pattern than the previous table structure.
So when I refactored the template based on the new structure, the report generation with JasperReports returned perfectly.


text:
Q: Ways of verifying a phone number Hi im working on a phone number based android app,
Im currently using google firebase.
Google firebase is pretty expensive when it comes to phone authentication,
I was thinking if there are any other ways to authenticate a phone number.
Programmable sms like twilio is fairly  cheaper but still pretty expensive for my budget.
Is it possible to use voip to auth a phone number?
Are there any other alternatives?

A: Using twilio is right option for limited number of sms for your purpose, as for voip they all depend on SMS gateways, and to have gateway which may be cheaper but require massive sms, as they are more expensive.