text:
Q: How get HttpsStatus with Java WebClient I only got http/https status with web client.
I need to call in my Spring-boot java application other rest api , and some don't return anything , only status
so i want something like this
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;
import java.time.Duration;

@Service
public class api {

    private HttpStatus exist(String username,User usr){
        localApiClient
                .head()
                .uri("/users/"+username )
                .bodyValue(usr)
                .exchangeToMono(response -> {
                        return response.statusCode();
                    }
                })
                .block(REQUEST_TIMEOUT);
    }
}

I find  solution with exchange but it's now deprecated


text:
Q: Null-Valued Expression Error in Powershell I am trying to uninstall a Program via Power Shell but I am getting an error "You cannot call a method on a null valued expression.
PS C:\Users\user> $App = Get-WmiObject -Class Win32_Product | Where-Object{$_.Name -eq "CVF_x64"}
PS C:\Users\user> $App.Uninstall()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $App.Uninstall()
+ ~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

The program is in Programs and Features on control panel, see attached picture below.
List of Apps on Control Panel
Powershell List of Apps
CVF Doesn't show up in Powershell for some reason

A: looks like your query does not find anything -> empty variable?
$x = $null
$x.uninstall()
result: You cannot call a method on a null-valued expression.

btw. wmi is a thing of the past, use the cim cmdlets, and do the filtering one step earlier:
$name = "MyApp"
get-ciminstance -query "select * from win32_product where name = '$name'"

To identify what the value of the variable name must be simply output this beforehand and identify the exact string:
(get-ciminstance -query "select * from win32_product").name

You could also check the registry:
HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\Uninstall
Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\*" -Name DisplayName,DisplayVersion,InstallSource,Publisher,UninstallString

Execute the command in the attribute UninStallString...

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there a better way i can handle my Generic BaseClass in inheriting classes? I have problems with the usage and understanding of Generics. I've worked with generics before, but now I get to a point where I can't get any further
Here is my basic class which should be extended by other classes:
public class BaseFiller<T> {

private WorkBook workBook;
private List<T> act_Bwa;
private List<T> act_Balance;
private List<T> p_l_v_e_L;

public BaseFiller(WorkBook workBook,
                  List<T> act_Bwa,
                  List<T> act_Balance,
                  List<T> p_l_v_e_L) {
    this.workBook = workBook;
    this.act_Bwa = act_Bwa;
    this.act_Balance = act_Balance;
    this.p_l_v_e_L = p_l_v_e_L;
}

protected static <T> Predicate<T> distinctByProperty(Function<? super T, ?> keyExtractor) {
    Map<Object, Boolean> seen = new ConcurrentHashMap<>();
    return t -> seen.putIfAbsent(keyExtractor.apply(t), Boolean.TRUE) == null;
}

protected static <T> Map<Integer, String> mapListToMap(Collection<? extends T> entityList, Function<? super T, Integer> intProperty,
                                                           Function<? super T, String> stringProperty) {
    return entityList.stream()
            .collect(Collectors.toMap(intProperty, stringProperty));
}

 //Getter & Setter

 }

The following class extends the base class:
public class FinanceBalanceFiller<T> extends BaseFiller<T> {

.
.
.

public FinanceBalanceFiller(WorkBook workBook, List<T> act_Bwa,
                            List<T> act_Balance,
                            List<T> p_l_v_e_L) {
    super(workBook, act_Bwa, act_Balance, p_l_v_e_L);
}

public Map<Integer, String> makeMapFromAllLists() {
    List<ResultlinevaluesEntity> res = new ArrayList<>();
    for (List<ResultlinevaluesEntity> list : getAct_Bwa()) {
        res.addAll(list);
    }

    //removes all duplicates from List by DbNr
    List<ResultlinevaluesEntity> resWithoutDuplicates = res.stream()
            .filter(distinctByProperty(ResultlinevaluesEntity::getDb_nr))
            .collect(Collectors.toList());

    //creates HashMap (Key = DbNr, Value = name)
    return mapListToHashMap(resWithoutDuplicates, ResultlinevaluesEntity::getDb_nr,
            ResultlinevaluesEntity::getName);
}

In the method makeMapFromAllLists() I have problems in my For loop. It spits out a bug that the types are not compatible with each other.

Error:(116, 68) java: incompatible types: T cannot be converted to
  java.util.List

I understand that, and I changed it that way:
    List<T> res = new ArrayList<>();
    for (List<T> list : getAct_Bwa()) {
        res.addAll(list);
    }

But that doesn't work either, because the types don't fit here either. Furthermore I get problems with the Methdode distinctByProperty from the base class. Here the compiler says:

Non-static method cannot be referenced from a static context

In the meantime I am totally confused and I can't get any further.
So, my goal is that all the methods in the method makeMapFromAllLists() will not only serve the ListType "ResultLineValuesEntity" but also other types.
Can somebody help me and show me how to deal with generics at this point?

A: It is the usage of addAll instead of add, but simplifications exist:
List<ResultlinevaluesEntity> res = new ArrayList<>();
for (List<ResultlinevaluesEntity> actBwa : getAct_Bwa()) {
    res.add(actBwa);
}

List<ResultlinevaluesEntity> res = new ArrayList<>();
res.addAll(getAct_Bwa());

List<ResultlinevaluesEntity> res = new ArrayList<>(getAct_Bwa());

After edited question: (not wanting the type parameter T)
There is a (sometimes unavoidable) (anti-)pattern of parallel class hierarchies
If you have an item / entity base class ItemBase.
class ItemBase
class ItemA extends ItemBase
class ItemB extends ItemBase

And a container base class ContainerBase
class ContainerBase<T extends ItemBase>
    List<T> items
    List<T> getItems();

class ContainerA extends ContainerBase<ItemA>
class ContainerB extends ContainerBase<ItemB>

This is a good way to have type-safe classes with a distinction between List<ItemA> and List<ItemB>. Otherwise you could have just List<ItemBase>.
Best would be not to need ContainerA and ContainerB.
You could also do (if you do not want a parameter):
class ContainerBase
    List<ItemBase> items;
    public List<ItemBase> getItems();

class ContainerA extends ContainerBase
    @Override
    public List<ItemA> getItems() {
        return items.stream().map(ItemA.class::cast).collect(Collectors.toList());
    }

class ContainerB extends ContainerBase
    @Override
    public List<ItemB> getItems() {
        return items.stream().map(ItemB.class::cast).collect(Collectors.toList());
    }


text:
Q: Negative Testing for PayPal using Sandbox with VB.NET - how to simulate different scenarios? I have a website written in VB.NET that implements PayPal for payments. This is all working fine for successful payments, but I need to be able to simulate scenarios of a failed transaction, pending transaction, etc.
I have read the documentation, which starts on page 47. I enabled Negative Testing in a business account that I created in a Sandbox, but I am not getting desired results.
To simulate an error, as specified in the documentation, I'm passing an error code to Token, which is then used in a request to DoExpressCheckoutPayment - code below - but instead of this raising the error 10417, the response says Invalid Token:
Dim oldToken As String
With RequestDetails
    oldToken = .Token
    .Token = "10417"
End With

Dim request As New DoExpressCheckoutPaymentRequestType
request.DoExpressCheckoutPaymentRequestDetails = RequestDetails

Dim response As DoExpressCheckoutPaymentResponseType
response = DirectCast(caller.Call("DoExpressCheckoutPayment", request),
    DoExpressCheckoutPaymentResponseType)

Questions:

*

*What am I doing wrong in the code above so that I can't trigger a correct error?

*How do I simulate a response where the status is Pending, Processed, Failed, etc.?

A: I was testing this about a week ago and was receiving the same problem, now, I no longer receive an error:
API Request:
METHOD=DoExpressCheckoutPayment
VERSION=82
token=10755
PayerID=GNT5WLV6WKLYW
PAYMENTACTION=Sale
AMT=456
PAYMENTREQUEST_0_AMT=458
PAYMENTREQUEST_0_ITEMAMT=458.00
PAYMENTREQUEST_0_SHIPPINGAMT=20.00
PAYMENTREQUEST_0_TAXAMT=46.20
PAYMENTREQUEST_0_CURRENCYCODE=USD
PAYMENTREQUEST_0_DESC=test EC payment
L_PAYMENTREQUEST_0_NAME0=Books
L_PAYMENTREQUEST_0_AMT0=154.00
L_PAYMENTREQUEST_0_NUMBER0=ABC123
L_PAYMENTREQUEST_0_QTY0=2
L_PAYMENTREQUEST_0_NAME1=CDs
L_PAYMENTREQUEST_0_AMT1=50.00
L_PAYMENTREQUEST_0_NUMBER1=BY-Z4736
L_PAYMENTREQUEST_0_QTY1=3

API Response:
TIMESTAMP=2011-09-27T20:39:57Z
CORRELATIONID=13126abeb4615
ACK=Failure
VERSION=82
BUILD=2133933
L_ERRORCODE0=10755
L_SHORTMESSAGE0=Unsupported Currency.
L_LONGMESSAGE0=Currency is not supported
L_SEVERITYCODE0=Error

I did find an article on x.com that deals with this issue as well.


text:
Q: Advice in making a color picker code for a certain function I have a code for picking a few colors using <button> for html. Is there any way to turn this into color picker? I don't know how to get the value from the color picker to be used in a javascript function. Can anyone help me? Here are the codes that I have right now.
html

        <button  class="black" id="#000000"> </button>
        <button  class="white" id = '#FFFFFF'> </button>
        <button  class="blue" id = '#0000FF'> </button>
        <button  class="red" id = '#FF0000'> </button>
        <button  class="yellow" id = '#FFFF00'> </button>
        <button  class="green" id = '#008000'> </button>
        <button  class="purple" id = '#800080'> </button>

        <input type="hidden" id="color_value_form">

and here is the function in the javascript file.
$('#colors button').on('click', function(){
        tmp_ctx.strokeStyle = $(this).attr('id');
        tmp_ctx.fillStyle = tmp_ctx.strokeStyle;
        console.log(tmp_ctx.strokeStyle);

        drawBrush();
    })

A: Not sure what exactly you are trying to accomplish, but here is something to start you off.

$('#colors button').on('click', function(){
 document.body.style.background = $(this).data('color');
});

