问:
Find parent with defined attribute wuth LINQ
I have variable XElement content =

```<code>        "...
         <item text="Name-1" id="1" segment="1" secret-id="Find-Me">
            <item text="Name-1-1" id="1.1">
               <item text="Name-1-1-1" id="1.1.1" />
               <item text="Name-1-1-2" id="1.1.2" />
            </item>
         </item>
         ..."
</code>```

I have also an item with id = 1.1.2

I need to find the first parent of this item which has attribute segment="1" and get its secret-id

How to do this with LINQ?

答:
Like this:</p>

```<code>item.Ancestors().Select(p => p.Attribute("secret-id")).First(a => a != null)
</code>```

Body:
I have variable XElement content =

        "...
         <item text="Name-1" id="1" segment="1" secret-id="Find-Me">
            <item text="Name-1-1" id="1.1">
               <item text="Name-1-1-1" id="1.1.1" />
               <item text="Name-1-1-2" id="1.1.2" />
            </item>
         </item>
         ..."

I have also an item with id = 1.1.2

I need to find the first parent of this item which has attribute segment="1" and get its secret-id

How to do this with LINQ?

Body:
Like this:

item.Ancestors().Select(p => p.Attribute("secret-id")).First(a => a != null)


来源: stackexchange

问:
git: Your branch is ahead by X commits
How does this actually come about?

I am working in one repo by myself at the moment, so this is my workflow:

Change files

Commit

Repeat 1-2 until satisfied

Push to master

Then when I do a git status it tells me that my branch is ahead by X commits (presumably the same number of commits that I have made). Is it because when you push the code it doesn't actually update your locally cached files (in the .git folders)? git pull seems to 'fix' this strange message, but I am still curious why it happens, maybe I am using git wrong?

including what branch is printed in the message

My local branch is ahead of master

where do you push/pull the current branch

I am pushing to GitHub and pulling to whichever computer I happen to be working on at that point in time, my local copy is always fully up to date as I am the only one working on it.

it doesn't actually check the remote repo

That is what I thought, I figured that I would make sure my understanding of it was correct.

are you passing some extra arguments to it?

Not ones that I can see, maybe there is some funny config going on on my end?

```<code>$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
nothing to commit (working directory clean)
</code>```

答:
This worked for me

git reset --hard origin/master

The output must look like

On branch dev
HEAD is now at ae1xc41z Last commit message

ContentLicense: CC BY-SA 3.0

Title: git: Your branch is ahead by X commits

Body:
How does this actually come about?

I am working in one repo by myself at the moment, so this is my workflow:

Change files

Commit

Repeat 1-2 until satisfied

Push to master

Then when I do a git status it tells me that my branch is ahead by X commits (presumably the same number of commits that I have made). Is it because when you push the code it doesn't actually update your locally cached files (in the .git folders)? git pull seems to 'fix' this strange message, but I am still curious why it happens, maybe I am using git wrong?

including what branch is printed in the message

My local branch is ahead of master

where do you push/pull the current branch

I am pushing to GitHub and pulling to whichever computer I happen to be working on at that point in time, my local copy is always fully up to date as I am the only one working on it.

it doesn't actually check the remote repo

That is what I thought, I figured that I would make sure my understanding of it was correct.

are you passing some extra arguments to it?

Not ones that I can see, maybe there is some funny config going on on my end?

$ git status
# On branch master
# Your branch is ahead of 'origin/master' by 1 commit.
#
nothing to commit (working directory clean)

ContentLicense: CC BY-SA 4.0


问:
The program '[3984] dotnet.exe' has exited with code -2147450751 (0x80008081)
```<code>The program '[3984] dotnet.exe' has exited with code -2147450751 (0x80008081).
The program '[3984] dotnet.exe: Program Trace' has exited with code 0 (0x0).
The program '[2492] iisexpress.exe: Program Trace' has exited with code 0 (0x0).
The program '[7352] chrome.exe: WebKit' has exited with code -1 (0xffffffff).
The program '[2492] iisexpress.exe' has exited with code 0 (0x0).
</code>```

After I started the debugger on my mvc project (Using VS 2017 .Net Core 2.14) the chrome opens and closes for a second during the debugging and I m getting this errors.
Anyone have an idea?

答:
I just right click on the project then select properties and change the target framework
from 1.1 to 1.0. DONE!

Body:
The program '[3984] dotnet.exe' has exited with code -2147450751 (0x80008081).
The program '[3984] dotnet.exe: Program Trace' has exited with code 0 (0x0).
The program '[2492] iisexpress.exe: Program Trace' has exited with code 0 (0x0).
The program '[7352] chrome.exe: WebKit' has exited with code -1 (0xffffffff).
The program '[2492] iisexpress.exe' has exited with code 0 (0x0).

After I started the debugger on my mvc project (Using VS 2017 .Net Core 2.14) the chrome opens and closes for a second during the debugging and I m getting this errors.
Anyone have an idea?


问:
Extract text and integer after specific letter
I have string:

```<code>s = 'travel to africa x 2\ asia x 2\ europe x 2\ Airport pick up included. Furnitures 3 seater couch x 1 4 seater+ couch x 1 < 60 inches TV x 1 60 inches+ TV x 1 Washer - front loader x 1 Box / bag / misc x 1 The maximum clearance is 1.5m.'
</code>```

I would like split it by x and extract number after it.

So expected output is:

```<code>out = [('travel to africa', '2'),
       ('\ asia', '2'),
       ( '\ europe', '2'),
       ('\ Airport pick up included. Furnitures 3 seater couch', '1'),
       ('4 seater+ couch', '1'),
       ('< 60 inches TV', '1'),
       ('60 inches+ TV', '1'),
       ('Washer - front loader', '1'),
       ('Box / bag / misc', '1')]
</code>```

I try this regex, but failed, because special chars like -+< was omited (also there should be another special chars):

```<code>r'([A-Za-z 0-9]+)\s+x\s+(\d+)'
</code>```

What is correct regex for extract this values? Or also is possible solution without regex?

答:
You may use

```<code>re.findall(r'(.*?)\s+x\s*(\d+)', s)
</code>```

See the Python demo and the regex demo.

The (.*?)\s+x\s*(\d+) pattern matches

(.*?) - Group 1: any 0+ chars other than line break chars

\s+ - 1+ whitespaces

x - x char

\s* - 0+ whitespaces

(\d+) - Group 2: one or more digits.

If you want to get rid of whitespace at the start of the match, use either re.findall(r'(\S.*?)\s+x\s*(\d+)', s) (see regex demo) or use comprehension after getting all matches, [x.strip() for x in re.findall(r'(.*?)\s+x\s*(\d+)', s)].

Body:
I have string:

s = 'travel to africa x 2\ asia x 2\ europe x 2\ Airport pick up included. Furnitures 3 seater couch x 1 4 seater+ couch x 1 < 60 inches TV x 1 60 inches+ TV x 1 Washer - front loader x 1 Box / bag / misc x 1 The maximum clearance is 1.5m.'

I would like split it by x and extract number after it.

So expected output is:

out = [('travel to africa', '2'),
       ('\ asia', '2'),
       ( '\ europe', '2'),
       ('\ Airport pick up included. Furnitures 3 seater couch', '1'),
       ('4 seater+ couch', '1'),
       ('< 60 inches TV', '1'),
       ('60 inches+ TV', '1'),
       ('Washer - front loader', '1'),
       ('Box / bag / misc', '1')]

I try this regex, but failed, because special chars like -+< was omited (also there should be another special chars):

r'([A-Za-z 0-9]+)\s+x\s+(\d+)'

What is correct regex for extract this values? Or also is possible solution without regex?

Body:
You may use

re.findall(r'(.*?)\s+x\s*(\d+)', s)

See the Python demo and the regex demo.

The (.*?)\s+x\s*(\d+) pattern matches

(.*?) - Group 1: any 0+ chars other than line break chars

\s+ - 1+ whitespaces

x - x char

\s* - 0+ whitespaces

(\d+) - Group 2: one or more digits.

If you want to get rid of whitespace at the start of the match, use either re.findall(r'(\S.*?)\s+x\s*(\d+)', s) (see regex demo) or use comprehension after getting all matches, [x.strip() for x in re.findall(r'(.*?)\s+x\s*(\d+)', s)].


问:
I am trying to update a new column with a value if at all there is an empty value in another column in my dataframe
I am trying to update column Report['Failure Reason'] with value "Interface Failure" if column Report['BSD'] is empty. Report is my dataframe.

i tried with the below code, it throws

"SyntaxError: keyword can't be an expression" error

```<code>Report['Failure Reason'] = np.where(Report['BSD'] = '', 'Interface Failure', ' ')
</code>```

if Report['BSD'] is empty, column Report['Failure Reason'] should be updated with value "Interface Failure", else it should be ignored

答:
If there is empty string use == only:

```<code>Report['Failure Reason'] = np.where(Report['BSD'] == '', 'Interface Failure', ' ')
</code>```

Or if there is missing value test it by Series.isna:

```<code>Report['Failure Reason'] = np.where(Report['BSD'].isna(), 'Interface Failure', ' ')
</code>```

Body:
I am trying to update column Report['Failure Reason'] with value "Interface Failure" if column Report['BSD'] is empty. Report is my dataframe.

i tried with the below code, it throws

"SyntaxError: keyword can't be an expression" error

Report['Failure Reason'] = np.where(Report['BSD'] = '', 'Interface Failure', ' ')

if Report['BSD'] is empty, column Report['Failure Reason'] should be updated with value "Interface Failure", else it should be ignored

Body:
If there is empty string use == only:

Report['Failure Reason'] = np.where(Report['BSD'] == '', 'Interface Failure', ' ')

Or if there is missing value test it by Series.isna:

Report['Failure Reason'] = np.where(Report['BSD'].isna(), 'Interface Failure', ' ')


问:
How to utilize ConcurrentHashMap.merge() with a shared AtomicInteger
I have a shared global counter that I want to check is less than a total before doing a concurrent computation and update into a map. How can I use modern java concurrency utils / API to ensure this is atomic?

class SharedAccess {

    AtomicInteger globalCounter = new AtomicInterger();
    Map<String, Integer> counterPerKey = new ConcurrentHashMap<>()

    class Holder{
        Integer value
    }

