text:
Q: Problem clipping background to coreimage aztec generation with CIBlendWithMask I am trying to add an image background to a generated atec code so far I can get the aztec code to generate but am having trouble with the CIBlendWithMask filter, i'm not sure exactly what i'm doing wrong I believe the user selected background as kCIInputBackgroundImageKey is correct and the aztec output image as the kCIInputImageKey is correct, I think where i'm going wrong is the kCIInputMaskImageKey but not exactly sure why I need to do I thought the aztec output would be a sufficient mask image - do I need to select the color or something to get the background clipping to the aztec image?
        CIFilter *aztecFilter = [CIFilter filterWithName:@"CIAztecCodeGenerator"];
        CIFilter *colorFilter = [CIFilter filterWithName:@"CIFalseColor"];
        [aztecFilter setValue:stringData forKey:@"inputMessage"];

        [colorFilter setValue:aztecFilter.outputImage forKey:@"background"];

        NSData* imageData = [[NSUserDefaults standardUserDefaults] objectForKey:@"usertheme"];

        CIImage *image = [UIImage imageWithData:imageData].CIImage;

        [colorFilter setValue:[CIColor colorWithCGColor:[[UIColor blackColor] CGColor]] forKey:@"inputColor0"];
        [colorFilter setValue:[CIColor colorWithRed:1 green:1 blue:1 alpha:0] forKey:@"inputColor1"];

         CIFilter *blendFilter = [CIFilter filterWithName:@"CIBlendWithMask"];
         [blendFilter setValue:colorFilter.outputImage forKey:kCIInputImageKey];
         [blendFilter setValue:image forKey:kCIInputBackgroundImageKey];
         [blendFilter setValue:colorFilter.outputImage forKey:kCIInputMaskImageKey];

Trying to create something like this but for aztec codes instead of QR

A: You may be over-thinking this a bit...
You can use the CIBlendWithMask filter with only a background image and a mask image.
So, if we start with a gradient image (you may be generating it on-the-fly):

Then generate the Aztec Code image (yellow outline is just to show the frame):

We can use that code image as the mask.
Here is sample code:
- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor systemYellowColor];

    // create a vertical stack view
    UIStackView *sv = [UIStackView new];
    sv.axis = UILayoutConstraintAxisVertical;
    sv.spacing = 8;
    sv.translatesAutoresizingMaskIntoConstraints = NO;

    [self.view addSubview:sv];

    // add 3 image views to the stack view
    for (int i = 0; i < 3; ++i) {
        UIImageView *imgView = [UIImageView new];
        [sv addArrangedSubview:imgView];
        [imgView.widthAnchor constraintEqualToConstant:240].active = YES;
        [imgView.heightAnchor constraintEqualToAnchor:imgView.widthAnchor].active = YES;
    }

    [self.view addSubview:sv];
    [sv.centerXAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.centerXAnchor].active = YES;
    [sv.centerYAnchor constraintEqualToAnchor:self.view.safeAreaLayoutGuide.centerYAnchor].active = YES;

    // load a gradient image for the background
    UIImage *gradientImage = [UIImage imageNamed:@"bkgGradient"];

    // put it in the first image view
    ((UIImageView *)sv.arrangedSubviews[0]).image = gradientImage;

    // create aztec filter
    CIFilter *aztecFilter = [CIFilter filterWithName:@"CIAztecCodeGenerator"];

    // give it some string data
    NSString *qrString = @"My string to encode";
    NSData *stringData = [qrString dataUsingEncoding: NSUTF8StringEncoding];
    [aztecFilter setValue:stringData forKey:@"inputMessage"];

    // get the generated aztec image
    CIImage *aztecCodeImage = aztecFilter.outputImage;

    // scale it to match the background gradient image
    float scaleX = gradientImage.size.width / aztecCodeImage.extent.size.width;
    float scaleY = gradientImage.size.height / aztecCodeImage.extent.size.height;

    aztecCodeImage = [[aztecCodeImage imageBySamplingNearest] imageByApplyingTransform:CGAffineTransformMakeScale(scaleX, scaleY)];

    // convert to UIImage and set the middle image view
    UIImage *scaledCodeImage = [UIImage imageWithCIImage:aztecCodeImage scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];
    ((UIImageView *)sv.arrangedSubviews[1]).image = scaledCodeImage;

    // create a blend with mask filter
    CIFilter *blendFilter = [CIFilter filterWithName:@"CIBlendWithMask"];

    // set the background image
    CIImage *bkgInput = [CIImage imageWithCGImage:[gradientImage CGImage]];
    [blendFilter setValue:bkgInput forKey:kCIInputBackgroundImageKey];

    // set the mask image
    [blendFilter setValue:aztecCodeImage forKey:kCIInputMaskImageKey];

    // get the blended CIImage
    CIImage *output = [blendFilter outputImage];

    // convert to UIImage
    UIImage *blendedImage = [UIImage imageWithCIImage:output scale:[UIScreen mainScreen].scale orientation:UIImageOrientationUp];

    // set the bottom image view to the result
    ((UIImageView *)sv.arrangedSubviews[2]).image = blendedImage;

}

which produces:


text:
Q: 2 PlaceHolder inside Repeater - Hide/Show I am trying to hide PlaceHolder2 and show PlaceHolder1 - on click of linkButton. Both are insider repeater.
Aspx
<form id="form1" runat="server">
   <asp:Repeater ID="rptOnly" runat="server">
         <ItemTemplate>
              <asp:PlaceHolder ID="PlaceHolder1" runat="server" Visible="False">
                      //Display some images
              </asp:PlaceHolder>
              <asp:PlaceHolder ID="PlaceHolder2" runat="server">
                   <asp:linkbutton runat="server" id="lnkbtn" text="Click Here" OnClick="Myfunction_Click" />
              </asp:PlaceHolder>
         </ItemTemplate>
   </asp:Repeater>
</form>

VB.net
Protected Sub Myfunction_Click(sender As Object, e As EventArgs)
    PlaceHolder1.Visible = True
    PlaceHolder2.Visible = False
End Sub

A: The repeater has a collection of items - You need to check each item in the collection:
For Each c As Control in rptOnly.Items

    Dim p1 As Control = c.FindControl("PlaceHolder1")
    Dim p2 As Control = c.FindControl("PlaceHolder2")

    If p1 IsNot Nothing Then
        p1.Visible = True
    End If
    If p2 IsNot Nothing Then
        p2.Visible = False
    End If
Next

Each item is a RepeaterItem: http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeateritem_methods(v=vs.110).aspx
In Myfunction_Click you should be able to find the placeholder as the control parent - something like this (you might need to cast the Parent object):
Protected Sub Myfunction_Click(sender As Object, e As EventArgs)
    sender.Parent.Visible = True
    sender.Parent.Visible = False
End Sub

A: Use FindControl from the RepeaterItem (as there could be multiple items in the Repeater) and then set the visibility.
EX for First Item in Repeater =
CType(rptOnly.Items(0).FindControl("PlaceHolder1"), PlaceHolder).Visible = True
CType(rptOnly.Items(0).FindControl("PlaceHolder2"), PlaceHolder).Visible = False

For all items in the repeater, do a For Each RPI as RepeaterItem in rptOnly.Items and do the same thing.
Edit from Comments:
Your particular issue would have you set the CommandName Property of your Button, which is also within the ItemTemplate, and change the visibility of the PlaceHolders in the ItemCommand Event of the Repeater.
CType(e.Item.FindControl("PlaceHolder1"), PlaceHolder).Visible = True

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to get the path information from a Node in TRzShellTree? In a 32-bit VCL Application in Windows 10 in Delphi 11 Alexandria, I have a TRzShellTree control (by Ray Konopka from the popular Konopka Signature VCL Controls 7.0 available in GetIt).
I iterate through the nodes of the TRzShellTree control to append some specific information to each Node's text, retrieved from the Node's folder path :
for Node in RzShellTree1.Items do
begin
  //Node.FullPath? How to get the FULL PATH of the Node?
  Node.Text := Node.Text + GetNodeInfoFromNodePath(Node);
end;

However, I need the full path from each Node to get that information. Looking at the TRzShellTree methods, there seems to be no way to get a node's full path.
So how can I get the full path from each Node?

A: There IS a method to get the RELATIVE path from a Node:
var RelativePath := RzShellTree1.PathFromNode(Node);

You then could easily get the full path for each node by extracting the BaseFolder path from the RzShellTree1.BaseFolder property. But how to do that? The TRzShellTree.BaseFolder property is of type TRzShellLocator. You then can concatenate the path from RzShellTree1.BaseFolder.PathName with the RelativePath variable to get the Node's full path:
var ThisBasePath := System.SysUtils.IncludeTrailingPathDelimiter(ExtractFilePath(RzShellTree1.BaseFolder.PathName));
for Node in RzShellTree1.Items do
begin
  var ThisNodeRelativePath := RzShellTree1.PathFromNode(Node);
  var ThisNodeFullPath := ThisBasePath + ThisNodeRelativePath;
  if System.SysUtils.DirectoryExists(ThisNodeFullPath) then
    CodeSite.Send('ThisNodeFullPath', ThisNodeFullPath);
end;

However, if you change the Node.Text inside this Loop, then nested subfolders in the tree will be excluded from the DirectoryExists condition because TRzShellTree obviously calculates PathFromNode from the nodes down the tree. In this case, it is better to use a downwards loop:
for var i := RzShellTree1.Items.Count - 1 downto 1 do

A: I'm not quite sure what you are trying to accomplish by modifying the node text for each file. The TRzShellTree (and TRzShellList) controls provide access to the Windows Shell space. The nodes represent the items in that space. It almost sounds like you want to have a standard tree view control that you just populate with the files from a specified directory. You may have better luck using the System.IOUtils functionality to iterate over the files you are interested and populating the tree view manually. Then you would be able to populate each node the way you want. The TRzShellTree (and TRzShellList) are designed to mimic the functionality of Windows Explorer and provide the file operations supported in those controls.


text:
Q: Is there any optimal time to check ipfs-hash exist or not? ipfs object stat:

'ipfs object stat' is a plumbing command to print DAG node statistics.
 is a base58 encoded multihash.