 <button class="black" data-color="#000000">black</button>
 <button class="white" data-color='#FFFFFF'>white </button>
 <button class="blue" data-color='#0000FF'>blue</button>
 <button class="red" data-color='#FF0000'>red</button>
 <button class="yellow" data-color='#FFFF00'>yellow </button>
 <button class="green" data-color='#008000'> green</button>
 <button class="purple" data-color='#800080'>purple </button>

A: html5 has colorpicker as well
 <input id="html5colorpicker" type="color">

in js:
$("#html5colorpicker").value //is a string like "#000000"


text:
Q: C# issue using "Or" I am trying to say here if userinput = 1 or 2 display the message "you won a new car", but it is not working.
The error says

"operator || cannot be applied to operands of type and string".

I have been doing C# for only 2 days.
namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(" 1 2 or 3");
            String message = Console.ReadLine();
            string userinput = "";
            if (userinput == "1" || "2")
                message = "you won a new car";

A: Your last line needs to be changed to:
if (userinput == "1" || userinput == "2")
    message = "you won a new car";

Each part of the statement separated by the "OR" operator needs to be able to evaluate to true or false.

A: Doesn't work like that I'm afraid! Use:
if(userinput == "1" || userinput == "2")

The reason for this is that the if statement is expecting a true or false result. With a boolean operator (||), both sides must evaluate to either true or false. In this case, userinput == "1" will evaluate to true if userinput is 1, otherwise it will be false. The standalone "2" doesn't evaluate to true or false, it evaluates to "2".

A: You need
if(userinput == "1" || userinput == "2")

The trick is that or says one binary condition OR the other must be true for true. It is boolean logic, not the english or for lists.

A: Subsequently you could do something like this:
message = userinput != 3 ? "you won a new car" : "you lost a new car"

Which is a conditional operator expression.https://msdn.microsoft.com/en-us/library/ty67wk28.aspx

A: you can also use Array.IndexOf if you have multiple values.
ex. if you have 10 values that you want to compare by using OR,you can just use Array.IndexOf to shorten the code..
string[] array= new string[2];
array[0] = "1";
array[1] = "2";

if( Array.IndexOf(array, userInput) != -1) //-1 means it doesn't exist
{
   message = "you won a new car";
}


text:
Q: How often are Space Marine chapters deployed? We know that the Imperial Guard is the meat shield of the Imperium and the main force. But how often are the chapters called, them being the elite of the Imperium. By deployment I mean from space marine squads to terminators and even dreadnoughts, knights, titans.

A: The books detail everything from a single marine being deployed to several companies to the whole chapters.
Single marine - Iron snakes book
a few squads - All Ragnar books and countles others
A few companies - Armageddon war event that happened a few years back had multiple chapters send everything they had to stem the tide.
the entire chapter - tyranid invasion of a Chapter home world would qualify involving the entire chapter and all its allies. ( Ultramar was attacked in this way and almost destroyed )
It depends upon the threat. It also depends if it is a Chapter world that they are sworn to protect. It also depends if they have men to spare.
In the grim future there is only war. In war there is no rest for the Space Marines. They are constantly going from a hot zone to a hot zone. The  only time they are "resting" is when the company numbers and materiel drop so low that they HAVE to return to their staging point or home world to resupply and rearm.
To answer your question they are always out there. Space Marines are honour bound to help if they receive an astropatic call for help. Problem is that they receive so many all the time, they have to pick and prioritise.
An Allied world of the chapter would get priority over a small colony.
A forge world would get priority over a hive world. (men you can replace pretty fast, machines and factories not so much )


text:
Q: UIScrollView not loading/updating properly Im having problem with my UISCrollView, UIScrollVIew is in my View2Controller, my UIScrollView has thumbnail of images, which I imported from my ImagePicker picked images(multiple/single images). I have put my [self createScrollView]; in viewDidAppear, So at my first load of the view only the UIScrollView, obviously because I havent picked images yet. So after I picked its not updating in my view. But my images.count are updating in the my debugger. It's not updating in View, but when I go to another ViewController then return again to View2Controller, it loads the images in my UIScrollView,then when I add again images it's not updating. Why is it like that?.
- (void)addImage:(UIImage *)image {
    [_images addObject:image];
    [_thumbs addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
}

- (void) createScrollView {

    [scrollView setNeedsDisplay];
    int row = 0;
    int column = 0;
    for(int i = 0; i < _thumbs.count; ++i) {

        UIImage *thumb = [_thumbs objectAtIndex:i];
        UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.frame = CGRectMake(column*60+10, row*60+10, 60, 75);
        [button setImage:thumb forState:UIControlStateNormal];
        [button addTarget:self
                   action:@selector(buttonClicked:)
         forControlEvents:UIControlEventTouchUpInside];
        button.tag = i;

        [scrollView addSubview:button];

        if (column == 4) {
            column = 0;
            row++;
        } else {
            column++;
        }

    }
   [scrollView setContentSize:CGSizeMake(300, (row+1) * 60 + 10)];
}

- (void)viewDidAppear:(BOOL)animated
{
    [self createScrollView];
}

- (void)viewDidLoad
{
     [super viewDidLoad];
        self.slotBg = [[UIView alloc] initWithFrame:CGRectMake(43, 370, 310, 143)];
        CAGradientLayer *gradient = [CAGradientLayer layer];
        gradient.frame = self.slotBg.bounds;
        gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor grayColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
        [self.slotBg.layer insertSublayer:gradient atIndex:0];
        [self.view addSubview:self.slotBg];

        self.scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0.0f,0.0f,300.0f,130.0f)];
        [slotBg addSubview:self.scrollView];
            for(int i = 0; i <= 100; i++)
            {
                NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
                NSString *documentsDir = [paths objectAtIndex:0];

                NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"oneSlotImages%d.png", i]];
                NSLog(@"savedImagePath=%@",savedImagePath);
                if([[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]){
                    [self addImage:[UIImage imageWithContentsOfFile:savedImagePath]];
                    NSLog(@"file exists");
                }
            }
            NSLog(@"Count : %d", [_images count]);
}

EDIT: (In this part, the image can't be deleted from the view. But in my NSDocumentDirectory it is deleted, )
- (IBAction)buttonClicked:(id)sender {

        _clickedButton = (UIButton *)sender;
        UIAlertView *saveMessage = [[UIAlertView alloc] initWithTitle:@""
                                                              message:@"DELETE IMAGE?"
                                                             delegate:self
                                                    cancelButtonTitle:@"NO"
                                                    otherButtonTitles:@"YES", nil];
        [saveMessage show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    NSString *title = [alertView buttonTitleAtIndex:buttonIndex];

    if([title isEqualToString:@"YES"]) {
        NSLog(@"YES was selected.");
        UIButton *button = _clickedButton1;
        [button removeFromSuperview];
        [_images1 objectAtIndex:button.tag];
        [_images1 removeObjectAtIndex:button.tag];

        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"firstSlotImages%lu.png", button.tag]];
        [fileManager removeItemAtPath: fullPath error:NULL];
        NSLog(@"image removed");
    }

A: viewDidAppear: is only called once you go to a view. So when you are 'adding' the images you are only adding them to the _images array, they are not displayed because you are not adding them to the screen. They are displayed when you leave the view and come back because viewDidAppear: is called again.
To fix this, use addImage: to also add it to the current view.
- (void)addImage:(UIImage *)image {
    int row = ?;
    int column = ?;
    [_images addObject:image];
    [_thumbs addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
    UIImage *thumb = [_thumbs objectAtIndex:_thumbs.count-1];
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(column*60+10, row*60+10, 60, 75);
    [button setImage:thumb
            forState:UIControlStateNormal];
    [button addTarget:self
               action:@selector(buttonClicked:)
     forControlEvents:UIControlEventTouchUpInside];
    button.tag = _thumbs.count-1;
    [scrollView addSubview:button];
}

Only problem of course is how to determine the placement, aka column and row. You can do this by getting the last thumb's frame and figuring out where to place it according to screen bounds.
Another Fix
- (void)addImage:(UIImage *)image {
    [_images addObject:image];
    [_thumbs addObject:[image imageByScalingAndCroppingForSize:CGSizeMake(60, 60)]];
    [self createScrollView];
}

A: You need to call createScrollView after you have updated your array of images. Maybe try moving [self createScrollView]; to the end of your viewDidLoad method? Either way, you need to call createScrollView after you have added all of your images.


text:
Q: How to fetch images by their uid's Swift Firebase? I am trying to show all images that the current user posts. As you can see in the picture in a table view, every time the current user post an image it automatically creates a unique id for the image under the current user information.

In this images, You will see that when the users post an image it create a node called media for the image with their children.

Here's my code:
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "CellMe", for: indexPath) as! MyPosttTableViewCell

    FIRDatabase.database().reference().child("users").child(FIRAuth.auth()!.currentUser!.uid).observeSingleEvent(of: .value, with: { (snapshot) in
    // check if user has photo
    if snapshot.hasChild("media") != nil{
        print("found it")

     //set image locatin
    let filePath = "\(FIRAuth.auth()!.currentUser!.uid)/\("media")"

    FIRStorage.storage().reference().child(filePath).data(withMaxSize: 10*1024*1024, completion: { (data, error) in

    let userPhoto = UIImage(data: data!)
    cell.Myimages.image = userPhoto

    })

    }
    else {
        print("nil")
        }
        })

        return cell

    }}

A: The media in your users node is stored as a NSDictionary, not as a String. You will have to loop through the media node to get the paths of all your files. You can do something like
//Create reference to media directly instead
FIRDatabase.database().reference().child("users").child(FIRAuth.auth()!.currentUser!.uid).child("media").observeSingleEvent(of: .value, with: { (snapshot) in
  if let media = snapshot.value as? NSDictionary {

    //Loop thorugh all the entries in your media node to get all the media paths
    for (_, value) in media {
      FIRStorage.storage().reference().child("media").child(value as! String)

      //get the file now that you have the reference
    }
  }
})

A: If you want to add a image to a specific ID THEN upload the image to the firebase storage get the image.downloadurl in absolute string and add this value to the key "image" to your object and then post the object to the firebase database.


text:
Q: How did the Doctor escape being stranded in space in the original script for "Four to Doomsday"? This question is based on some facts I learned from Peter Davison, who played the Fifth Doctor, at an American Doctor Who convention about thirty years ago.  Among the things Davison told the audience was that his second Doctor Who story, "Four to Doomsday" was his least favorite.  (His favorite, for comparison, was his last story, "The Caves of Androzani.")  One of the reasons he said that he disliked "Four to Doomsday" was that it used a script that was really written for Tom Baker's Fourth Doctor.  (This was apparently a problem, in varying degrees, with several Davison's early stories.  Many of the scripts in his first season were commissioned before he was cast.  But with "Four to Doomsday," which was actually the first Fifth Doctor story to be filmed, the problem was the most severe.)
However, "Four to Doomsday" also includes one of the Fifth Doctor's most iconic scenes.  Floating free is space, between the evil Monarch's ship and the TARDIS, the Doctor digs a cricket ball out of his pocket and bounces it off the Monarch's vessel.  Catching it again on the rebound, the Doctor is propelled out to the TARDIS.  The episode can be seen here at archive.org; the ball scene is at about the 18:00 mark.
This scene, with the cricket ball, was one of the most memorable with Davison's Doctor.  At the convention, Davison answered several questions about how it was shot, and he acknowledged that it was the best part of the whole weak story.  However, if the script was originally prepared with Tom Baker's Doctor in mind, how did this scene originally play out?  Is there any information about how the action would have worked out without the Fifth Doctor's cricket angle?