    public Holder incrementForKeyMultipleThreads(String key) {
         if (total.get() < 1000) {

          Integer newTotal = counterPerKey.merge(key, 1, Integer::sum);
          globalCounter.increment();
         return new Holder(newTotal);

    }

  }

}

```

<p>EDIT: This is solved by the merge function actually being atomic too. Therefore you get the benefit of the multiple thread access to the rest of the map, and the atomic inc on the total counter. </p>

```
class SharedAccess {

    AtomicInteger globalCounter = new AtomicInterger();
    Map<String, Integer> counterPerKey = new ConcurrentHashMap<>()

    class Holder{
        Integer value
    }

    public Holder incrementForKeyMultipleThreads(String key) {
         if (total.get() < 1000) {

          Integer newTotal = counterPerKey.merge(key, 1, (v1, v2) -> {
              globalCounter.increment();
              return v1+v1;
          }

         return new Holder(newTotal);

    }

  }

}
```

答:
Modern java still uses the same basic principles of thread-safety. You have a check-then-act scenario, which covers pretty much the whole method. So you can make the method synchronized:

```<code>public synchronized Holder incrementForKeyMultipleThreads(String key) {
    if (globalCounter.get() < 1000) {
        globalCounter.increment();
        return new Holder(counterPerKey.merge(key, 1, Integer::sum));
    }
    return null;
}
</code>```

And then if this is the only place you are using (reading or writing) globalCounter, you can change it to int.

Body:
I have a shared global counter that I want to check is less than a total before doing a concurrent computation and update into a map. How can I use modern java concurrency utils / API to ensure this is atomic?

class SharedAccess {

    AtomicInteger globalCounter = new AtomicInterger();
    Map<String, Integer> counterPerKey = new ConcurrentHashMap<>()

    class Holder{
        Integer value
    }

    public Holder incrementForKeyMultipleThreads(String key) {
         if (total.get() < 1000) {

          Integer newTotal = counterPerKey.merge(key, 1, Integer::sum);
          globalCounter.increment();
         return new Holder(newTotal);

    }

  }

}

EDIT: This is solved by the merge function actually being atomic too. Therefore you get the benefit of the multiple thread access to the rest of the map, and the atomic inc on the total counter.

class SharedAccess {

    AtomicInteger globalCounter = new AtomicInterger();
    Map<String, Integer> counterPerKey = new ConcurrentHashMap<>()

    class Holder{
        Integer value
    }

    public Holder incrementForKeyMultipleThreads(String key) {
         if (total.get() < 1000) {

          Integer newTotal = counterPerKey.merge(key, 1, (v1, v2) -> {
              globalCounter.increment();
              return v1+v1;
          }

         return new Holder(newTotal);

    }

  }

}

Body:
Modern java still uses the same basic principles of thread-safety. You have a check-then-act scenario, which covers pretty much the whole method. So you can make the method synchronized:

public synchronized Holder incrementForKeyMultipleThreads(String key) {
    if (globalCounter.get() < 1000) {
        globalCounter.increment();
        return new Holder(counterPerKey.merge(key, 1, Integer::sum));
    }
    return null;
}

And then if this is the only place you are using (reading or writing) globalCounter, you can change it to int.


问:
Call URL in Background
I have a URL which turns on the light in a room, this URL works when I execute it in a normal browser. But now I have a image and with a onclick event, I want this URL to be executed in background to turn on the light.

```<code><script type="text/javascript">
    function LightOnOff(URL)
    {
        var temp = new Image();
        temp.src = "http://camera-kkw.at/axis-cgi/io/port.cgi?action=1:/1000%5C?";
        temp.onload = function(){document.location.href=URL};
        return false;
    }
</script>
</code>```

The image I press on to call the function:

```<code><img alt="Light on/off" src="images/lamp.png" onclick="return LightOnOff(window.location.href)">
</code>```

Thanks for your help guys!

答:
You can use fetch in order to remotely trigger the endpoint. You could add an onClick handler to the image and then execute the request:

```<code>function onClick() {
  fetch('http://camera-kkw.at/axis-cgi/io/port.cgi?action=1:/1000%5C?')
    .then(res => alert('Success'))
    .catch(err => alert('Failed));
}
</code>```

Title: Call URL in Background

Body:
I have a URL which turns on the light in a room, this URL works when I execute it in a normal browser. But now I have a image and with a onclick event, I want this URL to be executed in background to turn on the light.

The image I press on to call the function:

Thanks for your help guys!

Body:
You can use fetch in order to remotely trigger the endpoint. You could add an onClick handler to the image and then execute the request:

function onClick() {
  fetch('http://camera-kkw.at/axis-cgi/io/port.cgi?action=1:/1000%5C?')
    .then(res => alert('Success'))
    .catch(err => alert('Failed));
}


问:
Load different index files for different customers in Angular 7
I want to be able to host different index.html files for my different customers so I allow customer branding on the app-loading screen.

My customers have their own urls, such as:

```<code>customer1.myapp.com
customer2.myapp.com
</code>```

So each customer wants their own app-loading screen (You know the default "Loading...".

I really prefer not having this configuration in a script tag in index.html, and load different preloading screens based on location.origin or something similiar, but that's all I can think of at the moment.

Any ideas how to solve this? Loading different index.html files came to my mind but have no idea how to do this.

答:
Different domain names imply different builds for each domain.

This means you should have several configurations for your angular.json file (you know, like when you use --prod).

By default, you have development and production. But you can add as much as you want.

Good thing is, the configuration takes into consideration file replacement :

```<code>      "configurations": {
        "production": {
          "fileReplacements": [{
            "replace": "src/environments/environment.ts",
            "with": "src/environments/environment.prod.ts"
          }],
</code>```

This means that all you have to do, is provide the files you want to replace in your configuration !

After that, all you have to do is run ng build --configuration=clientOne, and your project will be built for your client One, with the correct files in it.

Body:
I want to be able to host different index.html files for my different customers so I allow customer branding on the app-loading screen.

My customers have their own urls, such as:

customer1.myapp.com
customer2.myapp.com

So each customer wants their own app-loading screen (You know the default "Loading...".

I really prefer not having this configuration in a script tag in index.html, and load different preloading screens based on location.origin or something similiar, but that's all I can think of at the moment.

Any ideas how to solve this? Loading different index.html files came to my mind but have no idea how to do this.

Body:
Different domain names imply different builds for each domain.

This means you should have several configurations for your angular.json file (you know, like when you use --prod).

By default, you have development and production. But you can add as much as you want.

Good thing is, the configuration takes into consideration file replacement :

      "configurations": {
        "production": {
          "fileReplacements": [{
            "replace": "src/environments/environment.ts",
            "with": "src/environments/environment.prod.ts"
          }],

This means that all you have to do, is provide the files you want to replace in your configuration !

After that, all you have to do is run ng build --configuration=clientOne, and your project will be built for your client One, with the correct files in it.


答:
Here's one way to do it.I simplified the problem by just trying to match each group, and split manually afterwards.

```<code>s = 'travel to africa x 2\ asia x 2\ europe x 2\ Airport pick up included. Furnitures 3 seater couch x 1 4 seater+ couch x 1 < 60 inches TV x 1 60 inches+ TV x 1 Washer - front loader x 1 Box / bag / misc x 1 The maximum clearance is 1.5m.'
import re
res = []
for match in re.finditer(".*?x\s*\d+", s):
    l, _, r = map(str.strip, match.group().rpartition('x'))
    res.append((l, r))
</code>```

Output:

```<code>[('travel to africa', '2'),
 ('\\ asia', '2'),
 ('\\ europe', '2'),
 ('\\ Airport pick up included. Furnitures 3 seater couch', '1'),
 ('4 seater+ couch', '1'),
 ('< 60 inches TV', '1'),
 ('60 inches+ TV', '1'),
 ('Washer - front loader', '1'),
 ('Box / bag / misc', '1')]
</code>```

Title: Extract text and integer after specific letter

Body:
Here's one way to do it.I simplified the problem by just trying to match each group, and split manually afterwards.

s = 'travel to africa x 2\ asia x 2\ europe x 2\ Airport pick up included. Furnitures 3 seater couch x 1 4 seater+ couch x 1 < 60 inches TV x 1 60 inches+ TV x 1 Washer - front loader x 1 Box / bag / misc x 1 The maximum clearance is 1.5m.'
import re
res = []
for match in re.finditer(".*?x\s*\d+", s):
    l, _, r = map(str.strip, match.group().rpartition('x'))
    res.append((l, r))

Output:

[('travel to africa', '2'),
 ('\\ asia', '2'),
 ('\\ europe', '2'),
 ('\\ Airport pick up included. Furnitures 3 seater couch', '1'),
 ('4 seater+ couch', '1'),
 ('< 60 inches TV', '1'),
 ('60 inches+ TV', '1'),
 ('Washer - front loader', '1'),
 ('Box / bag / misc', '1')]


问:
how to send file to server with retrofit2 and alertDialog
hi i want send file to server with retrofit2 and alertDialog but i have somthing error .

my Request by retrofit2

```<code>@Multipart
    @POST("ads")
    Call<ResponseBody> getUpload(@Header("Authorization") String token
            , @Part("title") RequestBody title
            , @Part("description") RequestBody description
            , @Part("price") RequestBody price
            , @Part("tell") RequestBody tell
            , @Part("address") RequestBody address
            , @Part("category") RequestBody category
            , @Part MultipartBody.Part image);
</code>```

i create one floatingAction Button for add item

```<code>FloatingActionButton floatingActionButton = findViewById(R.id.fab);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showList();
            }
        });
</code>```

i create onActivityResult For me when I choose to notify me by changing the name of the Button

```<code> @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_FROM_GALLERY_REQUEST && resultCode == RESULT_OK
                && data != null && data.getData() != null) {
            saveUri = data.getData();
            btn_select.setText("Image Selected !");
        }
    }