If given hash is valid, it returns some information (if and only if shared node's ipfs daemon is on).
$ ipfs object stat QmNd4PHGU8Z7fwbEvps5jvVscCDd5husnNgKpaDCfm1tpt
NumLinks: 0
BlockSize: 39
LinksSize: 2
DataSize: 37
CumulativeSize: 39

Now I try it with an invalid hash or node (which shares the ipfsHash)'s ipfs daemon is off: I observe that the command halts.
$ ipfs object stat QmNd4PHGU8Z7fwbEvps5jvVscCDd5husnNgKpaDCfm1t88 #invalid hash
#waits.

If I enter an invalid has into ipfs object stat it pauses. I can do timeout N to terminate it: But I am not sure how long should I wait.
timeout 30 ipfs object stat QmNd4PHGU8Z7fwbEvps5jvVscCDd5husnNgKpaDCfm1t88

Overall, I just want to check does given ipfs-hash exists for me to retrieve its information.
[Q] Is there any optimal time for me to wait until ipfs object stat <ipfsHash> returns a valid value or not? Would around 30 seconds to wait be enough?
Please note that:  I tried between node in Europe and node in States, it took around 120 seconds on first try. But after I assume a path route is generated between those nodes, my next try with different hash between same nodes takes less than a second. What might be the reason for this?
Thank you for your valuable time and help.

A: Not 100% sure what would cause a delay like that, but there have been a lot of improvements to the DHT since 2017 I'd imagine. What's happening is your node is effectively looking and asking around "who has this CID?". Once it finds who has the CID, it retrieves it from that node directly p2p (or using p2p-circuit).
I don't think there is a perfect "optimal time", so you'd have to decide what feels acceptable to you I suppose. By the sounds of it 150-180 seconds should be somewhat reasonable if you're expecting delays up to "around 120 seconds". In 2021 I rarely run into big delays like this, but it's not completely unheard of if the data is only on a node with a restrictive NAT for example. I personally usually give up around the 30s mark, but if I'm relatively sure the data is difficult to retrieve, I'll sometimes leave it try indefinitely until I eventually get the data I'm looking for.
As for why it's so fast after for retrievals from the same node, you've either now peered with them (likely), or another node that's peered with them retrieved their data and has it in their cache (like a gateway for example). So your node is probably aware of them and likely the CIDs they claim to have, so it's able to find and retrieve the data much quicker.


text:
Q: What is the role of the "generating server" and/or "Reporting-MTA" in an Exchange NDR? I'm a little confused on what exactly the "generating server" does in an NDR.
For example, I got the following NDR back when sending to a specific domain:
Diagnostic information for administrators:
Generating server: example.foo.com

recipient@foo.com
#< #5.1.1> #SMTP#

Is the "generating server" the MTA that was the last hop to successfully accept the message and tried to deliver the message at the time of the error? Or is the "generating server" the server that gave back the 5.1.1 error (and did NOT accept the message)?
I also noticed the following:
Reporting-MTA: dns;
example.foo.com
Final-recipient: RFC822; recipient@foo.com
Action: failed Status: 5.1.1
X-Supplementary-Info: < #5.1.1>

A: The generating server is the server that gave back the 5.1.1
5.1.1 > Is in the bad-address failure category, meaning the server received the message, did an internal lookup and couldnt find a mailbox to deliver to and generated an NDR.
A detailed explanation is given here:
http://technet.microsoft.com/en-us/library/bb232118.aspx


text:
Q: Android SurfaceView different than saved image I am creating a custom camera, in which I have 2 more bugs to fix before its finished. I'm here seeking help with 1 of them.
I am trying to create a square preview (SurfaceView) and save that square to file. The only way I've been able to accomplish this is with a custom View, seen here:
public class SquareSurfaceView extends SurfaceView {

    private int width;
    private int height;

    public SquareSurfaceView(Context context) {
        super(context);
    }

    public SquareSurfaceView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public SquareSurfaceView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        width = MeasureSpec.getSize(widthMeasureSpec);
        setMeasuredDimension(width, width);
    }

    public int getViewWidth() {
        return width;
    }

    public int getViewHeight() {
        return height;
    }
}

The problem I'm having is that the image on the preview and the saved image are a bit off. The saved image shows more from the top of the image.. So, lets say I take a picture of a door, and I align the top of the preview with the top of the door, take the photo, the image that gets saved, shows what I would equate to be about 30dp MORE image, showing stuff above the door that the preview didnt show.
The code I used to crop the image is below:
SimpleDateFormat sdf = new SimpleDateFormat(
        "yyyyMMdd_HHmmss", Locale.US);
mLastPhotoFilename = "IMG_" + sdf.format(new Date())
        + ".jpg";

// cropped file
File photoFile = new File(photoStoragePath,
        mLastPhotoFilename);

// gallery file
File galleryFile = new File(galleryStoragePath,
        mLastPhotoFilename);

// write the cropped file
mLastPhoto
        .compress(
                CompressFormat.JPEG,
                95,
                new FileOutputStream(galleryFile
                        .getAbsolutePath()));

// resize the bitmap
Bitmap scaledPhoto = Bitmap.createBitmap(mLastPhoto, 0, 0,
        mLastPhoto.getWidth(), mLastPhoto.getWidth());

// write the cropped file
scaledPhoto.compress(CompressFormat.JPEG, 95,
        new FileOutputStream(photoFile.getAbsolutePath()));

I save the full image to the phones gallery, resize the image, and store the resized to my apps directory.
So, why does my preview not show what the camera sees, and is saving? How can I get the top of my preview, to be what the top of the camera is seeing?


text:
Q: Invalid Post: 400 - Bad Request with Python requests I'm using PoliteMail's ODATA RESTful API (Doc: PoliteMail API Entity Directory)
I'm trying to create a Contact inside of PoliteMail with requests.post().
Below are my steps
Load Libraries
import requests
import json

# point to credentials
import os
import yaml
myKeys = yaml.load(open(os.path.join(os.path.expanduser('~'), 'Documents\keyfile2.json')))

Authentication Creds
user = myKeys['PoliteMail'][1]['user']
password = myKeys['PoliteMail'][1]['password']
auth = requests.auth.HTTPBasicAuth(user, password)

base_url = 'https://comm.microsoft.com/ssv3/odata/'
entity = 'Lists'
url = base_url+entity

GET request
r = requests.get(url+'(56)', auth=auth)
print(r.status_code) # '200'

I can GET anything within this entity, but can't post.
POST request
Below is the structure given in the documentation
payload = {
"ID":"0",
"Name":"Test List",
"Description":"Does this work",
"IsNewsletter":"0",
"Shared":False,
"CreationDate":"2014-11-19T23:00:00.000Z",
"ActiveState":"1",
"isAnonymous":False,
"BusinessID":"0",
"RegionID":"0"
}

My request:
r = requests.post(url, data=json.dumps(payload),auth=auth)

It's output

415: The request contains an entity body but no Content-Type header. The inferred media type 'application/octet-stream' is not supported for this resource."

But when I add a header for content type:
r = requests.post(url, data=json.dumps(payload),auth=auth,
                     headers = {"Content-Type": "application/json"})

I'm told:

400 "The request is invalid." An error has occurred.\r\n","type":"","stacktrace":""

I've tried the following, to no avail:

*

*json= instead of data=

*removing quotes from num

*changing the ID value to something other than 0

*removing newline characters from the payload

Any help is much appreciated!
Update
The errors are coming from the parsed text of the response below is the full response readout when I use BeautifulSoup
{
  "odata.error":{
    "code":"","message":{
      "lang":"en-US","value":"The request is invalid."
    },"innererror":{
      "message":"contact : An error has occurred.\r\n","type":"","stacktrace":""
    }
  }
}

A: I was able to create a list with your sample by fixing the capitalization of False to false and isAnonymous to IsAnonymous in the payload.
{
    "ID":"0",
    "Name":"Test List",
    "Description":"Does this work",
    "IsNewsletter":"0",
    "Shared":false,
    "CreationDate":"2014-11-19T23:00:00.000Z",
    "ActiveState":"1",
    "IsAnonymous":false,
    "BusinessID":"0",
    "RegionID":"0"
}

You also mentioned creating a Contact at the beginning of your post. I was able to successfully create a Contact with the following.
{
      "DisplayName": "Test Test",
      "FirstName": "Test",
      "LastName": "Test",
      "Email": "test@politemail.com",
      "ActiveState": true,
      "CreationDate": "2017-09-12T0:49:23.303Z",
      "Shared": false,
      "OwnerID": 0,
      "CategoryID": 8,
      "StageID": 1,
      "Company": "",
      "WebAddress": "",
      "Title": "",
      "FileAs": "Test Test",
      "Source": 0,
      "Notes": "",
      "Custom1": "",
      "Custom2": "",
      "Custom3": "",
      "Custom4": "",
      "Custom5": "",
      "Custom6": "",
      "Custom7": "",
      "Custom8": "",
      "Custom9": "",
      "Custom10": "",
      "Custom11": "",
      "Custom12": "",
      "Custom13": "",
      "Custom14": "",
      "Custom15": "",
      "Custom16": "",
      "Custom17": "",
      "Custom18": "",
      "Custom19": "",
      "Custom20": "",
      "BusinessID": 0,
      "RegionID": 0,
      "LastChangedDate": "2017-09-12T20:49:23.303Z",
      "ListID": null
    }

I work at PoliteMail and have made an internal request to get the documentation updated to fix the capitalization of IsAnonymous.

UPDATE: The documentation has been updated with the correct capitalization. http://kb.politemail.com/?p=1349

A: From the error log, server side may not handle the line break \r\n.
Can you try to remove the line break of your payload?
payload = {"ID":"0","Name":"Test List","Description":"Does this work","IsNewsletter":"0","Shared":False, "CreationDate":"2014-11-19T23:00:00.000Z","ActiveState":"1","isAnonymous":False,"BusinessID":"0","RegionID":"0"}


text:
Q: cannot invoke join(string) on string[] I am doing an project where I have to translate English into an another fictional language for an exercise. I have split the sentence into an array and has pushed that array through an if statement into another array, however when I try to do sentence.join(" ") I get the error cannot invoke join(string) on the array type string[]. Bellow is all of my code
import java.lang.reflect.Array;
import java.util.Arrays;
import java.util.Scanner;
import java.util.regex.*;