A: This question could only be authoritatively answered by a copy of the original script written for the Fourth Doctor. According to the TARDIS Data Core website, the novelisation of this story makes some changes in line with the "early scripts" but whether or not this refers to the very first script written for Four, or simply early drafts of the revision for Five is not clear.
In the absence of the original script to answer the question conclusively, I thought I would point out a couple of things as a sort of frame-challenge.
Firstly, that Davison apparently had some input into his Doctor's cricketing costume. The production team had "sporting attire" in mind but this was the actor's preference, therefore if the cricket ball plotline was written in exclusively to fit the new Doctor's image it may not have even appeared in the earliest revisions for Davison.
However, the cricket ball features very heavily throughout the episode, not just in the scene you refer to. The Doctor is seen playing with it in number of scenes, discusses his bowling technique, and even uses it to distract the monopticon. Were all of these scenes written into the script just to fit the Fifth Doctor's image? Or, is it possible that the original script for Tom Baker's Doctor also contained a cricket ball? After all, it would not be the first time cricket was written into Doctor Who - Douglas Adams' unused script featuring the Krikkitmen was submitted in 1976, 3 years into Baker's run.
Doctor Who stories have sometimes been accused of relying on deus ex machina - a contrived, unexpected solution to a character's inescapable problem. Including the cricket ball throughout the story establishes it as a plot device and so it does not seem contrived when it is used in the final scene to save the day. Although all the scenes could have been written in as a revision for Five it does seem a lot of script revision just for that one scene. Plus, it wouldn't really have been quite so necessary to repeatedly establish the cricket ball as a plot device given that the Fifth Doctor is dressed as a cricketer. He likes cricket, he carries a cricket ball - what is so unexpected about that? It would have been no more deus ex machina than him pulling out the sonic screwdriver and saving the day. I find it more likely that the writer would have worked so hard to establish the cricket ball for a Doctor who was not so obviously into the sport.
So unless a script can prove otherwise I suggest that it is possible the cricket ball was always part of the original script and not necessarily part of the adaption for Davison. If it did already have the cricket element in the script it may explain why this particular story was selected to be filmed as Davison's first appearance on camera.


text:
Q: Django Rest Framework - Filter by relationship hyperlink I hope you are well.
This is my first personal project with DRF and I had the following problem.
I have two models:
class Area(models.Model):
    name = models.CharField(max_length=100)
    ...

and
class SubArea(models.Model):
    area = models.ForeignKey("Area", on_delete=models.CASCADE, verbose_name='Area relacionada',
    related_name='subareas')
    name = models.CharField(max_length=100)
    ...

I was able to do something similar to what I need using HyperlinkedRelatedField
class SubareaSerializer(serializers.ModelSerializer):
    contents = ContentSerializer(many=True, read_only=True)

    quizzes = QuizSerializerAux(many=True, read_only=True)
    class Meta:
        model = SubArea
        fields = ['id', 'name', 'description', 'quizzes', 'contents']

class AreaSerializer(serializers.HyperlinkedModelSerializer):

    subareas = serializers.HyperlinkedRelatedField(
        many=True,
        read_only=True,
        view_name='subarea-detail',
        )
    class Meta:
        model = Area
        fields = ['url','id', 'name', 'description', 'subareas',]

But this is what I get using the endpoint api/area/:
{
    "url": "http://127.0.0.1:8000/rest-auth/quiz/area/1/",
    "id": 1,
    "name": "Area 1 de teste",
    "description": "Area 1 de teste - descrição",
    "subareas": [
        "http://127.0.0.1:8000/rest-auth/quiz/subarea/1/",
        "http://127.0.0.1:8000/rest-auth/quiz/subarea/2/"
    ]
},

I get a list with several links to Subareas, however I need only 1 link that lists all Subareas related to this Area, for example:
/api/area/1/subarea
endpoint that would list all subareas in area id = 1
{
    "url": "http://127.0.0.1:8000/rest-auth/quiz/area/1/",
    "id": 1,
    "name": "Area 1 de teste",
    "description": "Area 1 de teste - descrição",
    "subareas": [
        "http://127.0.0.1:8000/rest-auth/quiz/area/1/subarea"
    ]
},

how can i do this using the DRF?
these are my views.py:
class AreaViewSet(viewsets.ModelViewSet):
    queryset = Area.objects.all()
    serializer_class = AreaSerializer

class SubareaViewSet(viewsets.ModelViewSet):
    queryset = SubArea.objects.all()
    serializer_class = SubareaSerializer

these are my urls.py
router_quiz = routers.DefaultRouter()
router_quiz.register(r'area', AreaViewSet)
router_quiz.register(r'subarea', SubareaViewSet)
...
path('rest-auth/quiz/', include(router_quiz.urls)),

A: To get a single link to the list of children instead of a list of links to the children themselves, you should replace the use of HyperlinkedRelatedField with HyperlinkedIdentityField.
According to official docs:
HyperlinkedRelatedField
This serializer will give you a representation like this:
{
    'album_name': 'Graceland',
    'artist': 'Paul Simon',
    'tracks': [
        'http://www.example.com/api/tracks/45/',
        'http://www.example.com/api/tracks/46/',
        'http://www.example.com/api/tracks/47/',
        ...
    ]
}

HyperlinkedIdentityField
This serializer will give you a representation like this:
{
    'album_name': 'The Eraser',
    'artist': 'Thom Yorke',
    'track_listing': 'http://www.example.com/api/track_list/12/',
}


text:
Q: DeferRefresh Error in C#
Possible Duplicate:
What is the proper way to handle multiple datagrids in a tab control so that cells leave edit mode when the tabs are changed?

When I'm binding my list to data grid after updating of data grid it gives me error like
"DeferRefresh' is not allowed during an AddNew or EditItem transaction"

so how can i overcome my problem please any one help me.
Thanks,
@nagaraju.


text:
Q: JSF: Bean constructor called twice on initial loading of page
I am reading Java EE 7 tutorial. In chapter 13.12, there is an example application, ajaxguessnumber. I run the example in Glassfish 4 and everything works fine. I then put System.out.println in bean constructor and I realized that the constructor is being called twice during initial page loading. Why is that so, even for @SessionScoped bean?
Here is the xhtml file
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <h:head>
        <h:outputStylesheet library="css" name="default.css"/>
        <title>Ajax Guess Number Facelets Application</title>
    </h:head>
    <h:body>
        <h:form id="AjaxGuess">
            <h:graphicImage value="#{resource['images:wave.med.gif']}"
                            alt="Duke waving his hand"/>

                Hi, my name is Duke. I am thinking of a number from
                #{dukesNumberBean.minimum} to #{dukesNumberBean.maximum}.
                Can you guess it?

                <h:inputText
                    id="userNo"
                    title="Type a number from 0 to 10:"
                    value="#{userNumberBean.userNumber}">
                    <f:validateLongRange
                        minimum="#{dukesNumberBean.minimum}"
                        maximum="#{dukesNumberBean.maximum}"/>
                </h:inputText>

                <h:commandButton id="submit" value="Submit" >
                    <f:ajax execute="userNo" render="outputGroup" />
                </h:commandButton>

                <h:panelGroup layout="block" id="outputGroup">
                    <h:outputText id="result" style="color:blue"
                                  value="#{userNumberBean.response}" rendered="#{!facesContext.validationFailed}"/>
                    <h:message id="errors1"
                               showSummary="true"
                               showDetail="false"
                               style="color: #d20005;
                               font-family: 'New Century Schoolbook', serif;
                               font-style: oblique;
                               text-decoration: overline"
                               for="userNo"/>
                </h:panelGroup>

        </h:form>
    </h:body>

Here is the bean DukesNumberBean
package javaeetutorial.ajaxguessnumber;

import java.io.Serializable;
import java.util.Random;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;

@Named
@SessionScoped
public class DukesNumberBean implements Serializable {

    private Integer randomInt = null;
    private long maximum = 10;
    private long minimum = 0;

    public DukesNumberBean() {
        System.out.println("Inside DukesNumberBean constructor");

        Random randomGR = new Random();
        long range = maximum+minimum+1;
        randomInt = (int) (minimum + randomGR.nextDouble()*range);
        System.out.println("Duke's number: " + randomInt);
    }

    public long getMaximum() {
        return (this.maximum);
    }

    public void setMaximum(long maximum) {
        this.maximum = maximum;
    }

    public long getMinimum() {
        return (this.minimum);
    }

    public void setMinimum(long minimum) {
        this.minimum = minimum;
    }

    /**
     * @return the randomInt
     */
    public Integer getRandomInt() {
        return randomInt;
    }

    /**
     * @param randomInt the randomInt to set
     */
    public void setRandomInt(Integer randomInt) {
        this.randomInt = randomInt;
    }

}

And here's the bean UserNumberBean
    package javaeetutorial.ajaxguessnumber;

import java.io.Serializable;
import javax.enterprise.context.RequestScoped;
import javax.inject.Inject;
import javax.inject.Named;

@Named
@RequestScoped
public class UserNumberBean implements Serializable {
    @Inject
    DukesNumberBean dukesNumberBean;
    private Integer userNumber = null;
    String response = null;

    public UserNumberBean()
    {
        System.out.println("Inside constructor");
    }

    public void setUserNumber(Integer user_number) {
        userNumber = user_number;
    }

    public Integer getUserNumber() {
        return userNumber;
    }

    public String getResponse() {
        if ((userNumber != null) && (userNumber.compareTo(dukesNumberBean.getRandomInt()) == 0)) {
            return "Yay! You got it!";
        }
        if (userNumber == null) {
            return null;
        } else {
            return "Sorry, " + userNumber + " is incorrect.";
        }
    }
}

Any help would be much appreciated. Thank you.

A: This happens because the scoped objects and injected by CDI using proxies. CDI has first to create a proxy of your object that is a subclass of your real object - this is the first time your constructor gets called because when you instantiate a subclass the parent constructor is always called. And then CDI instantiates your real object in order to inject it - this is the second time your constructor gets called.
A better approach is to put your initialization login in a @PostConstruct method like this.
@PostConstruct
public void init() {
    Random randomGR = new Random();
    long range = maximum+minimum+1;
    randomInt = (int) (minimum + randomGR.nextDouble()*range);
    System.out.println("Duke's number: " + randomInt);
}

It will be called only once - when the real object gets instantiated. More info about the proxies you can find here.
EDIT:
I just found another explanation of the problem - here.


text:
Q: How to close browser window after form submission is complete? I have old file that has been changed. One of the requests for this file/project modification is when user clicks OK to submit the form and close the current browser window. I'm wondering if this can be achieved with plain/vanilla JavaScript? So I have form and button:
<form name="test" id="test" action="/save_form.cfm">
   <input type="submit" value="OK">
</form>

A: You can simply use:
window.close();

You can type it in your input tag or make a new script tag with that code in it, whenever a button is clicked.
For example
<input type="submit" value="OK" onclick="closeWindow();">

In addition, you can add return false to 'onclick' to prevent the default actions.

A: Yes, JavaScript can close the current window, but bare in mind that if the browser has other tabs open, the browser won't close.
var closeBtn = document.querySelector("#test input");

closeBtn.addEventListener("click", ()=>{
    window.close()
})

A: you can use onSubmit event as shown here to call a function and then when its done use window.close() to close the window.

A: window.close();

However you can't just close any window. It only works if it's one that you opened yourself. (security feature).
This was already answered in detail here:

A: Assuming the window was opened using window.open() , have your save-form.cfm return a basic html page with script tag to close window when submit and validation is succesfaul

Window should close automatically


text:
Q: SQL select max of boolean value on columns I have two boolean type columns in my table. I want to make a select on these two columns according to these conditions:
for each column:

*

*if at least one line = 1, I put @result =1

*if no line = 1, I put @result = 0