</code>```

i create showlist for show me layout add new post and me fill information with alertDialog

```<code> private void showList() {
        Log.d(TAG, "showList: started");
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(Home.this);
        alertDialog.setTitle("Add new post");
        alertDialog.setMessage("please fill all information");

        LayoutInflater layoutInflater = this.getLayoutInflater();
        View view = layoutInflater.inflate(R.layout.add_new_post, null);

        tv_title = view.findViewById(R.id.tv_title);
        tv_category = view.findViewById(R.id.tv_category);
        tv_tell = view.findViewById(R.id.tv_tell);
        tv_price = view.findViewById(R.id.tv_price);
        tv_description = view.findViewById(R.id.tv_description);
        tv_address = view.findViewById(R.id.tv_address);

        btn_select = view.findViewById(R.id.btn_select);
        btn_upload = view.findViewById(R.id.btn_upload);

        btn_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseImage();
            }
        });

        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadImage(saveUri);
            }
        });

        alertDialog.setView(view);

        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        alertDialog.show();

    }
</code>```

i create chooseImage for select image for read image in my gallery.

```<code>private void chooseImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_FROM_GALLERY_REQUEST);
    }
</code>```

In the end i create uploadImage for send file to server

```<code>private void uploadImage(Uri uri) {
        Log.d(TAG, "uploadImage: started");

        tv_title = findViewById(R.id.tv_title);
        tv_address = findViewById(R.id.tv_address);
        tv_description = findViewById(R.id.tv_description);
        tv_price = findViewById(R.id.tv_price);
        tv_tell = findViewById(R.id.tv_tell);
        tv_category = findViewById(R.id.tv_category);

        File originalFile = new File(uri.toString());

        RequestBody titlePart = RequestBody.create(MultipartBody.FORM, tv_title.getText().toString());
        RequestBody addressPart = RequestBody.create(MultipartBody.FORM, tv_address.getText().toString());
        RequestBody descriptionPart = RequestBody.create(MultipartBody.FORM, tv_description.getText().toString());
        RequestBody pricePart = RequestBody.create(MultipartBody.FORM, tv_price.getText().toString());
        RequestBody tellPart = RequestBody.create(MultipartBody.FORM, tv_tell.getText().toString());
        RequestBody categoryPart = RequestBody.create(MultipartBody.FORM, tv_category.getText().toString());

        RequestBody imagePart  = RequestBody.create(MediaType.parse(getContentResolver().getType(uri)),
                FileUtils.getFile(originalFile));

        MultipartBody.Part file = MultipartBody.Part.createFormData("image", originalFile.getName(), imagePart);

        SharedPreferences preferences = getSharedPreferences("Get_Token", MODE_PRIVATE);
        final String token = preferences.getString("Token", null);

        Call<ResponseBody> call = RetrofitClient.getmInstance().getApi().getUpload(token, titlePart, descriptionPart, pricePart, tellPart, addressPart, categoryPart, file);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }
</code>```

and show me this error

```<code>2019-05-29 12:12:46.647 19215-19215/com.example.book E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.book, PID: 19215
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
        at com.example.book.Activities.Home.uploadImage(Home.java:160)
        at com.example.book.Activities.Home.access$200(Home.java:53)
        at com.example.book.Activities.Home$3.onClick(Home.java:123)
        at android.view.View.performClick(View.java:6261)
        at android.widget.TextView.performClick(TextView.java:11163)
        at android.view.View$PerformClick.run(View.java:23748)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6776)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
</code>```

Now tell me where I got it wrong . thanks

答:
Thrown to indicate that the code has attempted to cast an object to a
  subclass of which it is not an instance. For example, the following
  code generates a ClassCastException:

Error:-

java.lang.ClassCastException:
  android.support.v7.widget.AppCompatTextView cannot be cast to
  android.widget.EditText

This error telling you that you are trying to typecast AppCompatTextView into EditText.

Go through your XML and check which one you are trying to cast forcefully.

Solution:- Change in your XML (TextView into EditaText) or in your activity (EditText into TextView).

Error:-

java.lang.NullPointerException: Attempt to invoke virtual method
  'android.text.Editable android.widget.EditText.getText()' on a null
  object reference

NullPointerException telling you that the EditText object are you accessing is null. Because you didn't provide EditText object any memory. Means you are accessing it without binding.

Solution:- Bind your EditText object using findViewById to the id you have mentioned in XML.

Body:
hi i want send file to server with retrofit2 and alertDialog but i have somthing error .

my Request by retrofit2

@Multipart
    @POST("ads")
    Call<ResponseBody> getUpload(@Header("Authorization") String token
            , @Part("title") RequestBody title
            , @Part("description") RequestBody description
            , @Part("price") RequestBody price
            , @Part("tell") RequestBody tell
            , @Part("address") RequestBody address
            , @Part("category") RequestBody category
            , @Part MultipartBody.Part image);

i create one floatingAction Button for add item

FloatingActionButton floatingActionButton = findViewById(R.id.fab);
        floatingActionButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showList();
            }
        });

i create onActivityResult For me when I choose to notify me by changing the name of the Button

 @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_FROM_GALLERY_REQUEST && resultCode == RESULT_OK
                && data != null && data.getData() != null) {
            saveUri = data.getData();
            btn_select.setText("Image Selected !");
        }
    }

i create showlist for show me layout add new post and me fill information with alertDialog

 private void showList() {
        Log.d(TAG, "showList: started");
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(Home.this);
        alertDialog.setTitle("Add new post");
        alertDialog.setMessage("please fill all information");

        LayoutInflater layoutInflater = this.getLayoutInflater();
        View view = layoutInflater.inflate(R.layout.add_new_post, null);

        tv_title = view.findViewById(R.id.tv_title);
        tv_category = view.findViewById(R.id.tv_category);
        tv_tell = view.findViewById(R.id.tv_tell);
        tv_price = view.findViewById(R.id.tv_price);
        tv_description = view.findViewById(R.id.tv_description);
        tv_address = view.findViewById(R.id.tv_address);

        btn_select = view.findViewById(R.id.btn_select);
        btn_upload = view.findViewById(R.id.btn_upload);

        btn_select.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                chooseImage();
            }
        });

        btn_upload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                uploadImage(saveUri);
            }
        });

        alertDialog.setView(view);

        alertDialog.setPositiveButton("YES", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        alertDialog.setNegativeButton("NO", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });

        alertDialog.show();

    }

i create chooseImage for select image for read image in my gallery.

private void chooseImage() {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_FROM_GALLERY_REQUEST);
    }

In the end i create uploadImage for send file to server

private void uploadImage(Uri uri) {
        Log.d(TAG, "uploadImage: started");

        tv_title = findViewById(R.id.tv_title);
        tv_address = findViewById(R.id.tv_address);
        tv_description = findViewById(R.id.tv_description);
        tv_price = findViewById(R.id.tv_price);
        tv_tell = findViewById(R.id.tv_tell);
        tv_category = findViewById(R.id.tv_category);

        File originalFile = new File(uri.toString());

        RequestBody titlePart = RequestBody.create(MultipartBody.FORM, tv_title.getText().toString());
        RequestBody addressPart = RequestBody.create(MultipartBody.FORM, tv_address.getText().toString());
        RequestBody descriptionPart = RequestBody.create(MultipartBody.FORM, tv_description.getText().toString());
        RequestBody pricePart = RequestBody.create(MultipartBody.FORM, tv_price.getText().toString());
        RequestBody tellPart = RequestBody.create(MultipartBody.FORM, tv_tell.getText().toString());
        RequestBody categoryPart = RequestBody.create(MultipartBody.FORM, tv_category.getText().toString());

        RequestBody imagePart  = RequestBody.create(MediaType.parse(getContentResolver().getType(uri)),
                FileUtils.getFile(originalFile));

        MultipartBody.Part file = MultipartBody.Part.createFormData("image", originalFile.getName(), imagePart);

        SharedPreferences preferences = getSharedPreferences("Get_Token", MODE_PRIVATE);
        final String token = preferences.getString("Token", null);

        Call<ResponseBody> call = RetrofitClient.getmInstance().getApi().getUpload(token, titlePart, descriptionPart, pricePart, tellPart, addressPart, categoryPart, file);
        call.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {

            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });
    }

and show me this error

2019-05-29 12:12:46.647 19215-19215/com.example.book E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.book, PID: 19215
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.text.Editable android.widget.EditText.getText()' on a null object reference
        at com.example.book.Activities.Home.uploadImage(Home.java:160)
        at com.example.book.Activities.Home.access$200(Home.java:53)
        at com.example.book.Activities.Home$3.onClick(Home.java:123)
        at android.view.View.performClick(View.java:6261)
        at android.widget.TextView.performClick(TextView.java:11163)
        at android.view.View$PerformClick.run(View.java:23748)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6776)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)

Now tell me where I got it wrong . thanks


问:
JSF RichFaces:a4jSkin.tableBackgroundColor behaviour for zebra table
jsf:

```<code><rich:dataTable id="files" styleClass="table" headerClass="header"
value="#{file}" var="fileRecord" rendered="#{file.rowCount>0}"
rowClasses="even,odd" onRowMouseOver="this.style.backgroundColor='#F1F1F1'"
onRowMouseOut="this.style.backgroundColor='#{a4jSkin.tableBackgroundColor}'">
<rich:column>
</code>```

precondition:

have zebra styled table with white and gray colored rows

steps:

1. mouse hover on row,it's hovered ok

2. mouse out and it becomes white

postcondition:
table lost its "zebraness"

It's occurred bevcause of #{a4jSkin.tableBackgroundColor} evaluated to white color.

How to preserve zebra styling?

Thank you for any assistance.

答:
should be changed to:</p>

```<code>#{a4jSkin.rowBackgroundColor}
</code>```

Body:
jsf:

<rich:dataTable id="files" styleClass="table" headerClass="header"
value="#{file}" var="fileRecord" rendered="#{file.rowCount>0}"
rowClasses="even,odd" onRowMouseOver="this.style.backgroundColor='#F1F1F1'"
onRowMouseOut="this.style.backgroundColor='#{a4jSkin.tableBackgroundColor}'">
<rich:column>

precondition:

have zebra styled table with white and gray colored rows

steps:

1. mouse hover on row,it's hovered ok

2. mouse out and it becomes white

postcondition:
table lost its "zebraness"

It's occurred bevcause of #{a4jSkin.tableBackgroundColor} evaluated to white color.

How to preserve zebra styling?

Thank you for any assistance.

Body:
should be changed to:

#{a4jSkin.rowBackgroundColor}


问:
How to retrieve the count of distinct rows with some event occurring on consecutive days
I have a table with 4 columns: date, event_name, video_id and user_id.

I need to write a query that will return the number of users who viewed at least one video in a given day and the number of those users who returned the next day to view at least one video. The video_play event signifies that a video was played by a user.

Here's some sample data upon which I need to base my query:

```<code>date            event_name      video_id    user_id
2018-01-01      video_play      51651561651 989189198
2018-01-01      video_play      98121651656 561884864
2018-01-01      video_play      78918918918 561884864
2018-01-01      create_video    32156541355 153215651
2018-01-01      create_video    87351531311 232135135
2018-01-02      create_video    51651561651 489846581
2018-01-02      video_play      12315315352 561884864
2018-01-02      create_video    32156541355 321351351
2018-01-02      create_video    87351531311 231513515
2018-01-02      video_play      98191891894 615616516
</code>```

This query completes the first half of the querying task, but I cannot figure out the second half:

```<code>SELECT date
    , COUNT(DISTINCT user_id) AS users_view_videos
    FROM clickstream_video
    WHERE event_name = 'video_play'
    GROUP BY date;