public class piglatin {

public static void main(String[] args) {

    System.out.println("welcome to the pig latin translator!");

    //declares the variable
    Scanner input = new Scanner(System.in);
    System.out.print("Input: ");
    String userin = input.nextLine(); // takes in raw user inpu
    String[] word = userin.split("[\\p{Punct}\\s]+");
    String[] sentence = new String[userin.length()];

    //consonats: bcdfgjklmnpqstvxzhrwy / B, C, D, F, G, J, K, L, M, N, P, Q, S, T, V, X, Z and often H, R, W, Y.
    //vowels aeiou pissibly y and w

    for(int i = 0; i < word.length; i++){

        if(word[i].length() > 1 && word[i]!= " "){
            String firstletter = word[i].substring(0, 1);// gets the 1st letter of the word that the user has inputed
            String secletter = word[i].substring(1, 2);// gets the 1st 2 letter olof the word that the user has inputed
            int InLength = word[i].length();
            if((firstletter.toLowerCase().matches(".*[bcdfgjklmnpqstvxzhrwy].*") && (secletter.toLowerCase().matches(".*[aeiou].*")) && word[i].length()> 1)){

                String restofword1 = word[i].substring(1, InLength);
                String wordfinal = restofword1 + firstletter + "ay";
                sentence[i] = wordfinal;

            }if((firstletter.toLowerCase().matches(".*[bcdfgjklmnpqstvxzhrwy].*") & (secletter.toLowerCase().matches(".*[bcdfgjklmnpqstvxzhrwy].*"))&& word[i].length()> 1)) {

                String restofword2 = word[i].substring(2, InLength);
                String wordfinal2 = restofword2 + firstletter + secletter + "ay";
                sentence[i] = wordfinal2;

            }if(firstletter.toLowerCase().matches(".*[aeiou].*")) {

                String wordfinal3 = word[i] + "way";
                sentence[i] = wordfinal3;
                System. out. println();//removes the % sign at the end of the print statment

            }if(word[i]==null){
                break;
            }
        }

    }
    String finished = sentence.join(" ");
    input.close();
    }

}

do you know how I can fix this?

A: You can't call methods that don't exist. There is no 'join' that is a member of a String[] and which takes a single String argument.
What you want is the static 'join' method of the String class.
The signature of String.join is
public static String join(CharSequence delimiter,
                          CharSequence... elements)

which means your call needs to be
finished = String.join(" ", sentence);

When in doubt, read the documentation!


text:
Q: "Error: Could not find or load main class" - Visibility exception I have the following code, which needs to be run by the HackerRank automated validator.
package stringrev;

import java.util.Scanner;

class str {
  public static void main(String[] args) {
    Scanner in=new Scanner(System.in);
    int k=in.nextInt()+1;
    for(int i=0;i<=k;i++)
    {
      StringBuffer a=new StringBuffer(in.nextLine());
      StringBuffer b=a.reverse();
      System.out.println(b);
    }
  }
}

This code is working fine on my compiler but while uploading to Hacker Rank it shows an error:

Error: Could not find or load main class str

What does that mean?

A: HackerRank, as well as other automated websites, will take your code snippet and run it inside of another program (the automated validator).
The error you are getting is due to the fact that the validator tries to compile / access your code from within his code. Unfortunately, you have setup the visibility of your Str class to be default, which is not public!
If you change your code to:
public class str {...}

It should work. Also check that the name of the class is correct (it's unlikely that they ask you to have a lowercase class name).

A: This error might happen if you add the package of the class, when you're copying the code from your editor to the  Hacker Rank. As an example, I had this error,
package hackerrank.RoadTransformation;

import java.util.*;

public class Solution{
...
    }

I removed the package hackerrank.RoadTransformation; part and the error was gone.


text:
Q: Adding a object randomly on the screen in as3 OK, so i am having trouble with adding a box randomly on the screen. I have done this before and it seems like it should have a relatively easy solution. But alas, i have not been able to figure this out. This is the info:
I have a box mc with exporting as Box.
I have a Box Actionscript file with this code in it:
package {
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;
public class Box extends MovieClip {

    public function Box() {
        createBox();

    }

    private function createBox():void {

        var _box:Box = new Box();
        _box.x = Math.random()*stage.stageWidth ;
        _box.y = Math.random()*stage.stageHeight;
        stage.addChild(_box);

    }
}
}

Nothing happens at all but there is no errors. Also i would like to keep everything in the classes.

A: There is a thing  in your code because of that code is not working:
1)  when you are using class as a Document class then the class name should be unique      i.e   name of Document class is not associated with any library symbols.
package
{
    import flash.display.MovieClip;
    import flash.events.Event;
    import flash.events.MouseEvent;

    public class Main extends MovieClip
    {
        private var _box:Box = new Box();

        public function Main()
        {
            createBox();
        }

        private function createBox():void
        {
            trace(Math.random()*stage.stageWidth)
            _box.x = Math.random()*stage.stageWidth ;
            _box.y = Math.random()*stage.stageHeight;
            stage.addChild(_box);
        }
    }
}


text:
Q: IBasicVideo CetCurrentImage catastrophic failure(DirectShow.NET) I'm trying to grab image from webcam using DirectShow.NET and IBasicVideo CetCurrentImage. But I only get catastrophic failure on second call GetCurrentImage.
What I'm doing particularly:

IBasicVideo bv = (IBasicVideo)graph;
IntPtr bvp = new IntPtr();
int size = 0;
int hr = bv.GetCurrentImage(ref size, IntPtr.Zero);
DsError.ThrowExceptionForHR(hr);
bvp = Marshal.AllocCoTaskMem(size);
hr = bv.GetCurrentImage(ref size, bvp);
DsError.ThrowExceptionForHR(hr);
Bitmap image = new Bitmap(480, 320, 480 * (24 / 8), System.Drawing.Imaging.PixelFormat.Format24bppRgb, bvp);
image.Save(path);

What am I doing wrong?
Prety much all I have:
IGraphBuilder graph = null;
IMediaEventEx eventEx = null;
IMediaControl control = null;
ICaptureGraphBuilder2 capture = null;
IBaseFilter srcFilter = null;
public IVideoWindow videoWindow = null;
IntPtr videoWindowHandle = IntPtr.Zero;

public void GetPreviewFromCam()
{
    graph = (IGraphBuilder)(new FilterGraph());
    capture = (ICaptureGraphBuilder2)(new CaptureGraphBuilder2());
    eventEx = (IMediaEventEx)graph;
    control = (IMediaControl)graph;
    videoWindow = (IVideoWindow)graph;
    videoWindowHandle = hVideoWindow;
    eventEx.SetNotifyWindow(hVideoWindow, WM_GRAPHNOTIFY, IntPtr.Zero);

    int hr;

    // Attach the filter graph to the capture graph
    hr = capture.SetFiltergraph(graph);
    DsError.ThrowExceptionForHR(hr);

    // Find capture device and bind it to srcFilter
    FindCaptureDevice();

    // Add Capture filter to our graph.
    hr = graph.AddFilter(srcFilter, "Video Capture");
    DsError.ThrowExceptionForHR(hr);

    // Render the preview pin on the video capture filter
    // Use this instead of graph->RenderFile
    hr = capture.RenderStream(PinCategory.Preview, MediaType.Video, srcFilter, null, null);
    DsError.ThrowExceptionForHR(hr);

    hr = control.Run();
    DsError.ThrowExceptionForHR(hr);
}

A: IBasicVideo::GetCurrentImage does not have to unconditionally succeed. What it does is forwarding of the call to video renderer in your graph (fails if you don't have one, or you have a weird non-renderer filter which unexpectedly implements the interface), then the renderer would attempt to get you the image. The renderer might fail if it is operating in incompatible mode (windowless video renderers don't have IBasicVideo - might fail here), or the renderer yet did not receive any video frame to have a copy delivered to you, that is the call is premature.
Additionally, there might be a handful of other issues related to obvious bugs - you did not put the graph into active mode, you are under wrong impression about topology you are having, you are using wrong interface, your code has threading issues etc.
With a specter of possibly causes this wide, start with a simple question: at the time of the call, do you have the video frame already presented to you visually?


text:
Q: E/zzf: Problem retrieving SafetyNet Token: 7: Android I have this error:
E/zzf: Problem retrieving SafetyNet Token: 7:

I am working on AndroidStudio with kotlin, the main problem is there is a captcha coming on everytime a I try to login via firebase phone auth.
Things done:

*

*Added all keys in the firebase project (SHA-1, SHA-256 -- both debug and release)

*Enabled Android Device Verification

And when implementation androidx.browser:browser:1.2.0 is removed, the following error shows up.
java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/browser/customtabs/CustomTabsIntent$Builder;
I concluded, if E/zzf: Problem retrieving SafetyNet Token: 7: error is solved, all the other errors will be solved automatically.

A: Based upon error code 7 and your attempts so far, the client appears to be out-of-sync with the back-end. Make sure to download the current google-services.json and overwrite the existing one file in your project; then build again and it should work out. If it doesn't, also delete all build directories and Gradle caches. Hope that my common sense will count as "reputable source", because this is not really documented anywhere, except the default setup instructions.
I've even found some "reputable source":

Make sure that you only have this most recent downloaded config file in your app.

A: Register your App from the Firebase console for SafetyNet
Follow these steps

*

*Open Firebase console

*Navigate to project settings

*Navigate to App Check and found Your apps section

*Click on your App and add SafetyNet

*Add SHA-256 certificate fingerprint

A: In Kotlin, I Solving this Error By Adding SHA-1 Key into the Firebase. Then after All the Errors are solved.

*

*Open Android Studio

*Select Gradle in Android Studio from right Panel.

*Select Your App.

*In Tasks -> android-> click on signing Report
It Will Automatic Generate SHA-1 Key.Add SHA-1 In Firebase Project Setting.

And Also I Add setActivity(this.requireActivity()) in sendVerificationCode() function.
`private fun sendVerificationCode(number: String) {

    val options = PhoneAuthOptions.newBuilder(mAuth)
        .setPhoneNumber(number)
        .setTimeout(10L,TimeUnit.SECONDS)
        .setActivity(this.requireActivity())
        .setCallbacks(callback)
        .build()

    PhoneAuthProvider.verifyPhoneNumber(options)
}`