CREATE TABLE test
(
    active1 bit,
    active2 bit,
)

INSERT INTO test(active1 , active2 )
 VALUES
 (0,0),
 (1;0),
 (0.0);

it must return @result1= 1 and @result2= 0 ,I want to do this in a single query, I tried with MAX but it didn't work :
declare @result1 bit
declare @result1 bit
select
@result1= max(active1), @result2= max(active2)
from test

Help please

A: You cannot perform aggregations on bit columns, you need to cast them to a suitable data type
declare @result1 bit, @result2 bit;

with t as (
    select Convert(tinyint, active1) active1, Convert(tinyint, active2) active2
    from test
)
select @result1=max(active1), @result2= max(active2)
from t;

select @result1 Result1, @result2 Result2;

(note also that bit columns are not booleans)


text:
Q: Can't display modal from link in jQuery I have a script that I need to be able do trigger a modal from a link from my jQuery. When a user clicks on the thumbnail class, a full screen modal should appear with more info.
I have the following, but stuck on how to organize the code so that the page works:
$(function(){
$.getJSON('url', function(data) {
    for(var key in data.results) {
      var poster = data.results[key].poster_path,
          title = data.results[key].title,
          description = data.results[key].overview;
          if(data.results.hasOwnProperty(key)) {
                  $('').attr({
                    src:'http://image.tmdb.org/t/p/w342' + poster
                  }).appendTo($('').attr({
                    href:'http://image.tmdb.org/t/p/w342' + poster
                  }).appendTo($('.container')));
          }
          $('body').append("
\

\

\

\
                    <button type="button" class="close" data-dismiss="modal">×Close</button>\

Modal title
\

\

\

This is the title of the movie
\

\

\
                    <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>\

\

\

\

");
      }
});
});

With the modal in its current place, the page doesn't work at all. I will also need to be able to grab data from the data feed as well, to populate the modal window.
This is a sample object that the modal needs to grab information from:
{
poster_path: "/e1mjopzAS2KNsvpbpahQ1a6SkSn.jpg",
overview: "details about movie",
release_date: "2016-08-03",
id: 297761,
original_title: "Title of movie",
original_language: "en",
title: "Title of movie",
popularity: 44.788935,
vote_count: 1552,
}


text:
Q: flask_sqlalchemy `pool_pre_ping` only working sometimes For testing, I amend the MYSQL (RDS) parameters as follows;

wait_timeout = 40 (default was 28800)
max_allowed_packet = 1GB (max - just to be sure issue not caused by small packets)
net_read_timeout = 10
interactive_timeout unchanged

Then tested my app without pool_pre_ping options set (defaults to False), kept the app inactive for 40 seconds, tried to login, and i get
Nov 14 20:05:20 ip-172-31-33-52 gunicorn[16962]: Traceback (most recent call last):
Nov 14 20:05:20 ip-172-31-33-52 gunicorn[16962]:   File "/var/www/api_server/venv/lib/python3.6/site-packages/sqlalchemy/engine/base.py", line 1193, in _execute_context
Nov 14 20:05:20 ip-172-31-33-52 gunicorn[16962]:     context)
Nov 14 20:05:20 ip-172-31-33-52 gunicorn[16962]:   File "/var/www/api_server/venv/lib/python3.6/site-packages/sqlalchemy/engine/default.py", line 507, in do_execute
Nov 14 20:05:20 ip-172-31-33-52 gunicorn[16962]:     cursor.execute(statement, parameters)
Nov 14 20:05:20 ip-172-31-33-52 gunicorn[16962]:   File "/var/www/api_server/venv/lib/python3.6/site-packages/MySQLdb/cursors.py", line 206, in execute
Nov 14 20:05:20 ip-172-31-33-52 gunicorn[16962]:     res = self._query(query)
Nov 14 20:05:20 ip-172-31-33-52 gunicorn[16962]:   File "/var/www/api_server/venv/lib/python3.6/site-packages/MySQLdb/cursors.py", line 312, in _query
Nov 14 20:05:20 ip-172-31-33-52 gunicorn[16962]:     db.query(q)
Nov 14 20:05:20 ip-172-31-33-52 gunicorn[16962]:   File "/var/www/api_server/venv/lib/python3.6/site-packages/MySQLdb/connections.py", line 224, in query
Nov 14 20:05:20 ip-172-31-33-52 gunicorn[16962]:     _mysql.connection.query(self, query)
Nov 14 20:05:20 ip-172-31-33-52 gunicorn[16962]: MySQLdb._exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query')

Added the pool_pre_ping like this (Using flask_sqlalchamy version 2.4.1);
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy as _BaseSQLAlchemy

class SQLAlchemy(_BaseSQLAlchemy):
    def apply_pool_defaults(self, app, options):
        super(SQLAlchemy, self).apply_pool_defaults(app, options)
        options["pool_pre_ping"] = True
#        options["pool_recycle"] = 30
#        options["pool_timeout"] = 35

db = SQLAlchemy()

class DevConfig():
    SQLALCHEMY_ENGINE_OPTIONS = {'pool_recycle': 280, 'pool_timeout': 100, 'pool_pre_ping': True} # These configs doesn't get applied in engine configs :/
    DEBUG = True
    # SERVER_NAME = '127.0.0.1:5000'
    SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI_DEV')
    SQLALCHEMY_TRACK_MODIFICATIONS = False

config = dict(
    dev=DevConfig,
)

app = Flask(__name__, instance_relative_config=True)
app.config.from_object(config['dev'])

# INIT DATABASE
db.init_app(app)
with app.app_context():
    db.create_all()

-----------run.py
app.run(host='127.0.0.1', port=5000)