</code>```

This is how the output should look:

```<code>date        users_view_videos   users_view_next_day
2018-01-01  2                   1
2018-01-02  2                   0
</code>```

答:
Hint:</p>

```<code>SELECT x.date
     , x.user_id
     , y.event_name
  FROM clickstream_video x
  LEFT
  JOIN clickstream_video y
    ON y.date = x.date + INTERVAL 1 DAY
   AND y.user_id = x.user_id
WHERE x.event_name = 'video_play';
</code>```

Body:
I have a table with 4 columns: date, event_name, video_id and user_id.

I need to write a query that will return the number of users who viewed at least one video in a given day and the number of those users who returned the next day to view at least one video. The video_play event signifies that a video was played by a user.

Here's some sample data upon which I need to base my query:

date            event_name      video_id    user_id
2018-01-01      video_play      51651561651 989189198
2018-01-01      video_play      98121651656 561884864
2018-01-01      video_play      78918918918 561884864
2018-01-01      create_video    32156541355 153215651
2018-01-01      create_video    87351531311 232135135
2018-01-02      create_video    51651561651 489846581
2018-01-02      video_play      12315315352 561884864
2018-01-02      create_video    32156541355 321351351
2018-01-02      create_video    87351531311 231513515
2018-01-02      video_play      98191891894 615616516

This query completes the first half of the querying task, but I cannot figure out the second half:

SELECT date
    , COUNT(DISTINCT user_id) AS users_view_videos
    FROM clickstream_video
    WHERE event_name = 'video_play'
    GROUP BY date;

This is how the output should look:

date        users_view_videos   users_view_next_day
2018-01-01  2                   1
2018-01-02  2                   0

Body:
Hint:

SELECT x.date
     , x.user_id
     , y.event_name
  FROM clickstream_video x
  LEFT
  JOIN clickstream_video y
    ON y.date = x.date + INTERVAL 1 DAY
   AND y.user_id = x.user_id
WHERE x.event_name = 'video_play';


问:
How can I call ActivateKeyboardLayout from 64bit Windows Vista using VBA
Running VBA under XP I was able to call ActivateKeyboardLayout to switch my input language from English to another language. However, this no longer works under Vista64.

Any suggestions or workarounds?

The code that used to work under XP was similar to the following:

```<code>Private Declare Function ActivateKeyboardLayout Lib "user32" ( _
    ByVal HKL As Long, ByVal flags As Integer) As Integer
Const aklPUNJABI As Long = &H4460446
ActivateKeyboardLayout aklPUNJABI, 0
</code>```

There was a suggestion to try

```<code>Public Declare Function ActivateKeyboardLayout Lib "user32" ( _
    ByVal nkl As IntPtr, ByVal Flags As uint) As Integer
</code>```

When I try this I get the error message:

Variable uses an Automation type not supported in Visual Basic

答:
The thing that everyone seems to overlook here is that you are working in VBA, not in .NET.  IntPtr is a .NET type which represents an integer which is native to the platform.  On a 32-bit platform it is 32 bits, on a 64 bit platform, it is 64 bits.

Given that an HKL is a typedef for a handle, which is a typedef for PVOID which is a typedef for VOID *, it's exactly what you need, if you were using .NET.

VBA doesn't have anything for 64-bit numbers, so you have to take a different approach.

On a 64-bit machine, you will have to do something like this:

```<code>Public Type HKL64
    High As Long
    Low As Long
End Type

Private Declare Function ActivateKeyboardLayout Lib "user32" ( _
    Byval HklHigh As Long, Byval HklLow As Long, _
    ByVal flags As Integer) As HKL64
</code>```

This should allow you to pass a 64 bit value on the stack to the API function (across two variables).  However, if you are going to use this code on 64 bit and 32 bit machines, you are going to have to make two declarations of the API and then determine which one to call.

Also, any other code in VBA that calls APIs that deal with pointers or handles will have to be changed appropriately to handle 64 bit input (not 32).

On a side note, the original declaration of ActivateKeyboardLayout is wrong, as it had a return type of Integer, which is a 16-bit value, while the API returns a type of HKL, which is 32 or 64 bits, depending on the platform.

OwnerDisplayName: Noah

ContentLicense: CC BY-SA 2.5

Body:
Running VBA under XP I was able to call ActivateKeyboardLayout to switch my input language from English to another language. However, this no longer works under Vista64.

Any suggestions or workarounds?

The code that used to work under XP was similar to the following:

Private Declare Function ActivateKeyboardLayout Lib "user32" ( _
    ByVal HKL As Long, ByVal flags As Integer) As Integer
Const aklPUNJABI As Long = &H4460446
ActivateKeyboardLayout aklPUNJABI, 0

There was a suggestion to try

Public Declare Function ActivateKeyboardLayout Lib "user32" ( _
    ByVal nkl As IntPtr, ByVal Flags As uint) As Integer

When I try this I get the error message:

Variable uses an Automation type not supported in Visual Basic

LastEditorDisplayName: Noah

Body:
The thing that everyone seems to overlook here is that you are working in VBA, not in .NET.  IntPtr is a .NET type which represents an integer which is native to the platform.  On a 32-bit platform it is 32 bits, on a 64 bit platform, it is 64 bits.

Given that an HKL is a typedef for a handle, which is a typedef for PVOID which is a typedef for VOID *, it's exactly what you need, if you were using .NET.

VBA doesn't have anything for 64-bit numbers, so you have to take a different approach.

On a 64-bit machine, you will have to do something like this:

Public Type HKL64
    High As Long
    Low As Long
End Type

Private Declare Function ActivateKeyboardLayout Lib "user32" ( _
    Byval HklHigh As Long, Byval HklLow As Long, _
    ByVal flags As Integer) As HKL64

This should allow you to pass a 64 bit value on the stack to the API function (across two variables).  However, if you are going to use this code on 64 bit and 32 bit machines, you are going to have to make two declarations of the API and then determine which one to call.

Also, any other code in VBA that calls APIs that deal with pointers or handles will have to be changed appropriately to handle 64 bit input (not 32).

On a side note, the original declaration of ActivateKeyboardLayout is wrong, as it had a return type of Integer, which is a 16-bit value, while the API returns a type of HKL, which is 32 or 64 bits, depending on the platform.

OwnerDisplayName: casperOne


问:
Disable browser back button for one page application
I need to disable the back button of browser in my single page application.
I tried using methods like onhashchange or window.history.forward but they don't work (reason may be that url doesn't get changed here)

答:
```<code>import { LocationStrategy } from '@angular/common';
 constructor( private location: LocationStrategy){
// preventing back button in browser implemented by "Samba Siva"
history.pushState(null, null, window.location.href);
this.location.onPopState(() => {
history.pushState(null, null, window.location.href);
});
}
</code>```


问:
Same number in hex and decimal returns different id
I presumed id() of immutable data types in python should be the same if the same value be used

But this fails if i store decimal and hex version of same integer :

```<code>In [1]: a = 0x1234

In [2]: b = 4660

In [3]: a == b
Out[3]: True

In [4]: id(a) == id(b)
Out[4]: False

In [5]: id(a)
Out[5]: 140579138155600