text:
Q: Old Camera API - what causes unlock() to fail? I'm working on recording video segments using the MediaRecorderAPI, and I'm using the deprecated Camera API. The code looks like this:
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private boolean prepareVideoRecorder() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        CameraManager manager = (CameraManager) getActivity().getSystemService(Context.CAMERA_SERVICE);
        try {
            CameraCharacteristics characteristics = manager.getCameraCharacteristics("" + currentCameraId);
            mSensorOrientation = characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
        } catch (CameraAccessException e) {
            e.printStackTrace();
        }
    }

    mMediaRecorder = new MediaRecorder();
    mCamera.unlock();
    mMediaRecorder.setCamera(mCamera);

    mMediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
    mMediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && mSensorOrientation != null) {
        int rotation = getActivity().getWindowManager().getDefaultDisplay().getRotation();
        switch (mSensorOrientation) {
            case SENSOR_ORIENTATION_DEFAULT_DEGREES:
                mMediaRecorder.setOrientationHint(DEFAULT_ORIENTATIONS.get(rotation));
                break;
            case SENSOR_ORIENTATION_INVERSE_DEGREES:
                mMediaRecorder.setOrientationHint(INVERSE_ORIENTATIONS.get(rotation));
                break;
        }
    } else {
        if (currentCameraId == 0) {
            mMediaRecorder.setOrientationHint(90);
        } else {
            mMediaRecorder.setOrientationHint(270);
        }
    }

    mMediaRecorder.setMaxDuration(MAX_DURATION_VIDEO);
    mMediaRecorder.setProfile(CamcorderProfile.get(currentCameraId, CamcorderProfile.QUALITY_HIGH));
    mMediaRecorder.setVideoSize(1280, 720);
    outputFile = VideoUtils.getOutputMediaFile(Constant.MEDIA_TYPE_VIDEO);
    mFileObserver = new MyFileObserver(outputFile.toString(), FileObserver.ALL_EVENTS);
    mMediaRecorder.setOutputFile(outputFile.toString());
    mListUri.add(VideoUtils.getOutputMediaFileUri(Constant.MEDIA_TYPE_VIDEO));
    mMediaRecorder.setVideoFrameRate(30);
    mMediaRecorder.setPreviewDisplay(mPreview.getHolder().getSurface());

    try {
        mMediaRecorder.prepare();
    } catch (IllegalStateException e) {
        Log.d(TAG,
                "IllegalStateException preparing MediaRecorder: "
                        + e.getMessage());
        releaseMediaRecorder();
        return false;
    } catch (IOException e) {
        Log.d(TAG, "IOException preparing MediaRecorder: " + e.getMessage());
        releaseMediaRecorder();
        return false;
    }
    return true;
}

This works on most devices. However, there are some others in which mCamera.unlock() will occasionally throw a RuntimeException: unlock failed.
I dug into the source code and saw this:
static void android_hardware_Camera_unlock(JNIEnv *env, jobject thiz)
{
    ALOGV("unlock");
    sp<Camera> camera = get_native_camera(env, thiz, NULL);
    if (camera == 0) return;
    if (camera->unlock() != NO_ERROR) {
        jniThrowRuntimeException(env, "unlock failed");
    }
}

Which I presume is the code that is executed when mCamera.unlock() is called.
My question is, if this really is the code to unlock the camera, what can cause camera->unlock() to return something other than NO_ERROR?


text:
Q: Error related to constructor calling. and passing of parameters I have trying to make custom layout manager for my recyclerview in android. by the name CustomLinearLayoutManager. and trying to calling constructor and class of this into my home fragment. but failed. and getting some errors.
CustomLinearLayoutManager class
public class CustomLinearLayoutManager extends LinearLayoutManager {

    public CustomLinearLayoutManager (Context context) {
        super(context);
    }

    public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public CustomLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
        final LinearSmoothScroller linearSmoothScroller =
                new LinearSmoothScroller(recyclerView.getContext()) {
                    private static final float MILLISECONDS_PER_INCH = 200f;

                    @Override
                    public PointF computeScrollVectorForPosition(int targetPosition) {
                        return CustomLinearLayoutManager.this
                                .computeScrollVectorForPosition(targetPosition);
                    }

                    @Override
                    protected float calculateSpeedPerPixel
                            (DisplayMetrics displayMetrics) {
                        return MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
                    }
                };
        linearSmoothScroller.setTargetPosition(position);
        startSmoothScroll(linearSmoothScroller);
    }
}

Home Fragment
CustomLinearLayoutManager customLinearLayoutManager = new CustomLinearLayoutManager(getContext());
        customLinearLayoutManager.smoothScrollToPosition();
recyclerViewHeaderSlider = view.findViewById(R.id.bannerSlider);
            SnapHelper snapHelper = new PagerSnapHelper();
            snapHelper.attachToRecyclerView(recyclerViewHeaderSlider);
            recyclerViewHeaderSlider.setHasFixedSize(true);
            recyclerViewHeaderSlider.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
            headerSliderAdapter.setOnClick(this);
            recyclerViewHeaderSlider.setAdapter(headerSliderAdapter);

Errors which i am facing..
public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }
Error: Constructor 'CustomLinearLayoutManager(android.content.Context, int, boolean)' is never used
public CustomLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
    }
 Error: Constructor 'CustomLinearLayoutManager(android.content.Context, android.util.AttributeSet, int, int)' is never used

In Home Fragment:
customLinearLayoutManager.smoothScrollToPosition();
Error: smoothScrollToPosition() in CustomLinearLayoutManager cannot be
applied to:
Expected Parameters:     Actual Arguments:
recyclerView:               RecyclerView
state:                         State
position:                       int

A: Firs, if you defined those constructors and you are not using them then this:

Error: Constructor 'CustomLinearLayoutManager(android.content.Context, android.util.AttributeSet, int, int)' is never used

This is not an error in all. This is an warning since it is never used.
Second, if you call a method, please make sure that the parameters are added properly else then this message is displayed.

Error: smoothScrollToPosition() in CustomLinearLayoutManager cannot be applied to: Expected Parameters: Actual Arguments:

Then you should call this method smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) by adding:
First parameter : an object as RecyclerView
Second parameter: an enum  as RecyclerView.State
Third parameter : a position as integer


text:
Q: Android room migration null error When i'm doing migration on Android from old sqlite way to Room i need to use "INTEGER NOT NULL" to compile.
The problem is that when migration is happening you are inserting NULL field in the new table with "NOT NULL" parameters and I'm getting error
android.database.sqlite.SQLiteConstraintException: NOT NULL constraint failed: note.notification_state (code 1299)
Edit:
11-29 22:52:58.891 14605-14630/com.aleksandarvasilevski.notes E/AndroidRuntime: FATAL EXCEPTION: pool-1-thread-1
                                                                            Process: com.aleksandarvasilevski.notes, PID: 14605
                                                                            java.lang.IllegalStateException: Migration didn't properly handle note(com.aleksandarvasilevski.notes.repository.db.Note).
                                                                             Expected:
                                                                            TableInfo{name='note', columns={notification_date=Column{name='notification_date', type='TEXT', notNull=false, primaryKeyPosition=0}, priority=Column{name='priority', type='INTEGER', notNull=true, primaryKeyPosition=0}, description=Column{name='description', type='TEXT', notNull=false, primaryKeyPosition=0}, title=Column{name='title', type='TEXT', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', notNull=true, primaryKeyPosition=1}, notification_state=Column{name='notification_state', type='INTEGER', notNull=true, primaryKeyPosition=0}, created_date=Column{name='created_date', type='TEXT', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}
                                                                             Found:
                                                                            TableInfo{name='note', columns={notification_date=Column{name='notification_date', type='TEXT', notNull=false, primaryKeyPosition=0}, priority=Column{name='priority', type='INTEGER', notNull=false, primaryKeyPosition=0}, title=Column{name='title', type='TEXT', notNull=false, primaryKeyPosition=0}, description=Column{name='description', type='TEXT', notNull=false, primaryKeyPosition=0}, id=Column{name='id', type='INTEGER', notNull=true, primaryKeyPosition=1}, notification_state=Column{name='notification_state', type='INTEGER', notNull=false, primaryKeyPosition=0}, created_date=Column{name='created_date', type='TEXT', notNull=false, primaryKeyPosition=0}}, foreignKeys=[], indices=[]}
                                                                                at com.aleksandarvasilevski.notes.repository.db.NoteDatabase_Impl$1.validateMigration(NoteDatabase_Impl.java:70)
                                                                                at android.arch.persistence.room.RoomOpenHelper.onUpgrade(RoomOpenHelper.java:75)
                                                                                at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.onUpgrade(FrameworkSQLiteOpenHelper.java:118)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:256)
                                                                                at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:163)
                                                                                at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper$OpenHelper.getWritableSupportDatabase(FrameworkSQLiteOpenHelper.java:93)
                                                                                at android.arch.persistence.db.framework.FrameworkSQLiteOpenHelper.getWritableDatabase(FrameworkSQLiteOpenHelper.java:54)
                                                                                at android.arch.persistence.room.RoomDatabase.query(RoomDatabase.java:193)
                                                                                at com.aleksandarvasilevski.notes.repository.db.NoteDao_Impl$5.compute(NoteDao_Impl.java:195)
                                                                                at com.aleksandarvasilevski.notes.repository.db.NoteDao_Impl$5.compute(NoteDao_Impl.java:181)
                                                                                at android.arch.lifecycle.ComputableLiveData$2.run(ComputableLiveData.java:87)
                                                                                at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
                                                                                at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
                                                                                at java.lang.Thread.run(Thread.java:761)

Code:
`@Database(entities = {Note.class}, version = 3)
public abstract class NoteDatabase extends RoomDatabase {
public static final Migration MIGRATION_2_3 = new Migration(2, 3) {
    @Override
    public void migrate(@NonNull SupportSQLiteDatabase database) {

        database.execSQL(
                "CREATE TABLE note (id INTEGER NOT NULL, title TEXT, description TEXT, created_date TEXT, notification_date TEXT, notification_state INTEGER, priority INTEGER, PRIMARY KEY(id))");

        database.execSQL(
                "INSERT INTO note (id, title, description, created_date) SELECT _ID, title, description, date FROM notes");

    }
};`

A: Ok i got it working, if anyone have the same problem just use NOT NULL DEFAULT 0(or other number).
@Database(entities = {Note.class}, version = 3)
public abstract class NoteDatabase extends RoomDatabase {

    public static final Migration MIGRATION_2_3 = new Migration(2, 3) {
        @Override
        public void migrate(@NonNull SupportSQLiteDatabase database) {

            database.execSQL(
                    "CREATE TABLE note (id INTEGER NOT NULL, " +
                    "title TEXT, description TEXT, created_date TEXT, notification_date TEXT, " +
                    "notification_state INTEGER NOT NULL DEFAULT 0, " +
                    "priority INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(id))");

            database.execSQL(
                    "INSERT INTO note (id, title, description, created_date) " +
                    "SELECT _ID, title, description, date FROM notes");

        }
    };

    // ...

}

A: Migration code:
class Migration1To2: Migration(1, 2){
    override fun migrate(database: SupportSQLiteDatabase) {
        database.execSQL("ALTER TABLE 'table_name' ADD COLUMN 'row_to modify' INTEGER NOT NULL **DEFAULT 1"**)
    }
}

 Dao Entity add **defaultValue = "1"**:
 @ColumnInfo( name="row_to modify", defaultValue = "1")
    var row_to modify: Int


text:
Q: Disable Parent ContextMenu in Chrome Extension If I have a Chrome Extension context menu with a submenu, how can I disable the parent so the submenu items are not accessible until the parent is enabled?
chrome.contextMenus.create({
  id: "parentMenu",
  title: "Parent Menu",
  contexts: ["browser_action"],
  enabled: false
});

// Create a submenu with two radio buttons

chrome.contextMenus.create({
  parentId: "parentMenu",
  title: "Submenu1",
  contexts: ["browser_action"],
  type: "radio",
  checked: true,
  onclick: function (evt) {}
});

chrome.contextMenus.create({
  parentId: "parentMenu",
  title: "Submenu2",
  contexts: ["browser_action"],
  type: "radio",
  onclick: function (evt) {}
});

Even though the parentMenu is marked disabled, it is not disabling.  When I disable the submenus, those do disable as expected.

A: I'm guessing it's impossible with a submenu.
A workaround solution would be to remove all submenu items, making the root menu item a normal entry, and disabling it. You lose the arrow, but achieve the disabled state.
Consider some other UI approach though; this seems somewhat clunky.


text:
Q: PHP Header Redirect not working when used with "www" I'm using this but whenever i try to open with www, it gives me an error:
if($_SERVER['HTTP_HOST'] == "sub.mydomain.com")
header("Location: mydomain.com/sub/");

Where am I going wrong?
I want users redirected when they type sub.mydomain.com or www.sub.mydomain.com

A: You need to do a correct header call.
Like this:
if(strpos('sub.example.com', $_SERVER['HTTP_HOST']) !== false){
    header("location: http://example.com/sub/");
}

EDIT:
Based on the information in this post:
You can also use this function instead:
function get_subdomain($url=""){
    if($url==""){
        $url = $_SERVER['HTTP_HOST'];
    }
    $parsedUrl = parse_url($url);
    $host = explode('.', $parsedUrl['path']);
    $subdomains = array_slice($host, 0, count($host) - 2 );
    return implode(".", $subdomains);
}

if('sub' != get_subdomain()){
      header("location: http://example.com/sub/");
}


text:
Q: Get json data at the end of a file upload data task I am trying to upload a file to the server and after the completion of upload, I'm supposed to get a JSON response.
I can see the data when I use the completion block
uploaderSession.dataTask(with: request, completionHandler: { (data, response, error) in
                print("\(NSString(data: data!, encoding: 4))")
            }).resume()

I need the same data but using the custom delegates
    let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    session.dataTask(with: request).resume()

I implemented
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive data: Data)