With this, now the webapp manages to get new connection even after MySQL server has closed the previous connection. It always works fine when I access the database right after its closed by server (tried max 50 seconds after)... but when I keep connection inactive for long time (haven't noted, but ~ >10-15 min), again I see same error.
According to the docs, (especially the section Dealing with disconnects), the pool_pre_ping option should handle this kind of scenario at background rite? Or is there any other timeout variable that I need to change in MySQL server?

A: I set the following settings:
SQLALCHEMY_ENGINE_OPTIONS = {
    'pool_size': 10,
    'pool_recycle': 60,
    'pool_pre_ping': True
}

The last few months have stopped falling...

A: From the Flask-SQLAlchemy  Configuration docs:

Certain database backends may impose different inactive connection
timeouts, which interferes with Flask-SQLAlchemy's connection pooling.
By default, MariaDB is configured to have a 600 second timeout. This
often surfaces hard to debug, production environment only exceptions
like

2013: Lost connection to MySQL server during query.

If you are using a backend (or a pre-configured database-as-a-service)
with a lower connection timeout, it is recommended that you set
SQLALCHEMY_POOL_RECYCLE to a value less than your backend's timeout.

The script cited in the question shows discrepancies between its MySQL  timeout-configs  (wait_timeout, net_read_timeout) and its SQLAlchemy  (pool_recycle, pool_timeout) and Flask-SQLAlchemy  timeouts (SQLALCHEMY_POOL_RECYCLE, SQLALCHEMY_POOL_TIMEOUT).
We can resolve this by using the DevConfig helper-class to coordinate the db connection config constants across the app. To do that, we assign our config to static attributes and refer back to them so that there are no conflicting timeout expectations. Here is an implementation:
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy as _BaseSQLAlchemy

# Coordinate DevConfig with SQLAlchemy and Flask-SQLAlchemy (don't repeat yourself!)

class DevConfig():
    SQLALCHEMY_POOL_RECYCLE = 35  # value less than backend's timeout
    SQLALCHEMY_POOL_TIMEOUT = 7  # value less than backend's timeout
    SQLALCHEMY_PRE_PING = True
    SQLALCHEMY_ENGINE_OPTIONS = {'pool_recycle': SQLALCHEMY_POOL_RECYCLE, 'pool_timeout': SQLALCHEMY_POOL_TIMEOUT, 'pool_pre_ping': SQLALCHEMY_PRE_PING}
    DEBUG = True
    # SERVER_NAME = '127.0.0.1:5000'
    SQLALCHEMY_DATABASE_URI = os.getenv('SQLALCHEMY_DATABASE_URI_DEV')
    SQLALCHEMY_TRACK_MODIFICATIONS = False

class SQLAlchemy(_BaseSQLAlchemy):
    def apply_pool_defaults(self, app, options):
        super(SQLAlchemy, self).apply_pool_defaults(app, options)
        options["pool_pre_ping"] = DevConfig.SQLALCHEMY_PRE_PING
#        options["pool_recycle"] = 30
#        options["pool_timeout"] = 35

db = SQLAlchemy()

config = dict(
    dev=DevConfig,
)

app = Flask(__name__, instance_relative_config=True)
app.config.from_object(config['dev'])

# INIT DATABASE
db.init_app(app)
with app.app_context():
    db.create_all()

If you like, you can check the diff for the changes I made: diffchecker.com/Q1e85Hhc


text:
Q: Azure Function App copy blob from one container to another using startCopy in java I am using java to write a Azure Function App which is eventgrid trigger and the trigger is blobcreated. So when ever blob is created it will be trigerred and the function is to copy a blob from one container to another. I am using startCopy function from com.microsoft.azure.storage.blob. It was working fine but sometimes, It uses to copy files of zero bytes which are actually containing some data in source location. So at destination sometimes it dumps zero bytes of files. I would like to have a little help on this so that I could understand how to possibly handle this situation
CloudBlockBlob cloudBlockBlob = container.getBlockBlobReference(blobFileName);
CloudStorageAccount storageAccountdest = CloudStorageAccount.parse("something");
CloudBlobClient blobClientdest = storageAccountdest.createCloudBlobClient();
CloudBlobContainer destcontainer = blobClientdest.getContainerReference("something");
CloudBlockBlob destcloudBlockBlob = destcontainer.getBlockBlobReference();
destcloudBlockBlob.startCopy(cloudBlockBlob);

A: Copying blobs across storage accounts is an async operation. When you call startCopy method, it just signals Azure Storage to copy a file. Actual file copy operation happens asynchronously and may take some time depending how how large file you're transferring.
I would suggest that you check the copy operation progress on the target blob to see how many bytes have been copied and if there's a failure in the copy operation. You can do so by fetching the properties of the target blob. A copy operation could potentially fail if the source blob is modified after the copy operation has started by Azure Storage.

A: had the same problem, and later figured out from the docs

Event Grid isn't a data pipeline, and doesn't deliver the actual
  object that was updated

Event grid will tell you that something has changed and that the actual message has a size limit and as long as the data that you are copying is within that limit it will be successful if not it will be 0 bytes. I was able to copy upto 1mb and beyond that it resulted 0 bytes. You can try and see if azure has increased by size limit in the recent.
However if you want to copy the complete data then you need to use Event Hub or Service Bus. For mine, I went with service bus.


text:
Q: Converting a BitSet to a byte[] with same representation I am working on generating a 64 bits keys for DES where only 20 bits are effective i.e. the rest is padded with zeros. The way I am trying to approach it is by having a BitSet of 23 bits where every 8th is skipped (i.e. kept as false) and the rest is determined the SecureRandom.nextBoolean(). So, the output of my BitSet is 23 bits where every 8th is false. The reason why I do this is to make sure that the parity bits are not a part of the 20 bits effective key.
Afterwards, I try to convert the BitSet by using Bitset.toByteArray(), which gives me 3 bytes and then I pad the rest 5 bytes with zeros. However, the problem occurs when I try to convert the BitSet to a byte[] as the representation is reversed.
public static byte[] generateDesKey() {
        BitSet temp = new BitSet();
        byte[] zeroByteKey = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
        Random r = new SecureRandom();

        for (int i = 0; i < 64; i++) {
            if (i % 8 != 0 && i < 23) {

                temp.set(i, r.nextBoolean());
            }
        }

          StringBuilder sb = new StringBuilder();
          for( int i = 0; i < temp.length();  i++ )
          {
              sb.append( temp.get( i ) == true ? 1: 0 );
          }

          System.out.println("Bitset " +sb );

        byte[] tempByteKey = temp.toByteArray();

        for (byte b : tempByteKey) {
            System.out.print(Integer.toBinaryString(b & 255 | 256).substring(1));
        }

        for (int i = 0; i < tempByteKey.length; i++) {
            zeroByteKey[i] = tempByteKey[i];
        }

        return zeroByteKey;
    }

An example of output:
Bitset 00010100011110010011101 // 23 bits where parity bits are skipped
Converted BitSet to byte[] in binary 101101000000111001011100 // 24 bits where every 8 bits are reversed

The reason why, I assume, the second output is 24 bits is because 23 bits is rounded up to 3 bytes, when converted from BitSet to byte[].


text:
Q: Complex integral with essential singularity at 0 I need help in solving the following problem in complex calculus. I need to calculate this real integral:
$$
\int_0^{2\pi} e^{\cos{\theta}}\cos(\sin\theta) \,\,\, d\theta
$$
I think that the best method is to do the substitution $z=re^{i\theta}$, from which we have $d\theta = \frac{dz}{iz}$, $\cos\theta=\frac{1}{2}(z+\frac{1}{z})$ and so on. The integral then becomes (without constants)
$$
\oint_{|z|=r} e^{\frac{z}{2}}e^{\frac{1}{2z}}\frac{z^4-6z^2+1}{z(z^2-1)} \,\,\,dz
$$
At this point I am unable to calculate the residue at the essential singularity in 0, because the manipulation of Laurent series rapidly becomes utterly complicated and I don't see any simple way to find the final coefficient of $1/z$. So, which is the way to handle this integral? Another substitution?

A: Things work very nicely if we take a slightly different approach at the start. (The value of the integral is $2\pi$.)  Notice that $$\cos\left(\sin\theta\right)=\text{Re}\left(e^{i\sin\theta}\right).$$ Hence, since $e^{\cos\theta}$  is already real our integral becomes $$\int_{0}^{2\pi}\text{Re}\left(e^{\cos\theta}e^{i\sin\theta}\right)d\theta=\text{Re}\int_{0}^{2\pi}e^{\left(e^{i\theta}\right)}d\theta.$$
Substituting $z=e^{i\theta}$  we have  $$\text{Re}\int_{\mathbb{S}^{1}}\frac{e^{z}}{iz}dz=2\pi i \text{Res}\left(\frac{e^{z}}{iz}\right) = 2\pi$$  since the residue is $\frac{1}{i}$.
Hope that helps,


text:
Q: Where do I ask non-mainstream physics questions? Where do I ask non-mainstream physics questions? For instance, a question that links the human mind, physics, neuroscience & perhaps mathematics like-
According to physics, do our visual thoughts (possibly others) appear to be not real because they occupy physically inaccessible higher dimensions?
It wasn't well received in physics stack exchange or psychology & neuroscience stack exchange.

A: As the [on hold] notice shows, it's about mainstream physics - things that scientists tend to agree about, and which we have a pretty good idea of.
And the science of our day just hasn't yet progressed to an understanding of the human mind to depth you seem to have been asking.
While I personally haven't ever posted there, perhaps philosophy might be able to host this question. No promises.

A: I don't think that question can be asked anywhere on the Stack Exchange network. These sites are only for specific, focused questions. As far as I can tell, what you posted seems to be an essay exploring your ideas on what is real or not. This may well be interesting, but it isn't a question that can be answered. After all, you even highlight it yourself at the end:

Finally, I just explored my thoughts in the above.I don't claim anything above to be true & I can be wrong or right. Please share your thoughts.

As you said, you're exploring your thoughts and are asking for others to share their thoughts. That is not what these sites are for. We don't do discussion, we don't accept open ended questions. These sites are strictly Q&A, so if you ask a question, it must be of a form that can take a more or less straightforward, specific answer.
It looks like you need a place that is more geared towards hosting discussions instead.

A: The question has been deleted, so the only available information is what's posted here.  Just going by that, it sounds like part of what cognitive psychology deals with.  It draws on some other disciplines, but physics wouldn't be one of them.  It's about how cognitive processes work, which is understandable through "brain science".  There's extensive research into this stuff.  To understand it, you would want to get the related science under your belt.  Undergraduate coursework in cognitive psychology might touch on it generally, but that would be a good jumping off point.
It's too complex of a subject to answer well within the intended scope of a Q&A site, and it could well be that there isn't a big concentration of subject matter experts here.  For the heck of it, I entered "cognitive psychology web site" in Google, and it looks like there are a number of sites dedicated to the subject.  That might be a good way to start exploring this.


text:
Q: I want to find the element Rig, on clicking "Rig" -> dropdown opens having only element "Search" How to find ul and li tags
I want to find the element Rig, on clicking "Rig" -> dropdown opens having only element "Search"
Home
Rig
Rig
enter image description here

A: Th element button with text Rig can be found using the xPath: "//div[@id='3_menubar']/ul/li/button[contains(text(), 'Rig')]"

A: Try following:
   driver.findElement(By.cssSelector("div.t-Header-nav > div > ul li:nth-child(2) button"));


text:
Q: JSON Write throws invalid type When I try to write some data for some ML Inside of a api, like in Postman, the entry works, but for some reason, when I write it in Swift I am having some trouble:
func makePOSTRequest() {

        print("entered request function")

        guard let url = URL(string: "https://doctagon.herokuapp.com/diagnose") else {
            print("error with getting the URL")
            return
        }
        print("got the URL")

        var request = URLRequest(url: url)
        print("Got the request")
        // method, body, headers?
        request.httpMethod = "POST"
        print("got the http.method = 'POST'")

        // might not need this --> request.setValue(" symptoms", forHTTPHeaderField: "Content-Type")
        let body: [String: AnyHashable] = [
            "symptoms": ["Headache", "Sweating"]
        ]
        print("got the body")

        print("About to enter the .httpBody part of the code")
        request.httpBody = try? JSONSerialization.data(withJSONObject: body, options: .fragmentsAllowed)
        //Make the request
        let task = URLSession.shared.dataTask(with: request) { data, _, error in
            guard let data = data, error == nil else {
                print("error with making sure that there is data")
                return
            }
            print("got data")
            do {
                let response = try JSONSerialization.data(withJSONObject: data, options: .fragmentsAllowed)
                print("SUCCESS \(response)")
            } catch {
                print("error with the conversion of the JSOn")
                print(error)
            }
        }
        task.resume()
        print("resumed Task")
    }

with my error:
2022-11-19 23:39:30.335160-0500 Doctagon[88188:1838200] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Foundation.__NSSwiftData)'
*** First throw call stack:
(
    0   CoreFoundation                      0x000000018040e7ec __exceptionPreprocess + 172
    1   libobjc.A.dylib                     0x0000000180051144 objc_exception_throw + 56
    2   Foundation                          0x0000000180c446f8 _writeJSONValue + 704
    3   Foundation                          0x0000000180c443f8 -[_NSJSONWriter dataWithRootObject:options:] + 84
    4   Foundation                          0x0000000180c470d0 +[NSJSONSerialization dataWithJSONObject:options:error:] + 108
    5   Doctagon                            0x0000000100be4080 $s8Doctagon12QuestionViewV15makePOSTRequestyyFy10Foundation4DataVSg_So13NSURLResponseCSgs5Error_pSgtYbcfU_ + 544
    6   Doctagon                            0x0000000100be45ec $s10Foundation4DataVSgSo13NSURLResponseCSgs5Error_pSgIeghggg_So6NSDataCSgAGSo7NSErrorCSgIeyBhyyy_TR + 264
    7   CFNetwork                           0x0000000183df9928 CFNetwork + 31016
    8   CFNetwork                           0x0000000183e14a4c _CFHTTPMessageSetResponseProxyURL + 14648
    9   libdispatch.dylib                   0x0000000104c30594 _dispatch_call_block_and_release + 24
    10  libdispatch.dylib                   0x0000000104c31d5c _dispatch_client_callout + 16
    11  libdispatch.dylib                   0x0000000104c3a040 _dispatch_lane_serial_drain + 928
    12  libdispatch.dylib                   0x0000000104c3adb8 _dispatch_lane_invoke + 484
    13  libdispatch.dylib                   0x0000000104c48b40 _dispatch_workloop_worker_thread + 1720
    14  libsystem_pthread.dylib             0x00000001af2568fc _pthread_wqthread + 284
    15  libsystem_pthread.dylib             0x00000001af2556c0 start_wqthread + 8
)
libc++abi: terminating with uncaught exception of type NSException
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Invalid type in JSON write (Foundation.__NSSwiftData)'
terminating with uncaught exception of type NSException
CoreSimulator 857.13 - Device: iPhone 14 Pro (4108291D-D836-4715-8386-5237B6D217E7) - Runtime: iOS 16.1 (20B72) - DeviceType: iPhone 14 Pro

I still do not understand my problem because I was able to run it fine in Postman, but as soon as I went into Xcode, the code stopped working.
I think that the error is on this line: let response = try JSONSerialization.data(withJSONObject: data, options: .fragmentsAllowed)

A: what you are trying to do is create a json object (in this case it will be an instance of Dictionary<String: Any>) using the data received from the network
so you should be calling JSONSerialization.jsonObject(with: data) instead.


text:
Q: Enabling Developer mode on a webos TV (LG) Trying to enable developer mode on an LG TV with WebOS via these instructions so I can install the twitch.tv app for webos but I cannot find the Developer App anywhere on my smart tv. Not in Smart World or any other store page I could find.
I've tried looking at similar questions on here but they all say something like "go to the "content store""  or  "go to "lg store"" which, for me atleast, aren't a thing on the page where the apps are displayed (smart home, I think?)
I've installed the SDK on my computer incase I need to do something with that.
I'm really confused and would like any help possible. Thanks!

A: To enable developer mode on LG WebOS TV you need to install Developer mode app from LG Content Store

*

*On remote press Home button

*Go to LG Content Store

*Search 'Developer mode' on LG Content Store

*Install 'Developer mode' app

*from this application you can enable Developer mode

A: Sadly, it seems I am a bit stupid and didn't realise that my TV isn't WebOS. It's netcast.