In [6]: id(b)
Out[6]: 140579138154736
</code>```

Why?

答: It's not about conversion, Python interpreter creates object every time you assign a big integer so those have different objects. numbers between -1 to 255 are created when interpreter starts and they have same id in all program.

Body:
I presumed id() of immutable data types in python should be the same if the same value be used

But this fails if i store decimal and hex version of same integer :

In [1]: a = 0x1234

In [2]: b = 4660

In [3]: a == b
Out[3]: True

In [4]: id(a) == id(b)
Out[4]: False

In [5]: id(a)
Out[5]: 140579138155600

In [6]: id(b)
Out[6]: 140579138154736

Why?


问:
How to put the if condition with 'throw' in a fetch...then API
I need to put an if condition with throw inside a fetch - .then function, to check if the response data is correct are not, but I don't know how to do.</p>

```<code>getWeather = (latitude, longitude) => {
    const API_KEY = "";
    const api = `http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;

    fetch(api)
      .then(response => response.json())
      .then(data => {
        this.setState({
          locationName: data.name,
          temperature: data.main.temp,
          weatherDescription: data.weather[0].description,
          isLoading: false,
        })

      })
  };
</code>```

答:
```<code>fetch(api)
  .then(response => response.json())
  .then(data => {
    this.setState({
      locationName: data.name,
      temperature: data.main.temp,
      weatherDescription: data.weather[0].description,
      isLoading: false,
    })

  })
  .catch(error=> { console.log(err) });
</code>```

you can use catch() with fetch API

Body:
I need to put an if condition with throw inside a fetch - .then function, to check if the response data is correct are not, but I don't know how to do.

getWeather = (latitude, longitude) => {
    const API_KEY = "";
    const api = `http://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}`;

    fetch(api)
      .then(response => response.json())
      .then(data => {
        this.setState({
          locationName: data.name,
          temperature: data.main.temp,
          weatherDescription: data.weather[0].description,
          isLoading: false,
        })

      })
  };

Body:
fetch(api)
  .then(response => response.json())
  .then(data => {
    this.setState({
      locationName: data.name,
      temperature: data.main.temp,
      weatherDescription: data.weather[0].description,
      isLoading: false,
    })

  })
  .catch(error=> { console.log(err) });

you can use catch() with fetch API


问:
Dockerfile CMD instruction will exit the container just after running it
I want to setup some configuration when my container starts, for this I am using shell scripts. But my container will exits as soon as my scripts ends, I have tried with -d flag / detached mode but It will never run in detached mode.

Below is my Dockerfile

```<code>FROM ubuntu:14.04

ADD shell.sh /usr/local/bin/shell.sh

RUN chmod 777 /usr/local/bin/shell.sh

CMD /usr/local/bin/shell.sh
</code>```

Below is my shell script

```<code>#!/bin/bash
echo Hello-docker
</code>```

Run without any flag

```<code>docker run hello-docker
</code>```

This will print 'Hello-docker' on my console and exits

Run with -itd flags

```<code>docker run -itd hello-docker
</code>```

and as below my console output, This time also will exits soon.  :(

The difference I saw is in COMMAND section when I run other images command section will shows "/bin/bash" and will continue in detached mode.

And when I run my image in container with shell script COMMAND section will show "/bin/sh -c /usr/loca", and Exit.

I want to run container till I not stop it manually.

EDIT:

After adding ENTRYPOINT instruction in Dockerfile, this will not execute my shell script :(

```<code>FROM ubuntu:14.04

ADD shell.sh /usr/local/bin/shell.sh

RUN chmod 777 /usr/local/bin/shell.sh

CMD /usr/local/bin/shell.sh

ENTRYPOINT /bin/bash
</code>```

As per docker documentation here

CMD will be overridden when running the container with alternative arguments, so If I run docker image with some arguments as below, will not execute CMD instructions. :(

```<code>sudo docker run -it --entrypoint=/bin/bash <imagename>
</code>```

答:
At your start shell append a line code:
tail -f /dev/null or /bin/bash
to make sure you shell done and suspend a process in system so that docker container not shutdown.Don't forget to give "chmod +x" access to start.sh.
there is demo:

```<code>#!/bin/bash
cp /root/supervisor/${RUN_SERVICE}.ini /etc/supervisor/conf.d/
sleep 1
service supervisor start
/bin/bash
</code>```

Body:
I want to setup some configuration when my container starts, for this I am using shell scripts. But my container will exits as soon as my scripts ends, I have tried with -d flag / detached mode but It will never run in detached mode.

Below is my Dockerfile

FROM ubuntu:14.04

ADD shell.sh /usr/local/bin/shell.sh

RUN chmod 777 /usr/local/bin/shell.sh

CMD /usr/local/bin/shell.sh

Below is my shell script

#!/bin/bash
echo Hello-docker

Run without any flag

docker run hello-docker

This will print 'Hello-docker' on my console and exits

Run with -itd flags

docker run -itd hello-docker

and as below my console output, This time also will exits soon.  :(

The difference I saw is in COMMAND section when I run other images command section will shows "/bin/bash" and will continue in detached mode.

And when I run my image in container with shell script COMMAND section will show "/bin/sh -c /usr/loca", and Exit.

I want to run container till I not stop it manually.

EDIT:

After adding ENTRYPOINT instruction in Dockerfile, this will not execute my shell script :(

FROM ubuntu:14.04

ADD shell.sh /usr/local/bin/shell.sh

RUN chmod 777 /usr/local/bin/shell.sh

CMD /usr/local/bin/shell.sh

ENTRYPOINT /bin/bash

As per docker documentation here

CMD will be overridden when running the container with alternative arguments, so If I run docker image with some arguments as below, will not execute CMD instructions. :(

sudo docker run -it --entrypoint=/bin/bash <imagename>

Body:
At your start shell append a line code:
tail -f /dev/null or /bin/bash
to make sure you shell done and suspend a process in system so that docker container not shutdown.Don't forget to give "chmod +x" access to start.sh.
there is demo:

#!/bin/bash
cp /root/supervisor/${RUN_SERVICE}.ini /etc/supervisor/conf.d/
sleep 1
service supervisor start
/bin/bash


问:
Using LocalStorage with React?
From what I am experiencing so far, it doesn't seem like ReactJS updates with the state of localStorage. My code below.

```<code>var Frr = React.createClass({
getInitialState: function(){
return { lights: localStorage.getItem('state')}
},

switchoff: function(){
this.setState({lights: localStorage.setItem('state', 'off')});
},

switchon:function(){
this.setState({lights: localStorage.setItem('state', 'on')});
},

render:function(){
if (this.state.lights === 'on'){ return (
<div>
<p>The lights are ON</p>
<input type="submit" value="Switch" onClick={this.switchoff}/>
</div>
);}

if ( (this.state.lights === 'off')|| (!this.state.lights) ){ return (
<div>
<p>The lights are OFF</p>
<input type="submit" value="Switch" onClick={this.switchon}/>
</div>
);}

}
});
</code>```

Simple application. If the state of localstorage is off or empty, then render the view with the ON button. If localstorage is on, then render the view with the OFF button.

I want to be able to set this render based on the state of localStorage. I have tried doing the same thing using basic booleans, and it works as expected. However, when using localStorage, something doesn't appear to work.

I wouldn't be surprised if my logic is simply off.

EDIT: To explain, the button and the view don't act as they should. When the lights are off and there is nothing in Storage, the button adds ON to localStorage, but does not change the view. If I refresh the page, the page renders ON, and when I click on it the button works by turning it OFF. But it only works once, which leads me to believe there may be a problem with the OFF switch.

答:
Use please reactjs-localstorage</p>

```<code>import {reactLocalStorage} from 'reactjs-localstorage';

reactLocalStorage.set('var', true);
reactLocalStorage.get('var', true);
reactLocalStorage.setObject('var', {'test': 'test'});
reactLocalStorage.getObject('var');
</code>```

Title: Using LocalStorage with React?

Body:
From what I am experiencing so far, it doesn't seem like ReactJS updates with the state of localStorage. My code below.

var Frr = React.createClass({
getInitialState: function(){
return { lights: localStorage.getItem('state')}
},

switchoff: function(){
this.setState({lights: localStorage.setItem('state', 'off')});
},

switchon:function(){
this.setState({lights: localStorage.setItem('state', 'on')});
},

render:function(){
if (this.state.lights === 'on'){ return (

The lights are ON

<input type="submit" value="Switch" onClick={this.switchoff}/>

);}

if ( (this.state.lights === 'off')|| (!this.state.lights) ){ return (

The lights are OFF

<input type="submit" value="Switch" onClick={this.switchon}/>

);}

}
});

Simple application. If the state of localstorage is off or empty, then render the view with the ON button. If localstorage is on, then render the view with the OFF button.

I want to be able to set this render based on the state of localStorage. I have tried doing the same thing using basic booleans, and it works as expected. However, when using localStorage, something doesn't appear to work.

I wouldn't be surprised if my logic is simply off.

EDIT: To explain, the button and the view don't act as they should. When the lights are off and there is nothing in Storage, the button adds ON to localStorage, but does not change the view. If I refresh the page, the page renders ON, and when I click on it the button works by turning it OFF. But it only works once, which leads me to believe there may be a problem with the OFF switch.

Body:
Use please reactjs-localstorage

import {reactLocalStorage} from 'reactjs-localstorage';

reactLocalStorage.set('var', true);
reactLocalStorage.get('var', true);
reactLocalStorage.setObject('var', {'test': 'test'});
reactLocalStorage.getObject('var');


问:
Should I cache the Carrierwave url?
My webhost is Heroku, which does not allow files to be saved to the local file system. Therefore, I am using Carrierwave to store my files onto Amazon S3.

In the console, I notice when I do:

```<code>Photo.last.attachment.url
</code>```

It returns:

```<code> => "https://foobar.s3.amazonaws.com/uploads/users/1/photos/7/foo.jpg"
</code>```

As expected. However, this process (of returning the value) in the console takes up 2-3 seconds. My guess is that it it trying to access S3. Even worst, when I load a web page with several photos, it takes quite a while to load.

Someone mentioned that because I am remotely storing my files via S3, I should cache the result from "Photo.last.attachment.url".

This means, in my db I would need to have two columns:

:attachment and :attachment_url

:attachment would be for the Carrierwave uploader object and :attachment_url would be the link to the S3 file directly.

Is this what I should be doing? Is there a better alternative?

答:
I would do the caching. We have done a similar approach using Paperclip.

Alternatively you could be caching the views (partials) where the URLS are being used.

Title: Should I cache the Carrierwave url?

Body:
My webhost is Heroku, which does not allow files to be saved to the local file system. Therefore, I am using Carrierwave to store my files onto Amazon S3.

In the console, I notice when I do:

Photo.last.attachment.url

It returns:

 => "https://foobar.s3.amazonaws.com/uploads/users/1/photos/7/foo.jpg"

As expected. However, this process (of returning the value) in the console takes up 2-3 seconds. My guess is that it it trying to access S3. Even worst, when I load a web page with several photos, it takes quite a while to load.

Someone mentioned that because I am remotely storing my files via S3, I should cache the result from "Photo.last.attachment.url".

This means, in my db I would need to have two columns:

:attachment and :attachment_url

:attachment would be for the Carrierwave uploader object and :attachment_url would be the link to the S3 file directly.

Is this what I should be doing? Is there a better alternative?


问:
Pretty print with libxml2?
Using libxml2.  I can pretty-print the XML into a file by using xmlSaveFormatFileEnc().  But is there a way to do the same thing into a text string or stream?

I'd like to avoid writing the XML out to a file and reading it back in just to get the pretty-print version of the XML.

For the record, what I'm doing now is the following:

```<code>xmlInitParser();
xmlKeepBlanksDefault(0);
xmlLineNumbersDefault(1);
xmlThrDefIndentTreeOutput(1);
xmlThrDefTreeIndentString("    ");

std::string content = "....."; // do something here to get the XML
xmlDoc * doc = xmlParseDoc((xmlChar*)content.c_str());

xmlSaveFormatFileEnc("output.xml", doc, "utf-8", 1); // pretty print
</code>```

答:
Stolen from here:

```<code>xmlBufferPtr buf;
/* Create a new XML buffer, to which the XML document will be
 * written */
buf = xmlBufferCreate();
if (buf == NULL) {
    std::cerr << "testXmlwriterMemory: Error creating the xml buffer" << std::endl;
    return;
}

/* Create a new XmlWriter for memory, with no compression.
 * Remark: there is no compression for this kind of xmlTextWriter */
writer = xmlNewTextWriterMemory(buf, 0);
if (writer == NULL) {
    std::cerr << "testXmlwriterMemory: Error creating the xml writer" << std::endl;
    return;
}
</code>```

And then, after you have written to the buffer:

```<code>std::cout << buf->content << std::endl
</code>```

Title: Pretty print with libxml2?

Body:
Using libxml2.  I can pretty-print the XML into a file by using xmlSaveFormatFileEnc().  But is there a way to do the same thing into a text string or stream?

I'd like to avoid writing the XML out to a file and reading it back in just to get the pretty-print version of the XML.

For the record, what I'm doing now is the following:

xmlInitParser();
xmlKeepBlanksDefault(0);
xmlLineNumbersDefault(1);
xmlThrDefIndentTreeOutput(1);
xmlThrDefTreeIndentString("    ");

std::string content = "....."; // do something here to get the XML
xmlDoc * doc = xmlParseDoc((xmlChar*)content.c_str());

xmlSaveFormatFileEnc("output.xml", doc, "utf-8", 1); // pretty print

Body:
Stolen from here:

xmlBufferPtr buf;
/* Create a new XML buffer, to which the XML document will be
 * written */
buf = xmlBufferCreate();
if (buf == NULL) {
    std::cerr << "testXmlwriterMemory: Error creating the xml buffer" << std::endl;
    return;
}

/* Create a new XmlWriter for memory, with no compression.
 * Remark: there is no compression for this kind of xmlTextWriter */
writer = xmlNewTextWriterMemory(buf, 0);
if (writer == NULL) {
    std::cerr << "testXmlwriterMemory: Error creating the xml writer" << std::endl;
    return;
}

And then, after you have written to the buffer:

std::cout << buf->content << std::endl


问:
Hover over button while still having hover effect of element behind it
I have created an element where when you hover within the area of the element a hover effect is applied (change background colour), on top of this element is a button.
When I hover over the button it causing the other hover effect to disappear, I want to be able to keep the hover for the whole time that the mouse is within the area of the first element.

Example Code Here

So when I hover over the button in the example, I still want the background of the a tag to be black. At the moment when I hover over the button it causes the black background to disappear. I also still want to be able to click on the button.

To achieve what I want to achieve would I need to use js? Or can it be done in CSS?

答:
#button1 {
  position: absolute;
  z-index: 100;
  top: 10%;
  left: 15%;
}
#label {
  position: absolute;
  z-index: -10;
  border: 1px solid red;
  width: 200px;
  height: 200px;
  text-align: center;
}
#label span {
  color: white;
}
#label:hover {
  background-color: black;
}

#label button:hover{
  color:white;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><span>Hidden Until Hover</span>
<button id="button1">Test Button</button>
</code>```

you need to wrap your button inside the #label !
this is how its work !

Body:
#button1 {
  position: absolute;
  z-index: 100;
  top: 10%;
  left: 15%;
}
#label {
  position: absolute;
  z-index: -10;
  border: 1px solid red;
  width: 200px;
  height: 200px;
  text-align: center;
}
#label span {
  color: white;
}
#label:hover {
  background-color: black;
}

#label button:hover{
  color:white;

<a id="label"><span>Hidden Until Hover</span>
<button id="button1">Test Button</button>
</a>

you need to wrap your button inside the #label !
this is how its work !


问:
Google Tag Manager how does it know pageview has occured?
I am trying to determine when gtm knows that a pageview has occurred

for instance if i have configure a pageview to be recorded at domready what is the flag of gtm that turns true when dom is ready and records that a pageview has occurred

I have read all the documentation from google and they do not provide this information.

答:
A pageview in GTM occurs when the GTM code is executed for the first time. When exactly that is depends on where in the page your GTM script is located.

That the DOM is ready is indicated by the DOMContentLoaded event. This is not the same as a page view (pageview means GTM code has been downloaded and executed, DomReady/DOMContentLoaded means that the DOM tree is rendered, but external assets like images, stylesheets and JS files might not have been loaded yet).

The load event means that both the DOM is ready and that every requested asset is fully downloaded. That might take some time (e.g. if you embed a marketing pixel and the server that hosts that pixel responds slowly then this will defer your load event, as the pixel cannot be downloaded in a timely fashion).

GTM maps these browser events to events in it's datalayer (gtm.js, gtm.dom and gtm.load respectively).


问:
ACI - VNET - IP Address
I have created Virtual Network and connected API Management to Virtual Network.

I am thinking to host my REST API in Azure Container Instances in my VNET and then expose those API in Azure API Management by configuring IP Address of Azure Container Instance REST API into Azure API Management web service url.

I have one doubt, if this is right way of doing it.

I am wondering if Azure Container Instance gets restarted and if IP Address will change, then my API exposed in API Mangament will be broken. Does IP Address gets changed if Azure Container Instances gets restarted for some reason.

答:
There are some limitations for Azure container instances.

The IP address of a container won't typically change between updates,
  but it's not guaranteed to remain the same. As long as the container
  group is deployed to the same underlying host, the container group
  retains its IP address. Although rare, and while Azure Container
  Instances makes every effort to redeploy to the same host, there are
  some Azure-internal events that can cause redeployment to a different
  host. To mitigate this issue, always use a DNS name label for your
  container instances.

Terminated or deleted container groups can't be updated. Once a
  container group has stopped (is in the Terminated state) or has been
  deleted, the group is deployed as new.

However, It's a rare case that Azure container instances will be redeployed to a different host. Also, if you have a container instance in a VNet, you're unable to directly set a --dns-name-label value and you only could access the instance via its private IP address from the outside world and other container groups. Note: Containers in a group are not discoverable through DNS. They can only be accessed through ‘localhost’, in combination with their exposed ports. You could get more references from More about networking in this blog.

Title: ACI - VNET - IP Address


问:
Removing Element from Document Flow
I'm using a [type=checkbox] to record the user input for a custom dropdown menu that I created. I'm also using it for the required functionality in browsers too.

The issue I'm running into, however, is that the element seems to need at least 1px of height in order to trigger the browser warning message when a user tries to submit the form without filling out that part. This is an issue because the dropdown menu has a height of auto, so as soon as the browser warning message is displayed, it shifts everything up so that there is a 1px gap at the bottom.

Notably, the content only shifts if or once the warning message is displayed.

I know that I can fix this by positioning the element absolutely with JS, but I'm trying to use as little JS as possible. Hence I've given the container a position: relative, and positioned the element so that it always displays at the bottom center of the container element like all of the other fields.

```<code>#dropdown {
  position: relative;
}

#subject {
  width: 1px;
  height: 1px;
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  pointer-events: none;
  padding: 0;
  opacity: 0;
  margin: 0;
}
</code>```

As I stated above, I've already tried giving it a height of 0, but by doing this the warning message does not trigger. I've also tried a couple different display values (and I will be going through the rest of them once I finish positing this). I've also tried applying position: absolute; bottom: 0; to the last option in the list. None of this stuff works.

const
  option = document.querySelector('#option')

document.querySelector('#dropdown').addEventListener('click', function(){
  option.style.maxHeight = option.scrollHeight + 'px'
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dropdown {
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
  border: solid red 3px;
}

#label {
  padding: 50px;
}

#option {
  max-height: 0;
  transition:
    .5s max-height;
}

#option:hover {
  background: skyblue;
}

#checkbox {
  width: 5px;
  height: 5px; /* added extra pixels to emphasize the issue */
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  pointer-events: none;
  padding: 0;
  opacity: 0;
  margin: 0;
}</code>```

<form>

Subject

Last Option

    <input id='checkbox' type='checkbox' required />

  <input type='submit' />
</form>```

Does anybody have any ideas how I might be able to do this with CSS alone?

Is it even possible since the container has a height of auto?

答:
Using position: static with display: block seems to work for me. This does make the tool tip appear at the top of the div, however:

const option = document.getElementById('option')

document.getElementById('dropdown').addEventListener('click', function(){
  option.style.maxHeight = option.scrollHeight + 'px'
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#dropdown {
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
  border: solid red 3px;
}

#label {
  padding: 50px;
}

#option {
  max-height: 0;
  transition:
    .5s max-height;
}

#option:hover {
  background: skyblue;
}

#checkbox {
    /* display: block; */
    width: 100%;
    /* height: 11px; */
    position: absolute;
    pointer-events: none;
    bottom: 0;
    padding: 0;
    opacity: 0;
    margin: 0;
    background-color: #0f0f0f;
    width: 5px;
    left: 50%;
}

#checkbox {

}</code>```

<form>

Subject

Last Option

    <input id='checkbox' type='checkbox' required />

  <input type='submit' />
</form>```

I have found that using top: 100%; is the issue here.

Title: Removing Element from Document Flow

Body:
I'm using a [type=checkbox] to record the user input for a custom dropdown menu that I created. I'm also using it for the required functionality in browsers too.

The issue I'm running into, however, is that the element seems to need at least 1px of height in order to trigger the browser warning message when a user tries to submit the form without filling out that part. This is an issue because the dropdown menu has a height of auto, so as soon as the browser warning message is displayed, it shifts everything up so that there is a 1px gap at the bottom.

Notably, the content only shifts if or once the warning message is displayed.

I know that I can fix this by positioning the element absolutely with JS, but I'm trying to use as little JS as possible. Hence I've given the container a position: relative, and positioned the element so that it always displays at the bottom center of the container element like all of the other fields.

#dropdown {
  position: relative;
}

#subject {
  width: 1px;
  height: 1px;
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  pointer-events: none;
  padding: 0;
  opacity: 0;
  margin: 0;
}

As I stated above, I've already tried giving it a height of 0, but by doing this the warning message does not trigger. I've also tried a couple different display values (and I will be going through the rest of them once I finish positing this). I've also tried applying position: absolute; bottom: 0; to the last option in the list. None of this stuff works.

const
  option = document.querySelector('#option')

document.querySelector('#dropdown').addEventListener('click', function(){
  option.style.maxHeight = option.scrollHeight + 'px'
})

#dropdown {
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
  border: solid red 3px;
}

#label {
  padding: 50px;
}

#option {
  max-height: 0;
  transition:
    .5s max-height;
}

#option:hover {
  background: skyblue;
}

#checkbox {
  width: 5px;
  height: 5px; /* added extra pixels to emphasize the issue */
  position: absolute;
  top: 100%;
  left: 50%;
  transform: translateX(-50%);
  pointer-events: none;
  padding: 0;
  opacity: 0;
  margin: 0;
}

<form>

Subject

Last Option

    <input id='checkbox' type='checkbox' required />

  <input type='submit' />
</form>

Does anybody have any ideas how I might be able to do this with CSS alone?

Is it even possible since the container has a height of auto?

Body:
Using position: static with display: block seems to work for me. This does make the tool tip appear at the top of the div, however:

const option = document.getElementById('option')

document.getElementById('dropdown').addEventListener('click', function(){
  option.style.maxHeight = option.scrollHeight + 'px'
})

#dropdown {
  position: relative;
  overflow: hidden;
  box-sizing: border-box;
  border: solid red 3px;
}

#label {
  padding: 50px;
}

#option {
  max-height: 0;
  transition:
    .5s max-height;
}

#option:hover {
  background: skyblue;
}

#checkbox {
    /* display: block; */
    width: 100%;
    /* height: 11px; */
    position: absolute;
    pointer-events: none;
    bottom: 0;
    padding: 0;
    opacity: 0;
    margin: 0;
    background-color: #0f0f0f;
    width: 5px;
    left: 50%;
}

#checkbox {

}

<form>
  <div id='dropdown'>
    <div id='label'>Subject</div>
    <div id='option'>Last Option</div>
    <input id='checkbox' type='checkbox' required />
  </div>
  <input type='submit' />
</form>

I have found that using top: 100%; is the issue here.


问:
Azure Analytics Query to see which ID has a StartTime before another ID's EndTime where the cloudRoleInstance is the same
Title says it all - I have App Insights Data that looks like this:

I need a query to go through this data and return to me - ID's 12345 and 09282 - because 09282 starts before 12345 and they are both on the same node.

Any help or pointers would be greatly appreciated.

答:
Please try to use join operator.

Sample code like below(assume the table name is mytable):

```<code>let mytablesss = mytable
| where timestamp > ago(7d);
mytablesss
| join kind= inner (
   mytable
   | where timestamp > ago(7d)
) on cloudRoleInstance
| where StartTime < EndTime1

//if startTime and EndTime are string type, use todatetime(StartTime) and todatetime(EndTime1) in the where clause.
</code>```

Please feel free to modify the code to meet your need.

Note that: in the 2nd table(mytable), all the fields will be automatically suffix with 1, eg. in the first table, the filed is Endtime; but in the 2nd table, it becomes Endtime1.

Body:
Please try to use join operator.

Sample code like below(assume the table name is mytable):

let mytablesss = mytable
| where timestamp > ago(7d);
mytablesss
| join kind= inner (
   mytable
   | where timestamp > ago(7d)
) on cloudRoleInstance
| where StartTime < EndTime1

//if startTime and EndTime are string type, use todatetime(StartTime) and todatetime(EndTime1) in the where clause.

Please feel free to modify the code to meet your need.

Note that: in the 2nd table(mytable), all the fields will be automatically suffix with 1, eg. in the first table, the filed is Endtime; but in the 2nd table, it becomes Endtime1.


问:
How to give access to users belonged to one Resource Group ,so that they do not find out the service account credentials?
I have created an Azure Container Registry ,have Microsoft subscription inherited to the users in that particular Resource Group .How to give access to the users as they can login to the registry using only service principal credentials.What privilege permissions should I give so that they cannot view the credentials in the portal.azure.com and should not push or pull docker images using service principal credentials?</p>

答:
All the roles and permissions for the ACR are shows in the Azure Container Registry roles and permissions. You can just choose one which you want to use.

The service principal is a little different from the users to do something with appropriate permission. For example, you can use a service principal with only acrpull permission to pull the image even the users have the permission to push, but login with the service principal, it just can pull the image.


问:
Logging with Retrofit 2
I'm trying to get the exact JSON that is being sent in the request. Here is my code:

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor(){
   @Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
      Request request = chain.request();
      Log.e(String.format("\nrequest:\n%s\nheaders:\n%s",
                          request.body().toString(), request.headers()));
      com.squareup.okhttp.Response response = chain.proceed(request);
      return response;
   }
});
Retrofit retrofit = new Retrofit.Builder()
   .baseUrl(API_URL)
   .addConverterFactory(GsonConverterFactory.create())
   .client(client).build();
```

<p>But I only see this in the logs:</p>

```request:
com.squareup.okhttp.RequestBody$1@3ff4074d
headers:
Content-Type: application/vnd.ll.event.list+json
```

How am I supposed to do proper logging, given the removal of setLog() and setLogLevel() which we used to use with Retrofit 1?

答:
First Add dependency to build.gradle:

implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'

While using Kotlin you can add Logging Interceptor like this :

```<code>companion object {
    val okHttpClient = OkHttpClient().newBuilder()
            .addInterceptor(HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            })
            .build()

    fun getRetrofitInstance(): Retrofit {
        val retrofit = Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(ScanNShopConstants.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        return retrofit
    }
}
</code>```

Title: Logging with Retrofit 2

Body:
I'm trying to get the exact JSON that is being sent in the request. Here is my code:

OkHttpClient client = new OkHttpClient();
client.interceptors().add(new Interceptor(){
   @Override public com.squareup.okhttp.Response intercept(Chain chain) throws IOException {
      Request request = chain.request();
      Log.e(String.format("\nrequest:\n%s\nheaders:\n%s",
                          request.body().toString(), request.headers()));
      com.squareup.okhttp.Response response = chain.proceed(request);
      return response;
   }
});
Retrofit retrofit = new Retrofit.Builder()
   .baseUrl(API_URL)
   .addConverterFactory(GsonConverterFactory.create())
   .client(client).build();

But I only see this in the logs:

request:
com.squareup.okhttp.RequestBody$1@3ff4074d
headers:
Content-Type: application/vnd.ll.event.list+json

How am I supposed to do proper logging, given the removal of setLog() and setLogLevel() which we used to use with Retrofit 1?

Body:
First Add dependency to build.gradle:

implementation 'com.squareup.okhttp3:logging-interceptor:3.12.1'

While using Kotlin you can add Logging Interceptor like this :

companion object {
    val okHttpClient = OkHttpClient().newBuilder()
            .addInterceptor(HttpLoggingInterceptor().apply {
                level = HttpLoggingInterceptor.Level.BODY
            })
            .build()

    fun getRetrofitInstance(): Retrofit {
        val retrofit = Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(ScanNShopConstants.BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build()

        return retrofit
    }
}


答:
Like this:</p>

```<code>fetch(api)
      .then(response => response.json())
      .then(data => {
               if(**YOUR_CONDITION_HERE**){

                  this.setState({
                   locationName: data.name,
                   temperature: data.main.temp,
                   weatherDescription: data.weather[0].description,
                   isLoading: false,

               } else {

                  throw new Error("data invalid");

       }).catch(err => console.log(err));
</code>```

Title: How to put the if condition with 'throw' in a fetch...then API

Body:
Like this:

fetch(api)
      .then(response => response.json())
      .then(data => {
               if(**YOUR_CONDITION_HERE**){

                  this.setState({
                   locationName: data.name,
                   temperature: data.main.temp,
                   weatherDescription: data.weather[0].description,
                   isLoading: false,

               } else {

                  throw new Error("data invalid");

       }).catch(err => console.log(err));


问:
Javadoc task in Ant build fails
I'm receiving an error message from Ant  when I try to run the Javadoc ant task.

"BUILD FAILED
/data/data/com.termux/files/home/LearnJava/Observer/build.xml:39: No source files, no packages and no modules have been specified."

The build files reside at:

https://github.com/Fernal73/LearnJava/blob/master/Observer/build.properties

```<code>version=1.0.0
main.class=com.javacodegeeks.patterns.observerpattern.TestObserver
main.class1=com.javacodegeeks.patterns.observerpattern.Test
cs.properties=../checkstyle.properties
gformat.properties=../gformat.properties
ant.build.javac.source=1.7
ant.build.javac.target=1.7
packages=com.javacodegeeks.patterns.observerpatern.*

</code>```

and
https://github.com/Fernal73/LearnJava/blob/master/Observer/build.xml

```<code><?xml version="1.0"?>
<project name="Observer" default="main"
  basedir=".">
  <property file = "build.properties"/>
  <property file = "${cs.properties}"/>
  <property file = "${gformat.properties}"/>
    <!-- Sets variables which can later be used. -->
    <!-- The value of a property is accessed via ${} -->
    <property name="src.dir" location="." />
    <property name="build.dir" location="." />
    <property name="dist.dir" location="dist" />
    <property name="docs.dir" location="docs" />
    <taskdef resource="${cs.taskdef.resource}"
      classpath="../${cs.jar}"/>
    <!-- Deletes the existing build, docs and dist directory-->
    <target name="clean">
        <delete>
            <fileset dir="." includes="**/*.class"/>
    </delete>
        <delete dir="${docs.dir}" />
        <delete dir="${dist.dir}" />
    </target>
    <!-- Creates the  build, docs and dist directory-->
    <target name="makedir">
        <mkdir dir="${docs.dir}" />
        <mkdir dir="${dist.dir}" />
    </target>
    <!-- Compiles the java code (including the usage of library for JUnit -->
    <target name="compile" depends="clean, makedir,gformat,checkstyle">
        <javac includeantruntime="false" srcdir="${src.dir}" destdir="${build.dir}">
<compilerarg value="-Xlint:-options"/>
        </javac>
    </target>
    <!-- Creates Javadoc -->
    <target name="docs" depends="compile">
      <javadoc  packagenames="${packages}" additionalparam="-Xdoclint:none"
        sourcepath="${src.dir}"
        destdir="${docs.dir}">
            <!-- Define which files / directory should get included, we include all -->
             <fileset dir="${src.dir}">
                <include name="*.java" />
             </fileset>
        </javadoc>
      </target>
      <target name="manifest">
        <tstamp/>
      <manifest file="manifest.mf">
  <attribute name="Built-By" value="${user.name}"/>
<section name="common">
    <attribute name="Specification-Title" value="${ant.project.name}"/>
    <attribute name="Specification-Version" value="${version}"/>
    <attribute name="Specification-Vendor" value=""/>
    <attribute name="Implementation-Title" value=""/>
    <attribute name="Implementation-Version" value="${build} ${TODAY}"/>
    <attribute name="Implementation-Vendor" value=""/>
  </section>
  <attribute name="Main-Class" value="${main.class}" />
</manifest>
</target>
    <!--Creates the deployable jar file  -->
    <target name="jar" depends="compile,manifest">
      <jar destfile="${dist.dir}\${ant.project.name}.jar" basedir="${build.dir}" includes="**/*.class"
        manifest="manifest.mf">
</jar>
</target>
<target name="run" >
<description>Run target</description>
<java classname="${main.class}">
 <classpath>
   <pathelement location="${dist.dir}\${ant.project.name}.jar"/>
<pathelement path="${java.class.path}"/>
</classpath>
</java>
</target>
<target name="gformat">
  <exec executable="find" dir="${basedir}"
    failonerror="true" outputproperty="sources">
            <arg line=" . -type f -name '*.java'"/>
          </exec>
          <echo message="About to format ...: ${sources}"/>
          <java classname="${gformat.main.class}">
            <arg line=" -i ${sources}"/>
 <classpath>
   <pathelement location="../${gformat.jar}"/>
<pathelement path="${java.class.path}"/>
</classpath>
</java>
    </target>
<target name="checkstyle">
  <first id="checkstylefile">
    <fileset dir=".." includes="${cs.config}"/>
  </first>
  <checkstyle config="${toString:checkstylefile}"
    classpath="../${cs.jar}"
    failOnViolation="false" properties="${cs.properties}">
  <fileset dir="${src.dir}" includes="**/*.java"/>
  <formatter type="plain"/>
  <formatter type="plain" toFile="${cs.output}"/>
</checkstyle>
</target>
<target name="main" depends="compile, jar, docs">
        <description>Main target</description>
    </target>
</project>
</code>```

respectively.

My other projects on the repository have similar configurations.

They work as expected.

Am I missing something obvious?

I did miss something obvious. An extra 't' in the property packages. Evidently, I'm going to need two sets of eyes for this or a fresh set, a few hours later!

NOW, how do I close this?

答:
I think the problem is in following part:

```<code><fileset dir="${src.dir}">
    <include name="*.java" />
</fileset>
</code>```

In Ant "*.java" means all files with names matching *.java. This does not search in subdirectories.
To include all subdirectories you must specify:

```<code><fileset dir="${src.dir}">
    <include name="**/*.java" />
</fileset>
</code>```

But since you already specified the sourcePath attribute I'm wondering if you can't just remove the fileset element as ant will add **/*.java by default.

Title: Javadoc task in Ant build fails

Body:
I'm receiving an error message from Ant  when I try to run the Javadoc ant task.

"BUILD FAILED
/data/data/com.termux/files/home/LearnJava/Observer/build.xml:39: No source files, no packages and no modules have been specified."

The build files reside at:

https://github.com/Fernal73/LearnJava/blob/master/Observer/build.properties

version=1.0.0
main.class=com.javacodegeeks.patterns.observerpattern.TestObserver
main.class1=com.javacodegeeks.patterns.observerpattern.Test
cs.properties=../checkstyle.properties
gformat.properties=../gformat.properties
ant.build.javac.source=1.7
ant.build.javac.target=1.7
packages=com.javacodegeeks.patterns.observerpatern.*

and
https://github.com/Fernal73/LearnJava/blob/master/Observer/build.xml

<?xml version="1.0"?>
<project name="Observer" default="main"
  basedir=".">
  <property file = "build.properties"/>
  <property file = "${cs.properties}"/>
  <property file = "${gformat.properties}"/>

    <property name="src.dir" location="." />
    <property name="build.dir" location="." />
    <property name="dist.dir" location="dist" />
    <property name="docs.dir" location="docs" />
    <taskdef resource="${cs.taskdef.resource}"
      classpath="../${cs.jar}"/>

    <target name="clean">
        <delete>
            <fileset dir="." includes="**/*.class"/>
    </delete>
        <delete dir="${docs.dir}" />
        <delete dir="${dist.dir}" />
    </target>

    <target name="makedir">
        <mkdir dir="${docs.dir}" />
        <mkdir dir="${dist.dir}" />
    </target>

    <target name="compile" depends="clean, makedir,gformat,checkstyle">
        <javac includeantruntime="false" srcdir="${src.dir}" destdir="${build.dir}">
<compilerarg value="-Xlint:-options"/>
        </javac>
    </target>

    <target name="docs" depends="compile">
      <javadoc  packagenames="${packages}" additionalparam="-Xdoclint:none"
        sourcepath="${src.dir}"
        destdir="${docs.dir}">

             <fileset dir="${src.dir}">
                <include name="*.java" />
             </fileset>
        </javadoc>
      </target>
      <target name="manifest">
        <tstamp/>
      <manifest file="manifest.mf">
  <attribute name="Built-By" value="${user.name}"/>

    <attribute name="Specification-Title" value="${ant.project.name}"/>
    <attribute name="Specification-Version" value="${version}"/>
    <attribute name="Specification-Vendor" value=""/>
    <attribute name="Implementation-Title" value=""/>
    <attribute name="Implementation-Version" value="${build} ${TODAY}"/>
    <attribute name="Implementation-Vendor" value=""/>

  <attribute name="Main-Class" value="${main.class}" />
</manifest>
</target>

    <target name="jar" depends="compile,manifest">
      <jar destfile="${dist.dir}\${ant.project.name}.jar" basedir="${build.dir}" includes="**/*.class"
        manifest="manifest.mf">
</jar>
</target>
<target name="run" >
<description>Run target</description>
<java classname="${main.class}">
 <classpath>
   <pathelement location="${dist.dir}\${ant.project.name}.jar"/>
<pathelement path="${java.class.path}"/>
</classpath>
</java>
</target>
<target name="gformat">
  <exec executable="find" dir="${basedir}"
    failonerror="true" outputproperty="sources">
            <arg line=" . -type f -name '*.java'"/>
          </exec>
          <echo message="About to format ...: ${sources}"/>
          <java classname="${gformat.main.class}">
            <arg line=" -i ${sources}"/>
 <classpath>
   <pathelement location="../${gformat.jar}"/>
<pathelement path="${java.class.path}"/>
</classpath>
</java>
    </target>
<target name="checkstyle">
  <first id="checkstylefile">
    <fileset dir=".." includes="${cs.config}"/>
  </first>
  <checkstyle config="${toString:checkstylefile}"
    classpath="../${cs.jar}"
    failOnViolation="false" properties="${cs.properties}">
  <fileset dir="${src.dir}" includes="**/*.java"/>
  <formatter type="plain"/>
  <formatter type="plain" toFile="${cs.output}"/>
</checkstyle>
</target>
<target name="main" depends="compile, jar, docs">
        <description>Main target</description>
    </target>
</project>

respectively.

My other projects on the repository have similar configurations.

They work as expected.

Am I missing something obvious?

I did miss something obvious. An extra 't' in the property packages. Evidently, I'm going to need two sets of eyes for this or a fresh set, a few hours later!

NOW, how do I close this?

Body:
I think the problem is in following part:

<fileset dir="${src.dir}">
    <include name="*.java" />
</fileset>

In Ant "*.java" means all files with names matching *.java. This does not search in subdirectories.
To include all subdirectories you must specify:

<fileset dir="${src.dir}">
    <include name="**/*.java" />
</fileset>

But since you already specified the sourcePath attribute I'm wondering if you can't just remove the fileset element as ant will add **/*.java by default.


问:
Q: How to check the extension of an URL website?
I would like to know if there is a way to check the extension of an URL website ? For example, do something when the website is like http://example.es/ and do another thing when the website is like http://example.fr/

I have check that there is something like

```<code>$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
</code>```

which returns the current URL of the web page.

Thanks for help.

答:
Use parse_url() function to get host part of the url then explode by . and get last element of an array

Example below:

```<code>    $url =  'http://' . $_SERVER['SERVER_NAME'];
    echo end(explode(".", parse_url($url, PHP_URL_HOST)));
    // echos "com"
</code>```

Body:
I would like to know if there is a way to check the extension of an URL website ? For example, do something when the website is like http://example.es/ and do another thing when the website is like http://example.fr/

I have check that there is something like

$actual_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

which returns the current URL of the web page.

Thanks for help.

Body:
Use parse_url() function to get host part of the url then explode by . and get last element of an array

Example below:

    $url =  'http://' . $_SERVER['SERVER_NAME'];
    echo end(explode(".", parse_url($url, PHP_URL_HOST)));
    // echos "com"


问:
render html in flex 4 (web) without an iframe
I know this question was asked before, but none of the solutions work properly.
How do I render a basic html in flex 4 without an iframe? I saw textarea renders some weird format that would suffice if it would work.

For example I wan't to add an image like this

```<code>text_area.htmlText += "<img src='...' />";
</code>```

then 1. I press enter 2. I add the image again like above, I get the img tag inserted 10 times or so; which is weird (but not funny at all). All things being equal, html is a much normal approach, is there a basic renderer for flex 4 that works ok? Thanks

答:
You'll want to use either RichText or RichEditableText component to show your html using TLF.  You'll want to do something like this:

```<code><s:RichText textFlow="{TextConverter.importToFlow(yourHtmlString, TextConverter.TEXT_FIELD_HTML_FORMAT)}" />
</code>```

However, you should know that if you have a lot of html, the conversion is going to take longer.

Body:
I know this question was asked before, but none of the solutions work properly.
How do I render a basic html in flex 4 without an iframe? I saw textarea renders some weird format that would suffice if it would work.

For example I wan't to add an image like this

text_area.htmlText += "";

then 1. I press enter 2. I add the image again like above, I get the img tag inserted 10 times or so; which is weird (but not funny at all). All things being equal, html is a much normal approach, is there a basic renderer for flex 4 that works ok? Thanks

Body:
You'll want to use either RichText or RichEditableText component to show your html using TLF.  You'll want to do something like this:

<s:RichText textFlow="{TextConverter.importToFlow(yourHtmlString, TextConverter.TEXT_FIELD_HTML_FORMAT)}" />

However, you should know that if you have a lot of html, the conversion is going to take longer.