but  didReceiveData is not called.
Please suggest what can  be done to get the JSON data at the end of completion of file upload
Thanks in advance

A: ok so got the answer just posting cause it can help somebody
we have to call
completionHandler(URLSession.ResponseDisposition.allow)

in
func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void)


text:
Q: What to do with annotations after setting metadata-complete="true" (which resolved slow Tomcat 7 start-up)? Seems like the slow Tomcat 7 startup problem can be resolved with "metadata-complete" set to "true" in the web.xml, like so:
<?xml version="1.0" encoding="UTF-8"?>
<web-app metadata-complete="true" id="WebApp_ID" version="3.0"...

The problem is that Tomcat scans for annotations at startup, and this significantly slows it down. My time is cut down from 25 secs to 5 secs. (More info here: Tomcat and Servlet 3.0 Web Configuration)
However, I have some annotations in my code, like:
@ManagedBean
@RequestScoped
@Override
...

I am confused - will my code work after I have set metadata-complete="true"? Do I have to remove annotations and move everything into web.xml?

A: The slow startup is caused because every single class file in every single JAR file in /WEB-INF/lib is also scanned for Servlet 3.0 specific annotations. You apparently have a lot of (large) JAR files in /WEB-INF/lib.
The metadata-complete="true" indicates that the JAR files in /WEB-INF/lib doesn't need to be scanned for Servlet 3.0 specific annotations, but the webapp's own classes will still be scanned.
Note that you listed there two JSF annotations and one Java SE annotation, not any Servlet 3.0 annotations. The Servlet 3.0 annotations are listed in the javax.servlet.annotation package. JSF will only scan for annotations when the JAR file contains a JSF 2.0 compatible /META-INF/faces-config.xml file. It won't immediately scan every single class in every JAR file. The Java SE @Override annotation is not a runtime annotation, but a compile-time aid only.
See also:

*

*Packaging Facelets files (templates, includes, composites) in a JAR

A: Here is what Java Servlet 3.0 / 3.1 Specification has to say:

The web application deployment descriptor contains a metadata-complete
  attribute on the web-app element. The metadata-complete attribute
  defines whether the web.xml descriptor is complete, or whether other
  sources of metadata used by the deployment process should be
  considered. Metadata may come from the web.xml file, web-fragment.xml
  files, annotations on class files in WEB-INF/classes, and annotations
  on classes in jar files in the WEB-INF/lib directory. If
  metadata-complete is set to "true", the deployment tool only examines
  the web.xml file and must ignore annotations such as @WebServlet,
  @WebFilter, and @WebListener present in the class files of the
  application, and must also ignore any web-fragment.xml descriptor
  packaged in a jar file in WEB-INF/lib. If the metadata-complete
  attribute is not specified or is set to "false", the deployment tool
  must examine the class files and web-fragment.xml files for
  metadata,as previously specified.

This being said and to answer your question: Yes, in order to optimise the start up time of Tomcat you need to use metadata-complete="true" and put every Servlet or Filter or Listener in your deployment descriptor.


text:
Q: Why does Android Studio throw errors in the manifest file when we change the compileSdkVersion and targetSdkVersion from 26 to 23? I have searched SO thoroughly and couldn't find the reason for the error that I am facing.
Things I did:

*

*I changed the compileSdkVersion & targetSdkVersions in app gradle file from 26 to 23.

*I clicked sync now.

*It resulted in 7 error messages making my manifest file go haywire.

Snippets:

*

*My App Gradle file after changing the compile,target sdk versions to 23 from 26

apply plugin: 'com.android.application'

android {
    compileSdkVersion 26
    defaultConfig {
        applicationId "com.airtelanalytics"
        minSdkVersion 14
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:26.1.0'
    compile 'com.android.support:recyclerview-v7:26.1.+'
    compile 'com.jaredrummler:android-processes:1.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.1'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
}

*Android SDK Platform 23 is installed already

*Error Messages (affecting Manifest file) due to change of SDK version from 26 to 23

*Manifest file

<uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="23" />

<application
    android:allowBackup="true"
    android:debuggable="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity android:name="com.analyticsdemo.MainActivity" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

How to fix this ?

A:
I changed the compileSdkVersion & targetSdkVersions in app gradle file from 26 to 23.

That is not a good plan, particularly if you plan to ship via the Play Store, as you will have to raise the values again shortly.

How to fix this ?

The best solution is to move your compileSdkVersion and targetSdkVersion back to 26.
Otherwise, fix the errors reported by the compiler.
In this case, your manifest has android:roundIcon on <application>, and android:roundIcon did not exist back with API Level 23. You are saying, via compileSdkVersion 23, that you want to compile using the rules that existed for API Level 23, and that includes not using things that did not exist back then. So, get rid of android:roundIcon from your actual manifest.


text:
Q: sudo add-apt-repository hangs with no error Ubuntu 19.04 Whenever I try to run sudo add-apt-repository ppa:docky-core/ppa(for any ppa, not just this one) it just hangs indefinitely, without giving any sort of error, even with the -m flag. After I terminate it with ctrl+c it shows the following:
^CTraceback (most recent call last):
  File "/usr/bin/add-apt-repository", line 136, in <module>
    shortcut = shortcut_handler(line)
  File "/usr/lib/python3/dist-packages/softwareproperties/SoftwareProperties.py", line 864, in shortcut_handler
    ret = factory(shortcut)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 469, in shortcut_handler
    return PPAShortcutHandler(shortcut)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 426, in __init__
    info = get_ppa_info(self.shortcut)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 380, in get_ppa_info
    ret = get_ppa_info_from_lp(user, ppa)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 110, in get_ppa_info_from_lp
    return get_info_from_lp(lp_url)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 104, in get_info_from_lp
    return get_info_from_https(lp_url, True)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 96, in get_info_from_https
    data = func(lp_url=url, accept_json=accept_json, retry_delays=retry_delays)
  File "/usr/lib/python3/dist-packages/softwareproperties/ppa.py", line 139, in _get_https_content_py3
    cafile=LAUNCHPAD_PPA_CERT)
  File "/usr/lib/python3.7/urllib/request.py", line 222, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/lib/python3.7/urllib/request.py", line 525, in open
    response = self._open(req, data)
  File "/usr/lib/python3.7/urllib/request.py", line 543, in _open
    '_open', req)
  File "/usr/lib/python3.7/urllib/request.py", line 503, in _call_chain
    result = func(*args)
  File "/usr/lib/python3.7/urllib/request.py", line 1360, in https_open
    context=self._context, check_hostname=self._check_hostname)
  File "/usr/lib/python3.7/urllib/request.py", line 1317, in do_open
    encode_chunked=req.has_header('Transfer-encoding'))
  File "/usr/lib/python3.7/http/client.py", line 1229, in request
    self._send_request(method, url, body, headers, encode_chunked)
  File "/usr/lib/python3.7/http/client.py", line 1275, in _send_request
    self.endheaders(body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.7/http/client.py", line 1224, in endheaders
    self._send_output(message_body, encode_chunked=encode_chunked)
  File "/usr/lib/python3.7/http/client.py", line 1016, in _send_output
    self.send(msg)
  File "/usr/lib/python3.7/http/client.py", line 956, in send
    self.connect()
  File "/usr/lib/python3.7/http/client.py", line 1384, in connect
    super().connect()
  File "/usr/lib/python3.7/http/client.py", line 928, in connect
    (self.host,self.port), self.timeout, self.source_address)
  File "/usr/lib/python3.7/socket.py", line 716, in create_connection
    sock.connect(sa)