text:
Q: extract data from specific column based on header in python I have a dataset (csv file) that contains water levels over time for many observation bores. For example
Time    REM_WELL1   REM_WELL2   DEEP_WELL_SYP   SP_1
1989.778        4.54
1989.786                4.87
1989.806
1990.531        4.46    4.5 4.7
1990.553
1990.575
1990.603    4.66    4.49    4.54    4.75
1990.908    4.71        4.61    4.6
1990.992    4.72    4.61    4.63    4.67
1991.106    4.41    4.59    4.58    4.82
1991.156    4.61    4.41    4.5 4.77
1991.256    4.61    4.37    4.49    4.75

I want to extract a column of data for a specific well (for example: SP100) by searching for its name on the first line and grab its water levels to plot a hydrograph. Can anyone help me with this?

A: Use the csv module:
import csv

with open('well.csv', 'rb') as f:
    reader = csv.DictReader(f, dialect='excel-tab')
    rows = list(reader)

sp100 = [x.values() for x in rows if 'sp100' in x]

Or, if you need to do some more manipulation of data use the excellent pandas library.


text:
Q: How to populate a 2-d array in python? What's the pythonic way to rewrite the following C code?
int a[16][4];
int s[16] = {1,0,2,3,0,1,1,3,3,2,0,2,0,3,2,1};

for (int i = 0; i < 16; ++i) {
    for (int j = 0; j < 16; ++j) {
        int diff = i ^ j;
        int val = s[i] ^ s[j];
        ++a[diff][val];
    }
}

A: Here is some equivalent Python code:
a = [[0]*4 for i in range(16)]
s = [1,0,2,3,0,1,1,3,3,2,0,2,0,3,2,1]
for i in range(16):
    for j in range(16):
        diff = i ^ j
        val = s[i] ^ s[j]
        a[diff][val] += 1

A: The array is initialized by
In [1]: a=[[0]*4]*16