KeyboardInterrupt

Any ideas what could be causing this? Thanks.

A: Manually adding ppa source and key worked for me
Check answer to this question:
I can't add PPA repository behind the proxy


text:
Q: Volatile piggyback. Is this enough for visiblity? This is about volatile piggyback.
Purpose: I want to reach a lightweight vars visibilty. Consistency of a_b_c is not important. I have a bunch of vars and I don't want to make them all volatile.
Is this code threadsafe?
class A {
    public int a, b, c;
    volatile int sync;

    public void setup() {
        a = 2;
        b = 3;
        c = 4;
    }

    public void sync() {
        sync++;
    }
}

final static A aaa = new A();

Thread0:
aaa.setup();
end

Thread1:
for(;;) {aaa.sync(); logic with aaa.a, aaa.b, aaa.c}

Thread2:
for(;;) {aaa.sync(); logic with aaa.a, aaa.b, aaa.c}

A: Incrementing a value between threads is never thread-safe with just volatile. This only ensures that each thread gets an up to date value, not that the increment is atomic, because at the assembler level your ++ is actually several instructions that can be interleaved.
You should use AtomicInteger for a fast atomic increment.
Edit: Reading again what you need is actually a memory fence. Java has no memory fence instruction, but you can use a lock for the memory fence "side-effect". In that case declare the sync method synchronized to introduce an implicit fence:
void synchronized sync() {
    sync++;
}

A: Java Memory Model defines the happens-before relationship which has the following properties (amongst others):

*

*"Each action in a thread happens-before every action in that thread that comes later in the program order" (program order rule)

*"A write to a volatile field happens-before every subsequent read of that same volatile" (volatile variable rule)

These two properties together with transitivity of the happens-before relationship imply the visibility guarantees that OP seeks in the following manner:

*

*A write to a in thread 1 happens-before a write to sync in a call to sync() in thread 1 (program order rule).

*The write to sync in the call to sync() in thread 1 happens-before a read to sync in a call to sync in thread 2 (volatile variable rule).

*The read from sync in the call to sync() in thread 2 happens-before a read from a in thread 2 (program order rule).

This implies that the answer to the question is yes, i.e. the call to sync() in each iteration in threads 1 and 2 ensures visibility of changes to a, b and c to the other thread(s). Note that this ensures visibility only. No mutual exclusion guarantees exist and hence all invariants binding a, b and c may be violated.
See also Java theory and practice: Fixing the Java Memory Model, Part 2. In particular the section "New guarantees for volatile" which says

Under the new memory model, when thread A writes to a volatile
  variable V, and thread B reads from V, any variable values that were
  visible to A at the time that V was written are guaranteed now to be
  visible to B.

A: The pattern is usually like this.
public void setup() {
    a = 2;
    b = 3;
    c = 4;
    sync();
}

However, while this guarantees the other threads will see this change, the other threads can see an incomplete change. e.g. the Thread2 might see a = 2, b = 3, c = 0. or even possibly a = 2, b = 0, c = 4;
Using the sync() on the reader doesn't help much.

A: From javadoc:

An unlock (synchronized block or method exit) of a monitor
  happens-before every subsequent lock (synchronized block or method
  entry) of that same monitor. And because the happens-before relation
  is transitive, all actions of a thread prior to unlocking
  happen-before all actions subsequent to any thread locking that
  monitor.
A write to a volatile field happens-before every subsequent read of
  that same field. Writes and reads of volatile fields have similar
  memory consistency effects as entering and exiting monitors, but do
  not entail mutual exclusion locking.

So I think that writing to volatile var is not an equivalent to syncronization in this case and it doesn't guarantee happens-before order and visibility of changes in Thread1 to Thread2

A: You don't really have to manually synchronize at all, just use an automatically synchronized data structure, like java.util.concurrent.atomic.AtomicInteger.
You could alternatively make the sync() method synchronized.


text:
Q: ENOTFOUND error while installing 'express' in Node.js - Windows I'm trying to install express package of Node.js through my Windows 7 CMD.
I did a
npm install express

and I'm getting the following error :
npm ERR! Error: getaddrinfo ENOENT
npm ERR!     at errnoException (dns.js:31:11)
npm ERR!     at Object.onanswer [as oncomplete] (dns.js:140:16)

and
 npm ERR! cwd D:\node
    npm ERR! node -v v0.6.15
    npm ERR! npm -v 1.1.16
    npm ERR! syscall getaddrinfo
    npm ERR! code ENOTFOUND
    npm ERR! message getaddrinfo ENOENT
    npm ERR! errno {}
    npm ERR!
    npm ERR! Additional logging details can be found in:
    npm ERR!     D:\node\npm-debug.log
    npm not ok

I'm working behind a Firewall. Is that by any chance, the reason behind this?
Many thanks!

A: run cmd with administrator and it will work.


text:
Q: recursive + 900 elements + neighbor check = causes stackoverflow I have a city simulation game and try to find a way to check the flow of our power system.
The basics:
The map for the city is based on tiles (30 by 30 tiles = 900 tiles).
Now i start at a power plant and do a recursive neighbor check (top, left, right, bottom) to check if there is something that will transport the power. If there is something, I start checking this tiles for neighbors, too.
To prevent double checks and/or infinite recursive calls, I fill a ArrayList with processed tiles and check if a new tile was already processed and added to the ArrayList...
Recursively started:
public void updatePowerEnvironment(int id, ArrayList<Integer> elements) {
    Log.w("GT", "update env for id: " + id);
    int newId = id - GameMap.mMapSize;
    if (newId >= 0 && GameMap.mMapCells.get(newId).mPowerEnabled
            && !elements.contains(newId)) {
        elements.add(newId);
        updatePowerEnvironment(newId, elements);
    }
    newId = id + GameMap.mMapSize;
    if (newId < GameMap.mMapCells.size() && GameMap.mMapCells.get(newId).mPowerEnabled
            && !elements.contains(newId)) {
        elements.add(newId);
        updatePowerEnvironment(newId, elements);
    }
    newId = id - 1;
    if (newId >= 0 && GameMap.mMapCells.get(newId).mPowerEnabled
            && !elements.contains(newId)) {
        elements.add(newId);
        updatePowerEnvironment(newId, elements);
    }
    newId = id + 1;
    if (newId < GameMap.mMapCells.size()
            && GameMap.mMapCells.get(newId).mPowerEnabled
            && !elements.contains(newId)) {
        elements.add(newId);
        updatePowerEnvironment(newId, elements);
    }
}

If I can trust the log output, no tile was tried to processed twice. That means, that I have no errors in the recursive calls. Which also means, the stack is simply too small.
Does someone have an idea how to avoid the stack limit?
[Update and my code as a result of Erics answer]
public void updatePowerEnvironment(int id, ArrayList<Integer> elements) {
    Stack<Integer> toProcess = new Stack<Integer>();
    toProcess.push(id);
    int mapSize = GameMap.mMapCells.size();
    while (!toProcess.empty()) {
        id = toProcess.pop();
        Log.e("GT", "id to process: " + id);
        if (elements.contains(id)) {
            continue;
        }
        int[] neighborIds = computeNeighbors(id);
        for (int neighbor : neighborIds) {
            if (neighbor < 0 || neighbor >= mapSize) {
                continue;
            }
            if (!GameMap.mMapCells.get(neighbor).mPowerEnabled) {
                continue;
            }
            toProcess.push(neighbor);
        }
        elements.add(id);
    }
}

private int[] computeNeighbors(int id) {
    return new int[] {id + GameMap.mMapSize, id - GameMap.mMapSize, id + 1, id - 1};
}

A: You just need to convert your recursive implementation into an iterative one (as theory tells us is always possible).
For example, you could:

*

*maintain a queue of cells-to-be-checked

*while this queue is not empty, process the front element

*

*to process a cell, do whatever you have to do to the cell itself, then for each of its four nneighbours

*if they are not already in the queue, add them to the queue

*repeat until the queue is empty

A: If I understand your problem correctly you are attempting to compute the transitive closure of the "is powered by" relation between two tiles. It is certainly possible to compute a transitive closure non-recursively.
Here's a non-recursive algorithm that computes the transitive closure of a relation in C#. You should be able to adapt that to the language of your choice.
http://blogs.msdn.com/b/ericlippert/archive/2010/02/08/making-the-code-read-like-the-spec.aspx
Note that basically what I'm doing here is avoiding the stack limit by allocating my own stack on the heap. That thing can grow as big as you like. (If you run out of heap memory then you've got bigger problems!)
Note also that it would be wise to choose a data structure that makes the "is a member of?" predicate extremely cheap. An array list of size n is usually O(n) to answer the question "is this element a member of this collection?" which means your algorithm is O(n^2) overall. Can you use a collection like a set or a hash table that has O(1) containment testing?
Also, on a purely "code quality" level, this method could use some work. The fact that there is so much duplicated code in there is a red flag. I would be inclined to write this method like this sketch:
Set<int> PoweredTiles(int powersource)
{
    Set<int> result = an empy set;
    Stack<int> stack = an empty stack;
    stack.Push(powersource);
    while (stack is not empty)
    {
        int current = stack.Pop();
        if (result.Contains(current)) continue;
        result.Add(current);
        int[] neighbours = { compute the neighbours }
        foreach(int neighbour in neighbours)
        {
            if (neighbour is not in range of grid) continue;
            if (neighbour is not a power carrier) continue;
            stack.Push(neighbour);
        }
    }
    return result;
}

Short, to the point, not recursive, no duplicated code, and O(n).

A: An efficient, recursive algorithm should work provided you do clear the flags (I assume you're simply setting flags on whether a tile has power or not) before doing the recursion.  Something like this:
void updateCell(position)
{
  for each direction (north, south, east, west) do the following:
  -- is there a cell there? (test for edges), if not, exit now;
  -- can it be powered?
     false: exit now;
     true: set powered=true, call updateCell(this position);
}

void updatePowerGrid(start)
{
  clearPowerFlags();
  set powered=true for start;
  updateCell(start);
}

This should work well enough until you use really huge grid sizes.

A: You can make it iterative. Have two lists, one that keeps track of where you have been, and one that keeps track of where you are currently checking.
Psuedo Code with your code:
While(ToBeChecked is not empty) {
    //Note In python i'd be using a copy of the list so I could edit it without
    //concequence during the iteration. ie for a in b[:]
    for each element in ToBeChecked
         updatePowerEnvironment(...);
         //Remove element you are checking
         removeElementFromToBeChecked(...);
}

public void updatePowerEnvironment(int id, ArrayList<Integer> elements) {
    Log.w("GT", "update env for id: " + id);
    int newId = id - GameMap.mMapSize;
    if (newId >= 0 && GameMap.mMapCells.get(newId).mPowerEnabled
            && !elements.contains(newId)) {
        elements.add(newId);
        //call addElementToBeChecked instead and I beleive the above already
        //makes sure it has not already been checked
        addElementToBeChecked(newId, elements);
    }
    newId = id + GameMap.mMapSize;
    if (newId < GameMap.mMapCells.size() && GameMap.mMapCells.get(newId).mPowerEnabled
            && !elements.contains(newId)) {
        elements.add(newId);
        addElementToBeChecked(newId, elements);
    }
    newId = id - 1;
    if (newId >= 0 && GameMap.mMapCells.get(newId).mPowerEnabled
            && !elements.contains(newId)) {
        elements.add(newId);
        addElementToBeChecked(newId, elements);
    }
    newId = id + 1;
    if (newId < GameMap.mMapCells.size()
            && GameMap.mMapCells.get(newId).mPowerEnabled
            && !elements.contains(newId)) {
        elements.add(newId);
        addElementToBeChecked(newId, elements);
    }
}

addElementToBeChecked(...) {
    ToBeChecked.add();
    //Some other stuff if needed
}
removeElemenToBeChecked(...) {
    ToBeChecked.remove();
    //Some other stuff if needed
}

A: The very first thing I would try is just to change the search order from North-South-West-East to North-East-South-West. Like this:
public void updatePowerEnvironment(int id, ArrayList<Integer> elements) {
    if (!GameMap.ValidCellId(id))
        return;
    if (!GameMap.mMapCells.get(id).mPowerEnabled)
        return;
    if (elements.Contains(id))
        return;
    elements.Add(id);
    updatePowerEnvironment(id - GameMap.mMapSize, elements);
    updatePowerEnvironment(id + 1, elements);
    updatePowerEnvironment(id + GameMap.mMapSize, elements);
    updatePowerEnvironment(id - 1, elements);
}

This might reduce the recursion depth, depeding on the maps involved.


text:
Q: UserControl default value for dependency property of type DataTemplate I have a simple EntriesViewModel that stores a list of items as well as supporting Add/Remove commands. (Add/Remove commanding left out)
public class EntriesViewModel
{
    public ObservableCollection<string> Entries { get; private set; }

    public EntriesViewModel()
    {
        Entries = new ObservableCollection<string>() { "One", "Two", "Three" };
    }
}

To view this I have created a simple EntriesEditor usercontrol that uses a listbox to display the entries and buttons to Add/Remove (Add/Remove commanding left out)
 public partial class EntriesEditor : UserControl
{
    public EntriesEditor()
    {
        InitializeComponent();
    }
}

<UserControl x:Class="UserControlDefaults.EntriesEditor"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:l="clr-namespace:UserControlDefaults"
         VerticalAlignment="Top">
<DockPanel Height="200">
    <UniformGrid Columns="2"
                 DockPanel.Dock="Bottom">
        <Button Content="Add" />
        <Button Content="Remove" />
    </UniformGrid>
    <ListBox ItemsSource="{Binding Entries}"
             ItemTemplate="{Binding EntryTemplate, RelativeSource={RelativeSource AncestorType={x:Type l:EntriesEditor}}}"/>
</DockPanel>

And is used as so :
<l:EntriesEditor DataContext="{Binding EntriesViewModel}"/>

I now want the EntriesEditor to support the ability to define a custom ItemTemplate. So I add an EntryTemplate property.
public partial class EntriesEditor : UserControl
{
    public DataTemplate EntryTemplate
    {
        get { return (DataTemplate)GetValue(EntryTemplateProperty); }
        set { SetValue(EntryTemplateProperty, value); }
    }

    public static readonly DependencyProperty EntryTemplateProperty =
        DependencyProperty.Register("EntryTemplate", typeof(DataTemplate), typeof(EntriesEditor), new PropertyMetadata(null));

    public EntriesEditor()
    {
        InitializeComponent();
    }
}

<UserControl x:Class="UserControlDefaults.EntriesEditor"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:l="clr-namespace:UserControlDefaults"
         VerticalAlignment="Top">
<DockPanel Height="200">
    <UniformGrid Columns="2"
                 DockPanel.Dock="Bottom">
        <Button Content="Add" />
        <Button Content="Remove" />
    </UniformGrid>
    <ListBox ItemsSource="{Binding Entries}"
             ItemTemplate="{Binding EntryTemplate, RelativeSource={RelativeSource AncestorType={x:Type l:EntriesEditor}}}"/>
</DockPanel>

Which is used as so:
<l:EntriesEditor DataContext="{Binding EntriesViewModel}">
    <l:EntriesEditor.EntryTemplate>
        <DataTemplate>
            <Border BorderThickness="1"
                    BorderBrush="Green"
                    Padding="5">
                <ContentPresenter Content="{Binding}"/>
            </Border>
        </DataTemplate>
    </l:EntriesEditor.EntryTemplate>
</l:EntriesEditor>

But now I want to define a default EntryTemplate within the EntriesEditor control, how would I do this?
The only way I can think of, is like this :
<UserControl x:Class="UserControlDefaults.EntriesEditor"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:l="clr-namespace:UserControlDefaults"
         VerticalAlignment="Top">

<UserControl.Style>
    <Style TargetType="{x:Type l:EntriesEditor}">
        <Setter Property="EntryTemplate">
            <Setter.Value>
                <DataTemplate>
                    <Border BorderThickness="2"
                            BorderBrush="Red">
                        <ContentPresenter Content="{Binding}" />
                    </Border>
                </DataTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</UserControl.Style>

<DockPanel Height="200">
    <UniformGrid Columns="2"
                 DockPanel.Dock="Bottom">
        <Button Content="Add" />
        <Button Content="Remove" />
    </UniformGrid>
    <ListBox ItemsSource="{Binding Entries}"
             ItemTemplate="{Binding EntryTemplate, RelativeSource={RelativeSource AncestorType={x:Type l:EntriesEditor}}}"/>
</DockPanel>

But that doesn't seem right.


text:
Q: Application Form in WordPress My company uses the Genesis Framework and WordPress for the overall website.  It's a multi-site set up and we'll have multiple child themes in Genesis.
I need to create a multi-page application form with user-sign-up (WP-MU?) that will allow a user to register, complete the app and be able to quit and return to their stopping point.
I'm looking for ideas on where to begin.  I've gone in and created my own version of the 'page' template, so I can create the form from that.  I've taken out the loop function and began writing my own custom code to replace it.
I normally use PHP frameworks for this sort of thing, making CRUD much simpler for me, but working inside of WP has me a bit lost.  Anyone care to offer up a bit of advice?  Need more info?  I'll edit the post if so.  Thanks!

A: The answer...in case anyone else needed help with this...turned out to be as simple as creating a custom page-template, replacing the loop with a hook to your own function and handling all of the requests by parsing the url.  this worked for me, but not well enough to stay with WP, so I wrote the application in an MVC framework.


text:
Q: socket stays established after closing the process of the running program I wrote a python program which uses sockets, but there's one problem and the problem is that when I close the running program(from the task manager or even from the X button) the server socket stays established(still listening) and it causes problem in the next program run(because the port is taken)
if anyone could help me I will be grateful, Cheers.

A: If you open a file for writing, then kill the program, the file is still on disk.  Same with sockets (which, internally are just files)
One way to avoid this is to install a signal handler that cleans up and sockets one a kill or HUP event:
import signal
import sys
def signal_handler(signal, frame):
        print('You pressed Ctrl+C!')
        # your sockets management code here
        sys.exit(0)

signal.signal(signal.SIGINT, signal_handler)
print('Press Ctrl+C')
signal.pause()


text:
Q: AWS Release Pipeline CodeCommit(repo A) -> CodeBuild -> CodeCommit(repo B) -> Beanstalk I am trying to create a release pipeline, where my source code is in CodeCommit(repo A) and I use Codebuild for build once code build for repo A is completed in the pipeline I want the artifact to be committed to repo B aa a part of release pipeline and then finally I want to take the source from repo B and deploy it to Beanstalk. I am trying to create this as a part of the release pipeline using the code pipeline.
But I am not able to figure out how to commit the artifact(built using code build) to repo B in the pipeline.

A: You can 'git push' the artifact to the other repo using regular git commands in buildspec. A better approach would be to copy the artifact to S3 using aws cli command (e.g. aws s3 cp) and create the second pipeline with the source as this s3 bucket/object. This way you can kick start the second pipeline by just copying the artifact to the S3 bucket.


text:
Q: Shortest way between two points by going through all other points from point collection Given a point collection defined by x and y coordinates.
In this collection I get the start point, the end point and all the other n-2 points.
I have to find the shortest way between the start point and end point by going through all the other points. The shortest way is defined by its value and if possible the crossing point order.
At a first look this seems to be a graph problem, but i am not so sure about that right now, any way i am trying to find this shortest way by using only geometric relations since currently all the information that i have is only the x and y coordinates of the points, and which point is the start point and which is the end point.
My question is, can this way be found by using only geometric relations?
I am trying to implement this in C#, so if some helpful packages are available please let me know.

A: The Euclidean travelling salesman problem can be reduced to this and it's NP-hard. So unless your point set is small or you have a very particular structure, you should probably look out for an approximation. Note that the Wikipedia article mentions the existence of a PTAS for the problem, which could turn out to be quite effective in practice.
UPDATE: Since your instances seem to have only few nodes, you can use a simple exponential-time dynamic programming approach. Let f(S, p) be the minimum cost to connect all the points in the set S, ending at the points p. We have f({start}, start) = 0 and we are looking for f(P, end), where P is the set of all points. To compute f(S, p), we can check all potential predecessors of p in the tour, so we have
f(S, p) = MIN(q in S \ {p}, f(S \ {p}, q) + distance(p, q))

You can represent S as a bitvector to save space (just use an single-word integer for maximum simplicity). Also use memoization to avoid recomputing subproblem results.
The runtime will be O(2^n * n^2) and the algorithm can be implemented with a rather low constant factor, so I predict it to be able to solve instance with n = 25 within seconds a reasonable amount of time.

A: The simplest heuristic with reasonable performance is 2-opt. Put the points in an array, with the start point first and the end point last, and repeatedly attempt to improve the solution as follows. Choose a starting index i and an ending index j and reverse the subarray from i to j. If the total cost is less, then keep this change, otherwise undo it. Note that the total cost will be less if and only if d(p[i - 1], p[i]) + d(p[j], p[j + 1]) > d(p[i - 1], p[j]) + d(p[i], p[j + 1]), so you can avoid performing the swap unless it's an improvement.
There are a possible number of improvements to this method. 3-opt and k-opt consider more possible moves, resulting in better solution quality. Data structures for geometric search, kd-trees for example, decrease the time to find improving moves. As far as I know, the state of the art in local search algorithms for TSP is Keld Helsgaun's LKH.
Another family of algorithms is branch and bound. These return optimal solutions. Concorde (as far as I know) is the state of the art here.
Here's a Java implementation of the O(n^2 2^n) DP that Niklas described. There are many possible improvements, e.g., cache the distances between points, switch to floats (maybe), reorganize the iteration so that subsets are enumerating in increasing order of size (to allow only the most recent layer of minTable to be retained, resulting in a significant space saving).
class Point {
    private final double x, y;

    Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    double distanceTo(Point that) {
        return Math.hypot(x - that.x, y - that.y);
    }

    public String toString() {
        return x + " " + y;
    }
}

public class TSP {
    public static int[] minLengthPath(Point[] points) {
        if (points.length < 2) {
            throw new IllegalArgumentException();
        }
        int n = points.length - 2;
        if ((1 << n) <= 0) {
            throw new IllegalArgumentException();
        }
        byte[][] argMinTable = new byte[1 << n][n];
        double[][] minTable = new double[1 << n][n];
        for (int s = 0; s < (1 << n); s++) {
            for (int i = 0; i < n; i++) {
                int sMinusI = s & ~(1 << i);
                if (sMinusI == s) {
                    continue;
                }
                int argMin = -1;
                double min = points[0].distanceTo(points[1 + i]);
                for (int j = 0; j < n; j++) {
                    if ((sMinusI & (1 << j)) == 0) {
                        continue;
                    }
                    double cost =
                        minTable[sMinusI][j] +
                        points[1 + j].distanceTo(points[1 + i]);
                    if (argMin < 0 || cost < min) {
                        argMin = j;
                        min = cost;
                    }
                }
                argMinTable[s][i] = (byte)argMin;
                minTable[s][i] = min;
            }
        }
        int s = (1 << n) - 1;
        int argMin = -1;
        double min = points[0].distanceTo(points[1 + n]);
        for (int i = 0; i < n; i++) {
            double cost =
                minTable[s][i] +
                points[1 + i].distanceTo(points[1 + n]);
            if (argMin < 0 || cost < min) {
                argMin = i;
                min = cost;
            }
        }
        int[] path = new int[1 + n + 1];
        path[1 + n] = 1 + n;
        int k = n;
        while (argMin >= 0) {
            path[k] = 1 + argMin;
            k--;
            int temp = s;
            s &= ~(1 << argMin);
            argMin = argMinTable[temp][argMin];
        }
        path[0] = 0;
        return path;
    }

    public static void main(String[] args) {
        Point[] points = new Point[20];
        for (int i = 0; i < points.length; i++) {
            points[i] = new Point(Math.random(), Math.random());
        }
        int[] path = minLengthPath(points);
        for (int i = 0; i < points.length; i++) {
            System.out.println(points[path[i]]);
            System.err.println(points[i]);
        }
    }
}

A: This can be solved using an evolutionary algorithm.
Look at this: http://johnnewcombe.net/blog/post/23

A: You might want to look at TPL (Task Parallel Library) to speed up the application.
EDIT
I found this Link which has a Traveling Salesman algorithm:
http://msdn.microsoft.com/en-us/magazine/gg983491.aspx
The Source Code is said to be at:
http://archive.msdn.microsoft.com/mag201104BeeColony


text:
Q: ¿Cómo escribir texto con caracteres especiales en un documento RTF? Estoy tratando de rellenar los campos de una plantilla en formato .rtf con los valores que obtengo de una base de datos. La plantilla (plantilla.rtf) esta formateada de la siguiente manera:

Me llamo @nombre, y tengo @edad años.

Y en la función (escrita en c#) realizo lo siguiente:
protected void function(object sender, EventArgs e)
{
    // Obtenemos los datos y los asignamos a variables

    Response.ContentType = "text/rtf";
    Response.Headers.Add("Content-Disposition", "attachment; filename=\"documento.rtf\"");

    var f = new StringBuilder(System.IO.File.ReadAllText(Server.MapPath("~/ruta/plantilla.rtf")));

    f.Replace("@nombre", nombre); // nombre = "Óscar"
    f.Replace("@edad", edad); // edad = "20"

    Response.Write(f);
    Response.End();
}

Todo el proceso funciona correctamente, el problema lo tengo al insertar texto con caracteres especiales, como en el ejemplo que acabo de pasar (nombre = "Óscar"), ya que el documento resultante me queda de la siguiente manera:

Me llamo Óscar, y tengo 20 años.

¿Cómo puedo solucionar esto?

A: Debes hacer tres cosas. Por un lado, al leer el archivo rtf asegurarte de que lo lees como UTF-8:
var f = new StringBuilder(System.IO.File.ReadAllText(Server.MapPath("~/ruta/plantilla.rtf"),Encoding.UTF8));

Por otro, asegurarte de lo mismo en el Response:
Response.Charset= "UTF-8"

Y por ultimo, hay que comprobar que el archivo rtf no esté ya codificado como ANSI en lugar de UTF-8.

A: Debido a la imposibilidad de modificar la codificación de la plantilla, opté por codificar los caracteres antes de escribirlos en la misma. De la siguiente manera:
f.Replace("@nombre", codificarString(nombre)); // nombre = "Óscar"
f.Replace("@edad", codificarString(edad)); // edad = "20"

Ahora envío cada cadena de texto a la función codificarString que esta a su vez envía cada carácter a la función codificarChar, devolviendo el carácter correspondiente codificado para que sea legible en ANSI:
public static string codificarChar(char c)
{
    int intCode = Convert.ToInt32(c);
    if (char.IsLetter(c) && intCode < 0x80)
    {
        return c.ToString();
    }
    return "\\u" + intCode + "?";
}

public static string codificarString(string s)
{
    StringBuilder returned = new StringBuilder();
    foreach(char c in s)
    {
        returned.Append(codificarChar(c));
    }
    return returned.ToString();
}

De esta manera se escribe correctamente:

Me llamo Óscar, y tengo 20 años.


text:
Q: how to make first row of datatable active on search I have a table which is created by plugins datatable that is coming from external json,Just I need to make active of first td(to change color) of first row on search, I have already tried with some function call but its not working. Can anyone please help me.Below is my code.Thanks in advance.
HTML
<!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css">

                name
                stargazerscount
                forkscount
                description

JAVASCRIPT
$( document ).ready(function() {

    $('#example').DataTable( {
language: {
        searchPlaceholder: "Search records"
    },
 "ajax": {
             "type"   : "POST",
            "url": "http://localhost/members.json",
             "dataSrc": function (json) {
      var return_data = new Array();
      for(var i=0;i< json.length; i++){

        return_data.push({

         'name': json[i].name,
          'stargazerscount'  : ''+json[i].stargazerscount+'',
           'forkscount'  : json[i].forkscount,
          'description' : json[i].description
        })

      }

      return return_data;
             }
    },

        "columns": [
            { "data": "name" },
            { "data": "stargazerscount" },
            { "data": "forkscount" },
            { "data": "description" }

        ]

});

);

members.json
[{
            "name": "mango",
            "stargazerscount": 526,
            "forkscount": "critical",
            "description": "fruits"
        },
        {
            "name": "brinjal",
            "stargazerscount": 526,
            "forkscount": "critical",
            "description": "vagetables"
        },
        {
            "name": "grapes",
            "stargazerscount": 526,
            "forkscount": "major",
            "description": "fruits"
        },
        {
            "name": "soap",
            "stargazerscount": 526,
            "forkscount": "major",
            "description": "groceries"
        },
        {
            "name": "dates",
            "stargazerscount": 526,
            "forkscount": "critical",
            "description": "dryfruits"
        },
        {
            "name": "mobiles",
            "stargazerscount": 526,
            "forkscount": "major",
            "description": "electronics"
        },
        {
            "name": "shirt",
            "stargazerscount": 526,
            "forkscount": "critical",
            "description": "clothes"
        },
        {
            "name": "dates",
            "stargazerscount": 526,
            "forkscount": "critical",
            "description": "dryfruits"
        },
        {
            "name": "mobiles",
            "stargazerscount": 526,
            "forkscount": "major",
            "description": "electronics"
        },
        {
            "name": "shirt",
            "stargazerscount": 526,
            "forkscount": "critical",
            "description": "clothes"
        },
        {
            "name": "shirt",
            "stargazerscount": 526,
            "forkscount": "critical",
            "description": "clothes"
        },
        {
            "name": "dates",
            "stargazerscount": 526,
            "forkscount": "critical",
            "description": "dryfruits"
        },
        {
            "name": "mobiles",
            "stargazerscount": 526,
            "forkscount": "major",
            "description": "electronics"
        },
        {
            "name": "shirt",
            "stargazerscount": 526,
            "forkscount": "critical",
            "description": "clothes"
        },
        {
            "name": "dates",
            "stargazerscount": 526,
            "forkscount": "critical",
            "description": "dryfruits"
        },
        {
            "name": "mobiles",
            "stargazerscount": 526,
            "forkscount": "major",
            "description": "electronics"
        },
         {
            "name": "mobiles",
            "stargazerscount": 526,
            "forkscount": "major",
            "description": "electronics"
        }

    ]

A: Add your code to 'draw' event handler. On search, this should change the background color of the first tr's td to green.
Change:
$('#example').DataTable( {

To:
var dtable = $('#example').DataTable( {

Add this in your js code:
dtable.on( 'draw', function () {
    $('#example tbody tr').find('td:nth-child(1)').css('background-color', '');
    if(dtable.search() != ""){
        var row = dtable.row('tr:nth-child(1)').node();
        $(row).find('td:nth-child(1)').css('background-color', 'green');
    }

} );