In [2]: a
Out[2]:
[[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]

Then the second array (list):
In [5]: s  = [1,0,2,3,0,1,1,3,3,2,0,2,0,3,2,1]

Bitwise operators in Python are similar to C. As FJ already posted it's the same.

A: Implementation
a = [[0]*4 for _ in range(16)]
s = [1,0,2,3,0,1,1,3,3,2,0,2,0,3,2,1]
from itertools import product
for diff, val in ((i ^ j, s[i] ^ s[j])
                  for i, j in product(range(16), repeat = 2):
    a[diff][val] += 1


text:
Q: Omniauth facebook sessions controller create action integration after Michael Hartl tutorial I have just finished the Michael Hartl tutorial. I am trying to implement omniauth-facebook to sign-up and sign-in users. I am having trouble creating the master variable to use in the create action in the sessions controller. My assumption is that I should put in an if else statement to see if the master is either signing on through facebook or through the default form? Or should I use and or statement:
(master = Master.find_by(email: params[:session][:email].downcase) || Master.from_omniauth(env["omniauth.auth"])) ?

Here is the omniauth-facebook sessons controller create action code:
def create
    user = User.from_omniauth(env["omniauth.auth"])
    session[:user_id] = user.id
    redirect_to root_url
  end

And here is my current sessions controller create action code:
class SessionsController < ApplicationController

    def new
    end

    def create
        master = Master.find_by(email: params[:session][:email].downcase)
        if master && master.authenticate(params[:session][:password])
            sign_in master
            redirect_back_or master
        else
            flash.now[:error] = 'Invalid email/password combination'
            render 'new'
        end
    end
    .
    .
    .

end

A: Whilst I might be late by one year to answer this question, I still think that new viewers with the same sort of problem like you had a year ago might benefit from the following answer
As I understand it the actual question is:

How does one integrate Facebook Authentication with an Authentication system that is built from Scratch?

Since you said you used Michael Hartl's tutorial I went ahead and adapted my answer to an authentication system written by Michael himself. Now let's go over each piece of code one step at a time.

1
First of all we need to create two additional columns to our existing Users table for the provider and uid as follows...
rails g migration add_facebook_auth_to_users provider uid
...and add omniauth-facebook gem to the Gemfile...
Gemfile
gem 'omniauth-facebook',       '2.0.1'
Don't forget to run bundle install and migrate your database after.

2
Next we would need to go ahead and edit our Sessions controller...
sessions_controller.rb
def create
  user = User.find_by(email: params[:session][:email].downcase)
  if user && user.authenticate(params[:session][:password])
    if user.activated?
      log_in user
      params[:session][:remember_me] == '1' ? remember(user) : forget(user)
      redirect_back_or user
    else
      message  = "Account not activated. "
      message += "Check your email for the activation link."
      flash[:warning] = message
      redirect_to root_url
    end
  else
    flash.now[:danger] = 'Invalid email/password combination'
    render 'new'
  end
end

def create_facebook
  user = User.from_omniauth(env["omniauth.auth"])
  log_in user
  redirect_back_or user
end

Sessions controller above contains two create actions. First one is the untouched method taken straight from the book, when the second one is a piece of code I used specifically for Facebook authentications.
Line user = User.from_omniauth(env["omniauth.auth"]) has two purposes. Create a user IF his/her unique facebook uid is not in the database ELSE log this person in the app if the uid exists. More on this later.

3
Next lets create a working .from_omniauth method that you briefly showed inside of your code in your question...
user.rb
def self.from_omniauth(auth)
  where(provider: auth.provider, uid: auth.uid).first_or_initialize.tap do |user|
    user.provider = auth.provider
    user.uid = auth.uid
    user.name = auth.info.name unless user.name != nil
    user.email =  SecureRandom.hex + '@example.com' unless user.email != nil
    user.activated = true
    user.password = SecureRandom.urlsafe_base64 unless user.password != nil
    user.save!
  end
end

Here we try to find a user that matches the given provider and uid values from the hash and then we call first_or_initialize on the result of this. This method will either return the first matching record or initialize a new record with the parameters that were passed in. We then call tap on this to pass that User instance to the block. Inside the block we set various attributes on the user based on values from the OmniAuth hash.
You might be interested as to why did I put the unless statement after some of the attribute initializations. Well consider the situation whereby the user wants to update the profile, like change the name or smth, and then logs out. When that user finally decides to log back in, the .from_omniauth method will overwrite the User's in question update to the original facebook values, unless we stop it from doing so.
Also notice the use of SecureRandom library. Inside of the traditional authentication that was used by Michael Hartl inside his book, he introduces validations to email and password submissions. Emails must be neither blank nor taken. Likewise, a password has to be greater than 6 characters in length. Since emails have to be present and unique I decided to create dummy emails using SecureRandom.hex + @example.com. This will create a random hexadecimal string, like 52750b30ffbc7de3b362, and append it to @example.com, hence generating the unique dummy email. Same goes for the password, however, I preferred to generate a random base64 string using SecureRandom.urlsafe_base64. The most important thing to remember that Facebook users don't need to know this information to login since that is the whole point of using Facebook authentication. This allows them to add this information with real data later on if they desire to do so.

4
Now would be a good time to add the button on the main application page for users to let them actually log in into the app...
_header.html.erb
<% if logged_in? %>
  .
  .
  .
<% else %>
  .
  .

<%= link_to "Sign in with Facebook", "/auth/facebook", id: "sign_in" %>

<% end %>

5
So, now we can send a request to facebook. One problem remains that we cannot actually handle the callback. To do so we need to do the following...

*

*Add get 'auth/:provider/callback' => 'sessions#create_facebook' to the routes.rb file

*Use convenient Javascript SDK provided by Facebook. Let's create a custom javascript file that uses this SDK...
app/assets/javascripts/facebook.js.erb
jQuery(function() {
  $('body').prepend('

');
  return $.ajax({
    url: window.location.protocol + "//connect.facebook.net/en_US/sdk.js",
    dataType: 'script',
    cache: true
  });
});

window.fbAsyncInit = function() {
  FB.init({
    appId: 'your_facebook_app_id_goes_here',
    version: 'v2.3',
    cookie: true
  });
  $('#sign_in').click(function(e) {
    e.preventDefault();
    return FB.login(function(response) {
      if (response.authResponse) {
        return window.location = '/auth/facebook/callback';
      }
    });
  });
  return $('#sign_out').click(function(e) {
    FB.getLoginStatus(function(response) {
      if (response.authResponse) {
        return FB.logout();
      }
    });
    return true;
  });
};

6
And that is it, except for one small caveat...

If user decides to go and edit the profile, he/she would see our dummy email displayed right in the middle.This happends because Rails is smart enough to autofill User's information.In this case this, frankly, is quite embarassing. Good thing, however, that it is an easy fix. Just set the value to nil inside the form, like so...
 <%= f.email_field :email, value: nil, class: 'form-control' %>

Hopefully this helps people who would like to go the route of building authentication systems from scratch :)

A: Ok I was trying to integrate omniauth with the custom authorization code from the tutorial. After some research I decided to remove all the tutorial authorization code and go with Devise instead.

A: Timur's answer is excellent, but assumes that the OP has already configured some things for OmniAuth. Unfortunately some readers will not have done the config and will get errors.
The minimum config for omniauth is to set up facebook credientials, make them available to the app and create a file called config/initializers/omniauth.rb with the following:
    Rails.application.config.middleware.use OmniAuth::Builder do
      provider :developer unless Rails.env.production?
      provider :facebook, ENV['FACEBOOK_KEY'], ENV['FACEBOOK_SECRET']
    end

And of course, it would be wise to write some tests for this feature.
Neither this nor Timur's answer deals with the situation where a user has created a local login account, then tries to log in from Facebook. It will fail due to a duplicate email or create a new account if the Facebook email is different. the User.from_omniauth(auth) function should be updated to handle this case. omniauth has a page about how to handle this, but will require significant rework from Miachal's hartl's tutorial: https://github.com/omniauth/omniauth/wiki/Managing-Multiple-Providers


text:
Q: Maxthon Browser 5 on Ubuntu? Is there a way to get the MX5 Browser on Ubuntu? if yes how?

A: MX 5 is not in the Ubuntu Repositories.
MX 5 is not supported software.
Use at your own risk.
Go to
http://www.maxthon.com/blog/maxthon-expands-its-suite-of-high-performance-web-browsers-to-linux/ and download the appropriate .deb file. 1.0.5 is currently the latest available.
Use dpkg to install the .deb
sudo dpkg --install /path/to/file.deb


text:
Q: How to load 32 bit dll on 64 bit matlab I am trying to load a 32-bit library on 64-bit Matlab but this error appears:
 Error using loaddefinedlibrary

D:\Code\Thinkgear.dll is not a valid Win32 application.

I was wondering if there is any way to solve this issue please?


text:
Q: Ruby on Rails Heroku - error deploying project Recently I tried to push my Rails project to git using Heroku, but the wild problem appeard.
All lines I pasted here: http://pastebin.com/5y09wFCi
Here I paste lines, which I found most important:
$ git push heroku master
Initializing repository, done.
Counting objects: 98, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (89/89), done.
Writing objects: 100% (98/98), 20.04 KiB | 0 bytes/s, done.
Total 98 (delta 8), reused 0 (delta 0)

-----> Ruby app detected
-----> Compiling Ruby/Rails
-----> Using Ruby version: ruby-2.0.0
-----> Installing dependencies using 1.7.12
       Running: bundle install --without development:test --path vendor/bundle --binstubs vendor/bundle/bin -j4 --deployment
       Fetching gem metadata from https://rubygems.org/...........
.
.
.
   Bundle completed (26.03s)
       Cleaning up the bundler cache.
-----> Preparing app for Rails asset pipeline
       Running: rake assets:precompile
       I, [2015-02-07T17:06:17.823271 #1283]  INFO -- : Writing /tmp/build_374afebb598e92eacd894ae2e50e6a4d/public/assets/application-4be62d87c5bb7f3e09992032049b2bd0.js
       rake aborted!
       wrong number of arguments (2 for 1)
.
.
.
       Tasks: TOP => assets:precompile
       (See full trace by running task with --trace)
 !
 !     Precompiling assets failed.
 !

 !     Push rejected, failed to compile Ruby app

To git@heroku.com:stark-tor-4197.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'git@heroku.com:stark-tor-4197.git'

stark-tor-4197 is my randomly named project.
It may be also important - I read, that Heroku don't work with sqlite3, so I had to make change in my gemfile.
Now part about database looks like this:
http://pastebin.com/EKjFzKDh
# Use postgresql as the database for Active Record
gem 'pg'
gem 'rails_12factor', group: :production

Thanks for any help!

A: Try to run rake assets:precompile on your local as it looks like there is some error in your assets i.e. javascript or css files.

A: A while ago I also had this problem where the following happened:
git push github master
To git@github.com:Joey-project/project.git
 ! [rejected]        master -> master (non-fast-forward)
error: failed to push some refs to 'git@github.com:Joey-project/project.git'

I've been told that the most common reason of this happening is because one is trying to push a branch to a remote branch that has been updated in the meantime.
In general one has to use a variation of the following commands:
git fetch github; git merge github/master

Any chance you already looked at RomanKapitonov's question (heroku: Gemfile.lock is required issue)? I believe it's related to your issue.


text:
Q: Getting DiscordAPIError[50035] after upgrading to discord.js v14.0.0 I just downloaded discord.js v14 (not the latest release) and I'm getting the error. I can't find what I did wrong but it was working in v13.1.0.
DiscordAPIError[50035]: Invalid Form Body
0.type[NUMBER_TYPE_COERCE]: Value "CHAT_INPUT" is not int.
3.options[0].type[NUMBER_TYPE_COERCE]: Value "USER" is not int.
3.options[1].type[NUMBER_TYPE_COERCE]: Value "STRING" is not int.
4.options[0].type[NUMBER_TYPE_COERCE]: Value "USER" is not int.
4.options[1].type[NUMBER_TYPE_COERCE]: Value "STRING" is not int.
    at SequentialHandler.runRequest (H:\Projects\Discord\Handler\node_modules\@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:293:15)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async SequentialHandler.queueRequest (H:\Projects\Discord\Handler\node_modules\@discordjs\rest\dist\lib\handlers\SequentialHandler.cjs:99:14)
    at async REST.request (H:\Projects\Discord\Handler\node_modules\@discordjs\rest\dist\lib\REST.cjs:52:22)
    at async GuildApplicationCommandManager.set (H:\Projects\Discord\Handler\node_modules\discord.js\src\managers\ApplicationCommandManager.js:173:18)
    at async H:\Projects\Discord\Handler\handler\index.js:47:13 {

If you need to know, here's where the error points to:
await guild.commands.set(slashcmds);

A: I've found out what I did wrong. To people reading this in the future, here's the answer:
Discord has changed from strings to enums, here's what they changed in my case ("+" means added, "-" means deprecated)
+ const { ApplicationCommandType, ApplicationCommandOptionType } = require('discord.js');

const command = {
  name: 'ping',
- type: 'CHAT_INPUT',
+ type: ApplicationCommandType.ChatInput,
  options: [{
    name: 'option',
    description: 'A sample option',
-   type: 'STRING',
+   type: ApplicationCommandOptionType.String,
  }],
};


text:
Q: How CDN detection works in webpgatest I did some performance optimization (and I test it with webpagetest.org) but I still have problem with CDN detection. It looks like on screen:

All requests (except first which is http request for html) with red X icon in last column are:

*

*for assets (css, js, images or fonts)

*from same domain (different than main application domain)

What should I do to have assets detected as CDN on this test???

A: WebPageTest just uses a list of the most common CDN providers and then parse the assets request header :
CDN_PROVIDER_HEADER cdnHeaderList[] = {
    {"server", "cloudflare", _T("Cloudflare")},

to check (in this case) if there is a server key containing cloudflare.

A: Are the assets actually hosted on a CDN?
If it's one of the common CDNs that WebPageTest will automatically detect it.
If it's one of the less common ones you may have to update the code and issue a pull request - there are plenty of examples of what needs changing in the closed PRs.


text:
Q: Laravel Application on Oracle WebLogic Server please i need someone to highlight firstly how i could execute php 5.x on Oracle Weblogic J2EE server and the settings required if any...
its a java based environment and i'm wondering how i could get this up and running seamlessly.
if you could provide in details the process required to get Apache working, alongside PHP, my intentions is to use it as the base for a Laravel application i'm currently working on and utilize Oracle as the backend database model...
any ideas ?


text:
Q: Rank of a special matrix Say a $5\times 5$ matrix
$$A = \left[ \begin{array}{ccc}
1&2&3&4&5\\
6&7&8&9&10\\
11&12&13&14&15\\
16&17&18&19&20\\
21&22&23&24&25\\ \end{array} \right] $$
or $n\times n$ in general, is there a quick way of finding the rank of this kind of matrix without using any row operations?
Thank you very much!

A: With this particularly special matrix, you can observe that if you look at a particular row $r$, then it is the average of row $r - i$ and row $r + i$ (provided $r - i \geq 1$ and $r + i \leq 5$, so that the rows we're talking about are actually there).  More generally, though not necessary, is that row $a$ + row $d$ = row $b$ + row $c$ for $1 \leq a \leq b \leq c \leq d \leq 5$ such that $a + d = b + c$.
This tells you that all the intermediate rows are linear combinations of the first and last row, which are visibly linearly independent since neither is a multiple of the other.  Hence, $\text{rank}(A) = 2$.


text:
Q: jQuery Mobile Switch to "page" thats already in dom with .changePage() Right now my DOM has three divs with data-roll="page", all of them have unique id's. If I use the following code it works but jQuery Mobile is creating a new node rather than switching to the already existing node.
$('div.ui-page').live("swipeleft", function(){
    var nextpage = $(this).next('div[data-role="page"]');
    // swipe using id of next page if exists
    if (nextpage.length > 0) {
        console.log(nextpage);
        $.mobile.changePage(nextpage.attr('id'), {transition: 'slide'});
    }
});

I have also tried passing just nextpage to the .chagePage method but when ever the pages have an id set I get the following error.
TypeError: b.split is not a function

So I'm looking to switch directly to the already existing "page" thats in the DOM rather than create a new one from my swipeleft handler.
I'm using jQuery 1.7.1 and jQuery Mobile 1.1.1

A: Have you tried passing-in a jQuery object rather than a string?
$(document).delegate('.ui-page', "swipeleft", function(){
    var $nextPage = $(this).next('[data-role="page"]');
    // swipe using id of next page if exists
    if ($nextPage.length > 0) {
        $.mobile.changePage($nextPage, { transition: 'slide' });
    }
}).delegate('.ui-page', "swiperight", function(){
    var $prevPage = $(this).prev('[data-role="page"]');
    // swipe using id of next page if exists
    if ($prevPage .length > 0) {
        $.mobile.changePage($prevPage, { transition: 'slide', reverse : true });
    }
});

Here is a demo: http://jsfiddle.net/V3CXF/
Otherwise I think you have to prepend a hash mark to your string ID to make it a valid selector:
$(document).delegate('.ui-page', "swipeleft", function(){
    var $nextPage = $(this).next('[data-role="page"]');
    // swipe using id of next page if exists
    if ($nextPage.length > 0) {
        $.mobile.changePage('#' + $nextPage[0].id, { transition: 'slide' });
    }
}).delegate('.ui-page', "swiperight", function(){
    var $prevPage = $(this).prev('[data-role="page"]');
    // swipe using id of next page if exists
    if ($prevPage .length > 0) {
        $.mobile.changePage('#' + $prevPage[0].id, { transition: 'slide', reverse : true });
    }
});

Here is a demo: http://jsfiddle.net/V3CXF/1/
Notice I swapped .live() out for .delegate() as .live is now depreciated (as of jQuery Core 1.7). If you are using jQuery Core 1.7 or newer, you can use .on() instead.
Docs for .live(): http://api.jquery.com/live


text:
Q: How can I simplify $\frac{\left (\sum x_{i} \right )}{\left ( \sum X_{i} \right ) \left (\sum x_{i}^2 \right )}$ How can I simplify
$$\frac{\left (\sum x_{i}  \right )}{\left ( \sum X_{i} \right ) \left (\sum x_{i}^2  \right )}$$
where $x_{i}=X_{i} - \bar{X}$ and $\bar{X}$ is the mean of all $X_{i}$'s
I thought of the following which, I must admit, looks wrong to me:
multiply the numerator and the denominator by $x_{i}$
$$\frac{\left (\sum x_{i} x_{i} \right )}{\left ( \sum X_{i} x_{i} \right ) \left (\sum x_{i}^2  \right )} = \frac{1}{\left (\sum X_{i}x_{i}  \right )}$$
Can anyone help me figure it out?

A: You can't just multiply by $x_i$ because in the summation is a "moving index", which means that $x_i$ represents actually many values (one value for each $i$), so in order to multiply by $x_i$ you'll have to fix a value for $i$, e.g. $i = i_0$ for which it's easy to see why $\sum_i {X_i x_{i_0}} \neq \sum_i x_i x_{i_0}$. That's why your approach seems wrong.
As @Paresseux Nguyen pointed out, the correct way to approach this is by noting that:
$$
\sum_i x_i = \sum_i X_i - \frac{n}{n} \sum_j X_j = 0
$$
I hope it helps :)


text:
Q: Directory select with Zenity How to use zenity to only allow the user to select certain directory.
my code works file to filter out certain files types
zenity --title "Pick The Software Folder " --file-selection  --file-  filter=""*.zip" "*.sql" "*.tgz"" --directory

I would like the code to only allow the user to be able to select certain directory's
 zenity --title "Pick The Software Folder " --file-selection  --file-  filter=""Download" "Home" "Desktop"" --directory

A: This seems to work for me:
zenity  --file-selection --title="Choose a directory" --file-filter=""Downloads" "Desktop"" --directory


text:
Q: How to calculate deltas between two numeric nodes in two different data structures in Python? I have a complicated data structure that is a roughly hierarchical dict, but with some lists thrown in a some levels (the serverStatus output of MongoDB)
How could I traverse the data structure of the current data sample and, whenever number is found at a certain point in the data structure, calculate the difference between that number, and the number from the same point in the data structure of the previous sample? (if it exists in the previous sample)
I was thinking about converting the data structure to {tag1.tag2.tag3... : value} then using tag1.tag2.tag3... as the key for doing the diffs.
Thanks in advance

A: Well, I'm sure there's a much more Pythonic way of doing this, but here's what I came up with.  This is a recursive function to convert a hierarchical Python dictionary into a single level dictionary with the key value being a string like ".key1.key2.key3"
# Convert MongoDB serverStatus() output from :
# {
#   "host" : "myserver",
#   "version" : "4.x.x",
#   "process" : "mongouser",
#   "pid" : NumberLong(5236),
#   "uptime" : 457766,
#   "uptimeMillis" : NumberLong(457767459),
#   "uptimeEstimate" : NumberLong(457767),
#   "localTime" : ISODate("2020-07-27T21:15:06.901Z"),
#   "asserts" : {
#                 "regular" : 0,
#                 "warning" : 0,
#                 "msg" : 0,
#                 "user" : 458,
#                 "rollovers" : 0
#          ..snip...
# to (numbers below aren't from the same sample)
# {
#   ".host": "myserver",
#   ".version": "4.x.x",
#   ".process": "mongouser",
#   ".pid": 5236,
#   ".uptime": 529644.0,
#   ".uptimeMillis": 529644987,
#   ".uptimeEstimate": 529644,
#   ".localTime": null,
#   ".asserts.regular": 0,
#   ".asserts.warning": 0,
#   ".asserts.msg": 0,
#   ".asserts.user": 458,
#   ".asserts.rollovers": 0,
#   ...snip...
#
def py_struct_to_dot_struct(py_struct,dot_struct,dot_struct_key=""):
  if( type(py_struct) in [dict] ):
      for key in py_struct:
          if( type(py_struct[key]) in [dict] ):
              py_struct_to_dot_struct( py_struct[key], dot_struct, dot_struct_key+"."+key )
          else:
              dot_struct[dot_struct_key+"."+key]=py_struct[key]

I could then just loop through the current sample py_struct by key1.key2... key string and calculate diffs vs the previous sample (if that key exists in the previous sample)
All feedback appreciated.


text:
Q: 2d Tree Nearest Neighbor Algorithm Clarification I am trying to implement a recursive nearest neighbour algorithm for a 2d-Tree.
Recursion (and unwinding recursion) is still kind of confusing for me and the best pseudocode I have found is from this StackOverflow question:
2D KD Tree and Nearest Neighbour Search
However the answer uses a "Median" value, which I am not sure how to compute. Also the wikipedia article on kd-trees has a nearest neighbour pseudo code that does not use a median value.
I would like to know if it is possible to construct a recursive version of the Nearest Neighbours algorithm without using a median value. If anyone can provide me with pseudo code for this I will be grateful.

A: If you are desperate in not using a median, you can use mean. Here, there is the simple approach:

Example 1: What is the Mean of these numbers?
6, 11, 7
Add the numbers: 6 + 11 + 7 = 24
Divide by how many numbers (there are 3 numbers): 24 / 3 = 8

The Mean is 8

However, I highly recommend you to go for the median, since the dimensions allow it in your case.

Example: find the Median of 12, 3 and 5
Put them in order:
3, 5, 12
The middle number is 5, so the median is 5.

Source
You do not really need to sort them. Pseudo-sorting is enough, be using Quickselect for example.
In C++ for example you could use use nth_element() to efficiently find the median. You can see my question here, where I needed the median for general dimensions. In the case of 2D, it can sure be simplified.


text:
Q: Regex for specific pattern ending with ) I have a big string, for example: "s#$_123 /HEC2w.,-&#--HALOENCRYPT(177ey7y37, 'zimba'),dnjekkq%12nnvHALOENCRYPT(ECRa12 _*,'grate'),eqn12&*;". I am looking to extract all the substrings with pattern "HALOENCRYPT(<Any_char_or_symbol_sequence>)" which means starting with 'HALOENCRYPT(' and ending immediately with ')' with any sequence between them. which has been marked Bold in the input sequence. I want to extract all such substrings and add to a list.
This is the program i wrote which works partially:
String s = "s#$_123 /HEC2w.,-&#--HALOENCRYPT(177ey7y37,     'zimba'),dnjekkq%12nnvHALOENCRYPT(ECRa12 _*,'grate'),eqn12&*;";
Matcher m = Pattern.compile("HALOENCRYPT[0-9a-zA-Z(,_ ')/-]+").matcher(s);
List<String> myList = new ArrayList<String>();
while (m.find()) {
    myList.add(m.group())
}

The above string is giving out extra characters after HALOENCRYPT(177ey7y37, 'zimba') and HALOENCRYPT(ECRa12 _*,'grate')
What i am expecting in the list is:
HALOENCRYPT(177ey7y37, 'zimba') and HALOENCRYPT(ECRa12 _*,'grate')
What i could not figure out is how to provide regex for ANYTHING between ( and )

A: Use a reluctant quantifier:
HALOENCRYPT\(.*?\)

And use the results() method to stream and collect the matches:
List<String> myList = Pattern.compile("HALOENCRYPT\\(.+?\\)").matcher(s).results()
  .map(MatchResult::group)
  .collect(Collectors.toList());

A: Instead of
HALOENCRYPT[0-9a-zA-Z(,_ ')/-]+

just do:
HALOENCRYPT\([0-9a-zA-Z,_ '/-]+\)


text:
Q: Get authenticated ClientContext with logged in credentials I'm new to using SharePoint. Is it possible to get an authenticated ClientContext without a username and password? I would like to make my app automatically access SharePoint if the machine is already logged in to Office 365 (word,excel,outlook) or to SharePoint in a web browser. I need the authenticated ClientContext so i can pass the credentials to a DownloadFile method.
Private Sub DownloadFile(webUrl As String, credentials As ICredentials, fileRelativeUrl As String)
    Using client = New WebClient()
        client.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
        client.Headers.Add("User-Agent: Other")
        client.Credentials = credentials
        client.DownloadFile(webUrl, fileRelativeUrl)
    End Using
End Sub

Thanks in advance.


text:
Q: PHP как FastCGI
За счет кэширования некоторых промежуточных данных скрипт не
  интерпретируется каждый раз при выполнении и достигается более высокая
  скорость по сравнению с PHP как CGI.

Вопрос: Как отключить это кэширование?
Пояснения: Это мне мешает работать над скриптом, изменяю его много много раз в минуту. И хочу видеть результат сразу после изменения.

A: Для FastCGI в файле конфигурации виртуальных хостов nginx или fastcgi.conf
fastcgi_cache  off;


text:
Q: Maven assembly create jar with dependencies and then create zip and tar.gz file I would like to do the following with the maven:

*

*Pack my code & dependencies to uber jar

*Attach a script to it (either Windows script or Linux script)

*Put both script and jar to a folder

*Crate zip for Windows AND tar.gz file for Linux

Is this possible in Maven using assembly or any other plugin?

A: i would split this into two projects and for convenience a parent module, like this:
projectX
|- codeproject
|- packingproject
\- pom.xml

codeproject:

*

*Nothing special here, just create your über-jar

packagingproject:

*

*save your scripts as src/main/resources/start.bat

*copy your codeproject.jar with copy-dependencies

*create your zip/tar-file with the maven-assembly-plugin
parent pom:

*

*also, nothing special, just add both modules

Note:
be sure to call install on your codeproject so that the jar gets copied to your local maven repository, otherwise you may end with a file not found or an old version of your code.


text:
Q: Unable to pass boolean in URL I have 2 pages, inputForm.xhtml and outputPage.xhtml.
In inputForm.xhtml, there are 1 textfield and 1 checkbox. When user clicks submit button, the values are passed to outputPage.xhtml in URL.
The value of textfield can be passed correctly. However, no matter the checkbox is checked or not, the parameter in URL is always false.
e.g. http://localhost:8080/jsf-web/outputPage.xhtml?c=false&n=franz
I am using myFaces 2.1.13. I really have no idea how to fix that. Thanks.
inputForm.xhtml

<f:metadata>
    <f:viewParam name="n" value="#{inputFormBean.name}" />
    <f:viewParam name="c" value="#{inputFormBean.nameUppercase}" />
</f:metadata>

<h:head>
</h:head>
<h:body>
    <h:form>

Name: <h:inputText value="#{inputFormBean.name}" />

Name uppercase: <h:selectBooleanCheckbox value="#{inputFormBean.nameUppercase}"/>

<h:commandButton action="output_page" value="Submit" />

    </h:form>
</h:body>

outputPage.xhtml

<f:metadata>
    <f:viewParam name="n" value="#{outputPageBean.name}" />
    <f:viewParam name="c" value="#{outputPageBean.nameUppercase}" />
</f:metadata>

<h:head>
</h:head>
<h:body>

Welcome #{outputPageBean.nameUppercase ? outputPageBean.name.toUpperCase() : outputPageBean.name}!!

</h:body>

faces-config.xml
<?xml version="1.0"?>
<faces-config xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-facesconfig_2_0.xsd"
    version="2.0">

    <navigation-rule>
        <from-view-id>*</from-view-id>
        <navigation-case>
            <from-outcome>output_page</from-outcome>
            <to-view-id>/outputPage.xhtml</to-view-id>
            <redirect include-view-params="true"/>
        </navigation-case>
    </navigation-rule>
</faces-config>

InputFormBean.java
package com.franzwong.jsfweb;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped
public class InputFormBean {
    private String name;
    private boolean nameUppercase;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public boolean isNameUppercase() {
        return nameUppercase;
    }
    public void setNameUppercase(boolean nameUppercase) {
        this.nameUppercase = nameUppercase;
    }
}

OutputPageBean.java
package com.franzwong.jsfweb;

import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;

@ManagedBean
@RequestScoped
public class OutputPageBean {
    private String name;
    private boolean nameUppercase;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public boolean isNameUppercase() {
        return nameUppercase;
    }
    public void setNameUppercase(boolean nameUppercase) {
        this.nameUppercase = nameUppercase;
    }
}

A: Finally I tried primitive int and it is passed as 0 no matter what value I input.
Therefore, I tried Boolean, Integer and found that the value I input can be passed correctly in URL.


text:
Q: Относительные пути в golang Есть такое дерево:
|-cmd
|   |-task
|       |-main.go
|
|-configs
|    |-config.yaml
|
|-pkg
    |-runner
         |-runner.go
         |-runner_test.go

В runner.go к config.yaml обращаюсь так: ../../configs/. И тесты runner_test.go проходят. Однако после билда создается бинарник в корне проекта, который после запуска выдает ошибку обращения к конфигу, потому что уходит на две директории назад от корня проекта. И если изменить обращение к конфигу в runner.go на ./configs/, тогда после билда всё успешно запустится, однако при тестировании возникнет ошибка обращения к конфигу.
Как правильно обращаться к конфигу?

A: ответ зависит от того, что вы используйте для чтения конфига.
одни из попульярных инструментов - это а .
На нем вы можете указать несколько путей к конфигу: как для тестов, так и для main app.
v := viper.New()
v.SetConfigName("config")
v.SetConfigType("yaml")
v.AddConfigPath(".")
v.AddConfigPath("./configs")

тогда у вас конфиг будет искаться как в текущей директории, так и в ./configs
p.s. лучше иметь возможность передать пусть к конфигу.

A: *

*Напишите вывод терминала. Не надо заставлять отвечающих догадываться что именно выводит компилятор.

*Если вы используете pkg, тогда необходимо использовать и internal (чисто логически).

*Как вы запускаете ваши тесты?