问:
How to made CustomPaint like this in flutter
I know it's not the best way but I really can't do this. How to made something like this. I'm suck in geometry. I try to do this with cubicTo but I cen't get this effect :/.

Can someone help me. Below is part of my code.

```<code>var sw = size.width;
var sh = size.height;

var path = Path();

path.cubicTo(sw/2, 0, sw/4, 0, 2*sw/4, 2*sh/4);
path.cubicTo(2*sw/3, 2*sh/3, sw/3, 0, sw, 0);
path.cubicTo(0, 0, 0, 0, sw, 0);
path.lineTo(sw, sh);
path.lineTo(0, sh);
path.close();
</code>```

答:
Path@arcToPoint is useful for drawing circle/oval segments.

For example, for a circle with radius equal to half rect's height:

```<code>final w = size.width;
final h = size.height;
final r = h / 2;

final path = Path();
path.moveTo(0, 0);
path.lineTo(w / 2 - r, 0);
path.arcToPoint(
  Offset(w / 2 + r, 0),
  radius: Radius.circular(r),
  clockwise: false,
);
path.lineTo(w, 0);
path.lineTo(w, h);
path.lineTo(0, h);
path.close();
</code>```

Body:
I know it's not the best way but I really can't do this. How to made something like this. I'm suck in geometry. I try to do this with cubicTo but I cen't get this effect :/.

Can someone help me. Below is part of my code.

var sw = size.width;
var sh = size.height;

var path = Path();

path.cubicTo(sw/2, 0, sw/4, 0, 2*sw/4, 2*sh/4);
path.cubicTo(2*sw/3, 2*sh/3, sw/3, 0, sw, 0);
path.cubicTo(0, 0, 0, 0, sw, 0);
path.lineTo(sw, sh);
path.lineTo(0, sh);
path.close();

Body:
Path@arcToPoint is useful for drawing circle/oval segments.

For example, for a circle with radius equal to half rect's height:

final w = size.width;
final h = size.height;
final r = h / 2;

final path = Path();
path.moveTo(0, 0);
path.lineTo(w / 2 - r, 0);
path.arcToPoint(
  Offset(w / 2 + r, 0),
  radius: Radius.circular(r),
  clockwise: false,
);
path.lineTo(w, 0);
path.lineTo(w, h);
path.lineTo(0, h);
path.close();


来源: stackexchange

问:
Categorize Traffic with Specific (non-UTM) Parameter as Email Traffic
I have traffic coming from Salesloft emails sent by sales reps that gets bounced off a subdomain and then has a sbrc parameter appended to the URL. I'd like to ensure that this traffic gets counted by Google Analytics as coming from Email, whereas it's currently falling under the "Direct" bucket. Ideally, users would also be appending utm parameters to their links, but this isn't happening consistently.

I tried creating a filter to search and replace the following regex (?:^|\?|&)(sbrc=[^&]*&?) with ?utm_medium=email&utm_source=salesloft in the Request URI. This changed the displayed URL when looking at my realtime traffic, but did not change how GA categorized the channel of the traffic (still direct).

I then tried editing the default channel groupings for Email to be the system categorized OR Landing Page URL contains "sbrc" and dragged Email to the first channel grouping at the top. This doesn't seem to have done anything at all.

How can I make GA recognize this custom parameter as being attributable to the Email channel?

答:
You could use advanced filters to solve this task. The Advanced filter lets you construct Fields for reporting from one or two existing Fields.

In your case, advanced filters let you assign values to campaign source and campaign medium, based on the content of the request URL. This is a sample setup for the source field, and you need a second similar filter for medium as well:

ContentLicense: CC BY-SA 4.0


问:
Is there a tree control for the iphone?
Is there a Tree control available for the iphone?

I need to represent a tree with sub nodes in a tree, how can I do it?

Thanks

答:
See this help

Rolling your own iPhone treeview control

part 1 : http://dotnet.kapenilattex.com/?p=566, part 2 and part 3 are in the pages : 585 and 633
part 4 : http://dotnet.kapenilattex.com/?p=648&cpage=1#comment-59842

ContentLicense: CC BY-SA 3.0

Title: Is there a tree control for the iphone?


问:
ReactJS: How can I play an html5 video with an onClick event correctly with react?
In my react component I have a video tag like so:

```<code>  <video>
    <source src="https://fake.com/file.mp4" type="video/mp4" />
  </video>
</code>```

And I have a button a bit further down that I would like to use to activate the video:

```<code><button onClick={playVideoFunc?}/>
</code>```

I assume I will be using some sort of on click event to trigger the video play and I know I can use the following javascript code to do it:

```<code>var v = document.getElementsByTagName("video")[0];
v.play();
</code>```

But sense this is my first time using react I was wondering if there was a  more "reacty" way of doing this? Additionally if I do have to use pure javascript like above is it appropriate to put that code inside the react component itself? For reference my component looks like this (minus some details):

```<code>import React, { Component } from 'react';
import Footer from './footerComponent'
import Navbar from './navbarComponent';

class Home extends React.Component{
  render() {

    return (
      <div className="wrapper home-page">
        <div className="jumbotron-video-wrapper">
          <video>
            <source src="https://fake.com/file.mp4" type="video/mp4" />
          </video>
        </div>
        <Navbar type={"transparent"}/>
        <div className="jumbotron margin-bottom-20" style={heroStyle}>
          <div className="container-fluid">
            <div className="row">
              <div className="col-md-8 col-md-offset-2 text-center">
                <h1>WORDS WORDS WORDS</h1>
                <img onClick={playvideo??} width="130" src={playImage}/>
                <p className="thin">Watch our video</p>
              </div>
            </div>
          </div>
        </div>
        <Footer/>
      </div>
    )
  }
};

export default Home;
</code>```

答:
you could also do onClick={e => e.target.play()} on the video element.
hope this helps</p>

Body:
In my react component I have a video tag like so:

  <video>
    <source src="https://fake.com/file.mp4" type="video/mp4" />
  </video>

And I have a button a bit further down that I would like to use to activate the video:

<button onClick={playVideoFunc?}/>

I assume I will be using some sort of on click event to trigger the video play and I know I can use the following javascript code to do it:

var v = document.getElementsByTagName("video")[0];
v.play();

But sense this is my first time using react I was wondering if there was a  more "reacty" way of doing this? Additionally if I do have to use pure javascript like above is it appropriate to put that code inside the react component itself? For reference my component looks like this (minus some details):

import React, { Component } from 'react';
import Footer from './footerComponent'
import Navbar from './navbarComponent';

class Home extends React.Component{
  render() {

    return (

          <video>
            <source src="https://fake.com/file.mp4" type="video/mp4" />
          </video>

        <Navbar type={"transparent"}/>

WORDS WORDS WORDS

Watch our video

    )
  }
};

export default Home;


问:
I get an Error JNA while trying to run my java program from CLI
I get this error when trying to run my program from CLI:

Error: A JNI error has occurred, please check your installation and try again
Exception in thread "main" java.lang.UnsupportedClassVersionError: daniel has been compiled by a more recent version of the Java Runtime (class file version 58.0), this version of the Java Runtime only recognizes class file versions up to 52.0

I have Windows 10
Already tried updating the path following these steps:

Search for Advanced System Settings in your windows Search box. Click on Advanced System Settings.

Click on Environment variables button: Environment Variables popup will open.

Go to system variables session, and click on New button to create new variable (HOME_PATH), then New System Variables popup will open.

Give Variable Name: JAVA_HOME, and Variable value : Your Java SDK home path. Ex: C:\Profram files\java\jdk1.8.0_151 Note: It should not include \bin. Then click on OK button.

Now you are able to see your JAVA_HOME in system variables list.

Select Path (from system variables list) and click on Edit button, A new pop will opens (Edit Environment Variables). It was introduced in windows 10.

Click on New button and give %JAVA_HOME%\bin at highlighted field and click Ok button.

Didn't work, also tried uninstalling the JDK and reinstalling but same issue, I installed the JDK from this link: https://www.oracle.com/java/technologies/javase/javase-jdk8-downloads.html

Any clue?

答:
Class file version 58.0 belongs to java 14 (source).

You need to use java 14, instead of java 8 to run your program.

Alternatively you could compile your project using java 8.


问:
Supplying another function to sum() as a start parameter
I have seen the below function in a tutorial about packaging.

My doubt is in sum() which takes Counter() as the start parameter. What would happen in this case?

# Import needed functionality
from collections import Counter

def sum_counters(counters):
  # Sum the inputted counters
  return sum(counters, Counter())
```

<p>I tried replicating using the below code </p>

<pre class="lang-py prettyprint-override"><code>a=[2,3,3,4,5,5,6]
sum(a,len())
</code>```

Result:

```<code>TypeError: len() takes exactly one argument (0 given)
</code>```

I'm unable to replicate it with Counter() (due to an error in pip while downloading collections package), nor am i able to find any documentation that mentions about giving functions as the start parameters.

Could anyone throw some light on this. Thanks

答:
My doubt is in the sum() which takes Counter() as the start parameter. What would happen in this case ?

Just as in any other case, it takes the initial Counter() and adds the first element of counters to it, then it adds the next one to that result, and so on. This is the same as if you had used the + symbol between all of the Counter instances explicitly. To understand what that does, see the documentation.

TypeError: len() takes exactly one argument (0 given)

Well, yes, like it says; len needs to know what to get the length of. I don't understand what you want this sum call to do.

nor am i able to find any documentation that mentions about giving functions as the start parameters.

collections.Counter isn't a function; it's a class. However, len(x) isn't a function either; it's the result of calling that function. (Similarly, the result of calling the collections.Counter class is a collections.Counter instance.) Anyway, it doesn't matter where the start parameter comes from; what matters is the value it has. For example:

```<code>a=[2,3,3,4,5,5,6]
sum(a,len(a))
</code>```

a has 7 items in it, so len(a) is equal to 7, and the result is the same as writing sum(a, 7) directly. That is 7 + 2 + 3 + 3 + 4 + 5 + 5 + 6 = 35.

Body:
I have seen the below function in a tutorial about packaging.

My doubt is in sum() which takes Counter() as the start parameter. What would happen in this case?

# Import needed functionality
from collections import Counter

def sum_counters(counters):
  # Sum the inputted counters
  return sum(counters, Counter())

I tried replicating using the below code

a=[2,3,3,4,5,5,6]
sum(a,len())

Result:

TypeError: len() takes exactly one argument (0 given)

I'm unable to replicate it with Counter() (due to an error in pip while downloading collections package), nor am i able to find any documentation that mentions about giving functions as the start parameters.

Could anyone throw some light on this. Thanks

Body:
My doubt is in the sum() which takes Counter() as the start parameter. What would happen in this case ?

Just as in any other case, it takes the initial Counter() and adds the first element of counters to it, then it adds the next one to that result, and so on. This is the same as if you had used the + symbol between all of the Counter instances explicitly. To understand what that does, see the documentation.

TypeError: len() takes exactly one argument (0 given)

Well, yes, like it says; len needs to know what to get the length of. I don't understand what you want this sum call to do.

nor am i able to find any documentation that mentions about giving functions as the start parameters.

collections.Counter isn't a function; it's a class. However, len(x) isn't a function either; it's the result of calling that function. (Similarly, the result of calling the collections.Counter class is a collections.Counter instance.) Anyway, it doesn't matter where the start parameter comes from; what matters is the value it has. For example:

a=[2,3,3,4,5,5,6]
sum(a,len(a))

a has 7 items in it, so len(a) is equal to 7, and the result is the same as writing sum(a, 7) directly. That is 7 + 2 + 3 + 3 + 4 + 5 + 5 + 6 = 35.


问:
Accurate method to add months in PHP 5.1?
Yesterday I ran into an issue with PHP's strtotime not properly adding a month.  On '2011-05-31' I ran:

```<code>date('Y-m-d',strtotime( '+1 month', strtotime('now')));
</code>```

Which returns '2011-07-01' when I am expecting '2011-06-30'.

MySQL doesn't have any issue doing this.

I'd rather not reinvent the wheel with this, as it is fairly easy to make mistakes with date calculations from my experience.

Does anyone have a reliable and tested solution for this for PHP 5.1?

答: Adding +2592000 seconds (60 × 60 × 24 × 30) works the desired way for me.

Body:
Yesterday I ran into an issue with PHP's strtotime not properly adding a month.  On '2011-05-31' I ran:

date('Y-m-d',strtotime( '+1 month', strtotime('now')));

Which returns '2011-07-01' when I am expecting '2011-06-30'.

MySQL doesn't have any issue doing this.

I'd rather not reinvent the wheel with this, as it is fairly easy to make mistakes with date calculations from my experience.

Does anyone have a reliable and tested solution for this for PHP 5.1?


问:
Facebook login using firebaseui doesn't work errorCode: 100, subErrorCode: 33, errorType: GraphMethodException
I've followed the Authenticate using Facebook Login guide.
When I reached "Authenticate with Firebase" it says I should follow the Facebook developer's documentation.
As soon as I added the facebook_app_id in the Androidmanifest, which is in 4. Edit Your Resources and Manifest, step 4:

```<code><meta-data android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/facebook_app_id"/>
</code>```

I got an error:

```<code>Manifest merger failed : Attribute meta-data#com.facebook.sdk.ApplicationId@value value=(@string/facebook_app_id) from AndroidManifest.xml:52:13-52
    is also present at [com.firebaseui:firebase-ui-auth:4.3.1] AndroidManifest.xml:21:13-60 value=(@string/facebook_application_id).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:50:9-52:55 to override.
</code>```

It seems strange to add the key anyway, because I use Firebase so that I have an automatic drop-in UI, I'm expecting Firebase to handle this for me. The firebase documentation also says "If you integrated Facebook Login using a LoginButton" why would I want this? The whole reason you implement the firebase UI is so that you don't have to add a button etc.

When I remove facebook_app_id, then I get below error:

```<code>E/GraphResponse: {HttpStatus: 400, errorCode: 100, subErrorCode: 33, errorType: GraphMethodException, errorMessage: Unsupported get request. Object with ID '1234567890' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api}
</code>```

This seems to be the problem. This is the method:

```<code>override suspend fun makeSignInIntent(): Intent {
    return withContext(ioDispatcher) {
        // Choose authentication providers
        val providers = arrayListOf(
            AuthUI.IdpConfig.EmailBuilder().build(),
            AuthUI.IdpConfig.GoogleBuilder().build()
//                AuthUI.IdpConfig.FacebookBuilder().build()
        )
        // Create and launch sign-in intent
        AuthUI.getInstance()
            .createSignInIntentBuilder()
            .setAvailableProviders(providers)
            .build()
    }
}
</code>```

Please note that I excluded AuthUI.IdpConfig.FacebookBuilder().build() and still get the error.

Here is my build.gradle:

```<code>implementation 'com.firebaseui:firebase-ui-auth:6.2.0'
implementation 'com.firebaseui:firebase-ui-database:6.2.0'
implementation "com.google.firebase:firebase-auth:19.2.0"
implementation "com.google.firebase:firebase-database:19.2.0"
implementation 'com.facebook.android:facebook-android-sdk:5.13.0'
implementation 'com.facebook.android:facebook-login:5.13.0'
</code>```

My strings.xml:

```<code><!-- Facebook application ID and custom URL scheme (app ID prefixed by 'fb'). -->
<string name="facebook_application_id" translatable="false">MY_KEY</string>
<!-- Facebook Application ID, prefixed by 'fb'. Enables Chrome Custom tabs. -->
<string name="facebook_login_protocol_scheme" translatable="false">fbMY_KEY</string>
</code>```

I've enabled Facebook login and added the necessary keys:

I also added the redirect URI and the Development Key Hash:

UPDATE: Also tried this documentation, but is the same.

答:
I had the same issue. I resolved it by adding </p>

```<code><string name="facebook_application_id">MY_KEY</string>
<string name="facebook_app_id">MY_KEY</string>
<string name="fb_login_protocol_scheme">fbMY_KEY</string>
</code>```

<p>To the strings.xml file and I changed the meta-data to include a tools:replace: </p>

```<code><meta-data android:name="com.facebook.sdk.ApplicationId"
    tools:replace="android:value"
    android:value="@string/facebook_app_id"/>
</code>```

Body:
I've followed the Authenticate using Facebook Login guide.
When I reached "Authenticate with Firebase" it says I should follow the Facebook developer's documentation.
As soon as I added the facebook_app_id in the Androidmanifest, which is in 4. Edit Your Resources and Manifest, step 4:

<meta-data android:name="com.facebook.sdk.ApplicationId"
        android:value="@string/facebook_app_id"/>

I got an error:

Manifest merger failed : Attribute meta-data#com.facebook.sdk.ApplicationId@value value=(@string/facebook_app_id) from AndroidManifest.xml:52:13-52
    is also present at [com.firebaseui:firebase-ui-auth:4.3.1] AndroidManifest.xml:21:13-60 value=(@string/facebook_application_id).
    Suggestion: add 'tools:replace="android:value"' to <meta-data> element at AndroidManifest.xml:50:9-52:55 to override.

It seems strange to add the key anyway, because I use Firebase so that I have an automatic drop-in UI, I'm expecting Firebase to handle this for me. The firebase documentation also says "If you integrated Facebook Login using a LoginButton" why would I want this? The whole reason you implement the firebase UI is so that you don't have to add a button etc.

When I remove facebook_app_id, then I get below error:

E/GraphResponse: {HttpStatus: 400, errorCode: 100, subErrorCode: 33, errorType: GraphMethodException, errorMessage: Unsupported get request. Object with ID '1234567890' does not exist, cannot be loaded due to missing permissions, or does not support this operation. Please read the Graph API documentation at https://developers.facebook.com/docs/graph-api}

This seems to be the problem. This is the method:

override suspend fun makeSignInIntent(): Intent {
    return withContext(ioDispatcher) {
        // Choose authentication providers
        val providers = arrayListOf(
            AuthUI.IdpConfig.EmailBuilder().build(),
            AuthUI.IdpConfig.GoogleBuilder().build()
//                AuthUI.IdpConfig.FacebookBuilder().build()
        )
        // Create and launch sign-in intent
        AuthUI.getInstance()
            .createSignInIntentBuilder()
            .setAvailableProviders(providers)
            .build()
    }
}

Please note that I excluded AuthUI.IdpConfig.FacebookBuilder().build() and still get the error.

Here is my build.gradle:

implementation 'com.firebaseui:firebase-ui-auth:6.2.0'
implementation 'com.firebaseui:firebase-ui-database:6.2.0'
implementation "com.google.firebase:firebase-auth:19.2.0"
implementation "com.google.firebase:firebase-database:19.2.0"
implementation 'com.facebook.android:facebook-android-sdk:5.13.0'
implementation 'com.facebook.android:facebook-login:5.13.0'

My strings.xml:

<string name="facebook_application_id" translatable="false">MY_KEY</string>

<string name="facebook_login_protocol_scheme" translatable="false">fbMY_KEY</string>

I've enabled Facebook login and added the necessary keys:

I also added the redirect URI and the Development Key Hash:

UPDATE: Also tried this documentation, but is the same.

Body:
I had the same issue. I resolved it by adding

<string name="facebook_application_id">MY_KEY</string>
<string name="facebook_app_id">MY_KEY</string>
<string name="fb_login_protocol_scheme">fbMY_KEY</string>

To the strings.xml file and I changed the meta-data to include a tools:replace:

<meta-data android:name="com.facebook.sdk.ApplicationId"
    tools:replace="android:value"
    android:value="@string/facebook_app_id"/>


问:
Drawing a book's cover with folds (Ada)
Im working on an assignment that's similar to the flag package problem already solved on this site ( Package bodies and main programs. Simple assignment (Ada) )

This time however I need to draw a book cover with 4 folds on it as shown below:

```<code>Book with folds at the breaking points: 3, 10, 15, 17.
Height = 2, Width = 20,
Title (string(1..100),
Author (string(1..50).

<Title>
<Author>
|--|------|----|-|---|
|  |      |    | |   |
|  |      |    | |   |
|--|------|----|-|---|
</code>```

I get a host of problems emanating from line 25 in exercise_bluebook_main.adb, but the central one that bugs me the most is

exercise_bluebook_main.adb:25:11: expected type "Standard.Integer" exercise_bluebook_main.adb:25:11: found type "Breaking_Array" defined
  at exercise_bluebook.ads:7

Why does it expect a standard integer when Im out for the array as defined? Furthermore I think in the declare part of the main procedure line 15 Im in for trouble as the :=get_line is already taken by "Title". How would you solve that, anyone?

Maybe there are more faults in the code than that, Im thankful for any and all input as long as its constructive!

my .ads file

```<code>with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;

package Exercise_BlueBook is

   subtype Break_Points is integer range 1..20;
   type Breaking_Array is array (1..4) of Break_Points;
   type Book_Type is private;

   procedure Get (Item: out Book_Type;
          Title: in String;
          Author: in String;
          Width: in Integer;
          Height: in Integer;
          Break_Points: in Breaking_Array);

   procedure Put (Item: in Book_Type);

private

   type Book_Type is
      record

     Title : String(1..100);
     Title_L : Integer;
     Author : String(1..50);
     Author_L : Integer;
     Width : Integer;
     Height : Integer;
     Break_Points : Integer;

      end record;

end Exercise_BlueBook;
</code>```

my package body adb file

```<code>with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;

with Exercise_Bluebook; use Exercise_Bluebook;

package body Exercise_BlueBook is

  procedure Get (Item: out Book_Type;
         Title: in String;
         Author: in String;
         Width: in Integer;
         Height: in Integer;
         Break_Points: in Breaking_Array) is

  begin

     Item.Title_L := Integer'Min (Item.Title'Length, Title'Length);
     Item.Title (1..Item.Title_L) := Title(Title'First .. Item.Title_L);
     Item.Author_L := Integer'Min (Item.Author'Length, Author'Length);
     Item.Author (1..Item.Author_L) := Author (Author'First .. Item.Author_L);
     Item.Width := Width;
     Item.Height := Height;
     Item.Break_Points := Break_Points;

  end Get;

  procedure Put (Item: in Book_Type) is

  begin

     Put_Line(Item.Title(1..Item.Title_L));
     Put_Line(Item.Author(1..Item.Author_L));

     for H in 1..Item.Height loop
    Put("!");

    for I in 1..Item.Width loop
       Put("-");
       if I = Breaking_Array(1) then
          Put("!");
       elsif I = Breaking_Array(2) then
          Put("!");
       elsif I = Breaking_Array(3) then
          Put("!");
       elsif I = Breaking_Array(4) then
          Put("!");
       end if;
    end loop;
    Put_Line("!");
     end loop;

     end Put;

end Exercise_BlueBook;
</code>```

my main procedure

```<code>with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;

with Exercise_Bluebook; use Exercise_Bluebook;

procedure Exercise_BlueBook_Main is

   B : Book_Type;

begin

   Put("Enter the name of the book: ");
   declare
      Title : constant String := Get_Line; -- First Get_Line already taken
      Author: constant String := Get_Line; -- How do I solve this for "Author"?
      Width: Integer;
      Height: Integer;
      Break_Points : Exercise_BlueBook.Breaking_Array;
   begin
      Put("Enter the book's width: ");
      Get(Width);
      Put("Enter the book's height: ");
      Get(Height);
      Put("Enter the breaking points for the fold: ");
      Get(Break_Points); -- Won't read this as an array?

      Get(B,
      Title => Title,
      Author => Author,
      Width => Width,
      Height => Height,
      Break_Points => Break_Points);
   end;

   New_Line;
   Put(B);

end Exercise_BlueBook_Main;
</code>```

答:
As it stands, the main program prompts for the title, then calls Get_Line for the Title, then another Get_Line for the Author. The following data is read using Gets; the way that works is that characters are read, skipping white space until something that could be a part of a number is found, then more characters are read until something that couldn’t be part of a number is found.

The reason we’ve been suggesting the form

```<code>   declare
      Title : constant String := Get_Line;
</code>```

is that a String is a fixed-length array of characters; how can you know ahead of time how long to make it? and the way this works is that the actual length required is determined at run time by the length of the initialization value returned by Get_Line.

You could fix the lack of a prompt for the author by changing the prompt: "Enter the book’s name and the author’s name, hit RET after each:".

Or you could nest them:

```<code>   Put("Enter the name of the book: ");
   declare
      Title : constant String := Get_Line;
   begin
      Put("Enter the author's name: ");
      declare
         Author: constant String := Get_Line;
         Width: Integer;
         Height: Integer;
         Break_Points : Exercise_BlueBook.Breaking_Array;
      begin
         Put("Enter the book's width: ");
         Get(Width);
         Put("Enter the book's height: ");
         Get(Height);
         Put("Enter the breaking points for the fold: ");
</code>```

And now we come to read the Break_Points. You need to read each element with its own Get:

```<code>         for J in Break_Points'Range loop
            Get(Break_Points(J));
         end loop;
         Get(B,
             Title => Title,
             Author => Author,
             Width => Width,
             Height => Height,
             Break_Points => Break_Points);
      end;
   end;
</code>```

Title: Drawing a book's cover with folds (Ada)

Body:
Im working on an assignment that's similar to the flag package problem already solved on this site ( Package bodies and main programs. Simple assignment (Ada) )

This time however I need to draw a book cover with 4 folds on it as shown below:

Book with folds at the breaking points: 3, 10, 15, 17.
Height = 2, Width = 20,
Title (string(1..100),
Author (string(1..50).

<Title>
<Author>
|--|------|----|-|---|
|  |      |    | |   |
|  |      |    | |   |
|--|------|----|-|---|

I get a host of problems emanating from line 25 in exercise_bluebook_main.adb, but the central one that bugs me the most is

exercise_bluebook_main.adb:25:11: expected type "Standard.Integer" exercise_bluebook_main.adb:25:11: found type "Breaking_Array" defined
  at exercise_bluebook.ads:7

Why does it expect a standard integer when Im out for the array as defined? Furthermore I think in the declare part of the main procedure line 15 Im in for trouble as the :=get_line is already taken by "Title". How would you solve that, anyone?

Maybe there are more faults in the code than that, Im thankful for any and all input as long as its constructive!

my .ads file

with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;

package Exercise_BlueBook is

   subtype Break_Points is integer range 1..20;
   type Breaking_Array is array (1..4) of Break_Points;
   type Book_Type is private;

   procedure Get (Item: out Book_Type;
          Title: in String;
          Author: in String;
          Width: in Integer;
          Height: in Integer;
          Break_Points: in Breaking_Array);

   procedure Put (Item: in Book_Type);

private

   type Book_Type is
      record

     Title : String(1..100);
     Title_L : Integer;
     Author : String(1..50);
     Author_L : Integer;
     Width : Integer;
     Height : Integer;
     Break_Points : Integer;

      end record;

end Exercise_BlueBook;

my package body adb file

with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;

with Exercise_Bluebook; use Exercise_Bluebook;

package body Exercise_BlueBook is

  procedure Get (Item: out Book_Type;
         Title: in String;
         Author: in String;
         Width: in Integer;
         Height: in Integer;
         Break_Points: in Breaking_Array) is

  begin

     Item.Title_L := Integer'Min (Item.Title'Length, Title'Length);
     Item.Title (1..Item.Title_L) := Title(Title'First .. Item.Title_L);
     Item.Author_L := Integer'Min (Item.Author'Length, Author'Length);
     Item.Author (1..Item.Author_L) := Author (Author'First .. Item.Author_L);
     Item.Width := Width;
     Item.Height := Height;
     Item.Break_Points := Break_Points;

  end Get;

  procedure Put (Item: in Book_Type) is

  begin

     Put_Line(Item.Title(1..Item.Title_L));
     Put_Line(Item.Author(1..Item.Author_L));

     for H in 1..Item.Height loop
    Put("!");

    for I in 1..Item.Width loop
       Put("-");
       if I = Breaking_Array(1) then
          Put("!");
       elsif I = Breaking_Array(2) then
          Put("!");
       elsif I = Breaking_Array(3) then
          Put("!");
       elsif I = Breaking_Array(4) then
          Put("!");
       end if;
    end loop;
    Put_Line("!");
     end loop;

     end Put;

end Exercise_BlueBook;

my main procedure

with ada.text_IO; use ada.text_IO;
with ada.integer_text_IO; use ada.integer_text_IO;

with Exercise_Bluebook; use Exercise_Bluebook;

procedure Exercise_BlueBook_Main is

   B : Book_Type;

begin

   Put("Enter the name of the book: ");
   declare
      Title : constant String := Get_Line; -- First Get_Line already taken
      Author: constant String := Get_Line; -- How do I solve this for "Author"?
      Width: Integer;
      Height: Integer;
      Break_Points : Exercise_BlueBook.Breaking_Array;
   begin
      Put("Enter the book's width: ");
      Get(Width);
      Put("Enter the book's height: ");
      Get(Height);
      Put("Enter the breaking points for the fold: ");
      Get(Break_Points); -- Won't read this as an array?

      Get(B,
      Title => Title,
      Author => Author,
      Width => Width,
      Height => Height,
      Break_Points => Break_Points);
   end;

   New_Line;
   Put(B);

end Exercise_BlueBook_Main;

Body:
As it stands, the main program prompts for the title, then calls Get_Line for the Title, then another Get_Line for the Author. The following data is read using Gets; the way that works is that characters are read, skipping white space until something that could be a part of a number is found, then more characters are read until something that couldn’t be part of a number is found.

The reason we’ve been suggesting the form

   declare
      Title : constant String := Get_Line;

is that a String is a fixed-length array of characters; how can you know ahead of time how long to make it? and the way this works is that the actual length required is determined at run time by the length of the initialization value returned by Get_Line.

You could fix the lack of a prompt for the author by changing the prompt: "Enter the book’s name and the author’s name, hit RET after each:".

Or you could nest them:

   Put("Enter the name of the book: ");
   declare
      Title : constant String := Get_Line;
   begin
      Put("Enter the author's name: ");
      declare
         Author: constant String := Get_Line;
         Width: Integer;
         Height: Integer;
         Break_Points : Exercise_BlueBook.Breaking_Array;
      begin
         Put("Enter the book's width: ");
         Get(Width);
         Put("Enter the book's height: ");
         Get(Height);
         Put("Enter the breaking points for the fold: ");

And now we come to read the Break_Points. You need to read each element with its own Get:

         for J in Break_Points'Range loop
            Get(Break_Points(J));
         end loop;
         Get(B,
             Title => Title,
             Author => Author,
             Width => Width,
             Height => Height,
             Break_Points => Break_Points);
      end;
   end;


问:
static_assert type of a private class member, with no instance
I would like to statically assert whether a private class member type outside of the class:

```<code>class Human
{
    public:
        int getInt() const {return myInt;}
    private:
        int myInt{0};
};
</code>```

However, I don't have an instance of the object at the location i'd like to assert.

I tried:

static_assert(std::is_same<decltype(Human::getInt), int>::value);

but it requires an instance.

What's the best way to achieve this?

答:
There is std::declval which helps in such cases:

static_assert(std::is_same<decltype(std::declval<Human>().getInt()), int>::value);
```

Body:
I would like to statically assert whether a private class member type outside of the class:

class Human
{
    public:
        int getInt() const {return myInt;}
    private:
        int myInt{0};
};

However, I don't have an instance of the object at the location i'd like to assert.

I tried:

static_assert(std::is_same<decltype(Human::getInt), int>::value);

but it requires an instance.

What's the best way to achieve this?


问:
Logarithmic axis with modified ticks
I'm trying to re-create the below graph but am not able to get rid of the 'half-step' increments for x > 3. Is there a better way of doing this? I'm using ggplot2 for now - to get it right and then plan on switching to plotly for interactive plots.

Code

Only showing 3 traces for PoC:

```<code>set.seed(69)
library(data.table)
library(ggplot2)

k <- lapply(1:10, function(z){
  ret <- sample(x = (5*z):100,
                size = 20,
                replace = T)
  dat <- data.table(V1 =  ret[order(ret)] )
  colnames(dat) <- paste('trace', z, sep = '')
  return(dat)
  })

dat <- do.call(cbind, k)
dat$size <- c(seq(0.1, 1, 0.1), 2:11)

ggplot(dat[size >= 0.2, ], aes(x = size)) +
  geom_line(size = 1.5, aes(y = trace1), color = '#003366') +
  geom_line(size = 1.5, aes(y = trace2),
            color = rgb(red = 0, green = 103, blue = 62, maxColorValue = 255)) +
  geom_line(size = 1.5, aes(y = trace3), color = '#b20000') +
  scale_x_log10(breaks = c(seq(0.1, 1, 0.1), 2:11))
</code>```

Output

Desired Plot

答:
There is no need to start with ggplot2. You can do this directly in plotly:

library(dplyr)
library(tidyr)
library(plotly)

dat %>%
  filter(size >= 0.2) %>%
  pivot_longer(-size) %>%
 plot_ly(x = ~size, y = ~value, color = ~name, type = 'scatter', mode = 'lines') %>%
  layout(xaxis = list(type = "log",
                      tickvals = as.list(c(seq(0.2,1,0.2), seq(2,10,2)))))
```

Title: Logarithmic axis with modified ticks

Body:
I'm trying to re-create the below graph but am not able to get rid of the 'half-step' increments for x > 3. Is there a better way of doing this? I'm using ggplot2 for now - to get it right and then plan on switching to plotly for interactive plots.

Code

Only showing 3 traces for PoC:

set.seed(69)
library(data.table)
library(ggplot2)

k <- lapply(1:10, function(z){
  ret <- sample(x = (5*z):100,
                size = 20,
                replace = T)
  dat <- data.table(V1 =  ret[order(ret)] )
  colnames(dat) <- paste('trace', z, sep = '')
  return(dat)
  })

dat <- do.call(cbind, k)
dat$size <- c(seq(0.1, 1, 0.1), 2:11)

ggplot(dat[size >= 0.2, ], aes(x = size)) +
  geom_line(size = 1.5, aes(y = trace1), color = '#003366') +
  geom_line(size = 1.5, aes(y = trace2),
            color = rgb(red = 0, green = 103, blue = 62, maxColorValue = 255)) +
  geom_line(size = 1.5, aes(y = trace3), color = '#b20000') +
  scale_x_log10(breaks = c(seq(0.1, 1, 0.1), 2:11))

Output

Desired Plot


问:
Plot precedence while plotting adx and price oscillator in [pine- script]
Hi I am a newbie to pine editor, I am trying to plot Price oscillator and ADX in the same window with the same precedence, but whenever I plot them ADX is coming on the top but it should be in reverse order. Plots are not coming correctly (when plotted individually it shows correctly). Please find the code which I have used and let me know where it needs to be corrected?

```<code>//@version=4
    study(title="Price Oscillator", shorttitle="PPO", format=format.price, precision=2)
    shortlen=input(12, minval=1)
    longlen=input(26, minval=1)
    src = input(close, title="Source")
    short = ema(src, shortlen)
    long = ema(src, longlen)
    po = (short - long)/long*100
    adxlen = input(14, title="ADX Smoothing")
    dilen = input(14, title="DI Length")
    dirmov(len) =>
    up = change(high)
    down = -change(low)
    plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
    minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
    truerange = rma(tr, len)
    plus = fixnan(100 * rma(plusDM, len) / truerange)
    minus = fixnan(100 * rma(minusDM, len) / truerange)
    [plus, minus]
    adx(dilen, adxlen) =>
    [plus, minus] = dirmov(dilen)
    sum = plus + minus
    adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
    sig = adx(dilen, adxlen)
    plot(po, color=#990000, title="PPO")
    plot(sig, color=color.red, title="ADX")`
</code>```

I have attached the snapshot of the window as well for your referenceplotting PPO and ADX

答: That's because they don't have the same scale. It would be much easier and reliable to simply use each one separately and overlay them on in the same pane, on different scales.

Body:
Hi I am a newbie to pine editor, I am trying to plot Price oscillator and ADX in the same window with the same precedence, but whenever I plot them ADX is coming on the top but it should be in reverse order. Plots are not coming correctly (when plotted individually it shows correctly). Please find the code which I have used and let me know where it needs to be corrected?

//@version=4
    study(title="Price Oscillator", shorttitle="PPO", format=format.price, precision=2)
    shortlen=input(12, minval=1)
    longlen=input(26, minval=1)
    src = input(close, title="Source")
    short = ema(src, shortlen)
    long = ema(src, longlen)
    po = (short - long)/long*100
    adxlen = input(14, title="ADX Smoothing")
    dilen = input(14, title="DI Length")
    dirmov(len) =>
    up = change(high)
    down = -change(low)
    plusDM = na(up) ? na : (up > down and up > 0 ? up : 0)
    minusDM = na(down) ? na : (down > up and down > 0 ? down : 0)
    truerange = rma(tr, len)
    plus = fixnan(100 * rma(plusDM, len) / truerange)
    minus = fixnan(100 * rma(minusDM, len) / truerange)
    [plus, minus]
    adx(dilen, adxlen) =>
    [plus, minus] = dirmov(dilen)
    sum = plus + minus
    adx = 100 * rma(abs(plus - minus) / (sum == 0 ? 1 : sum), adxlen)
    sig = adx(dilen, adxlen)
    plot(po, color=#990000, title="PPO")
    plot(sig, color=color.red, title="ADX")`

I have attached the snapshot of the window as well for your referenceplotting PPO and ADX


问:
Java Regex validate String
There are lot of similar questions on the Regex, however I am still confused on the following case:

```<code>import java.util.regex.Pattern;

public class PatternTest {

  public static void main(String[] args) {
    String PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20})";
    Pattern pattern = Pattern.compile(PATTERN);

    boolean isTrue = pattern.matcher("nks#n1Kos2~([{&").matches();

    System.out.println(isTrue);
  }

}
</code>```

The characters of ~([{& is not in the PATTERN, however the matches shows up true. What is the reason for that?

Here is a link on Java Regular Expression Tester https://www.freeformatter.com/java-regex-tester.html#ad-output

答:
The (?=X) patterns are "zero-width positive lookahead" assertions. So they're asserting that the regexes are found in the search string without consuming any of it. All of these assertions are passing successfully.

The .{8,20} pattern is saying "match any character as long as there are between 8 and 20 of them (inclusive)". So it is matching the entire string.

Title: Java Regex validate String

Body:
There are lot of similar questions on the Regex, however I am still confused on the following case:

import java.util.regex.Pattern;

public class PatternTest {

  public static void main(String[] args) {
    String PATTERN = "((?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20})";
    Pattern pattern = Pattern.compile(PATTERN);

    boolean isTrue = pattern.matcher("nks#n1Kos2~([{&").matches();

    System.out.println(isTrue);
  }

}

The characters of ~([{& is not in the PATTERN, however the matches shows up true. What is the reason for that?

Here is a link on Java Regular Expression Tester https://www.freeformatter.com/java-regex-tester.html#ad-output


问:
Why I have an Error when importing scanpy._compat?
Hi I'm new here so sorry for my language which could result inaccurate.
I'm working with a conda environment in which I installed scanpy. However, when I import the module scanpy._compat, it returns an import error:

from scanpy._compat import Literal

ModuleNotFoundError: No module named 'scanpy._compat'

I tried to upgrade scanpy:
pip install --upgrade scanpy and I also created another conda environment following installation steps present on scanpy github (https://github.com/theislab/scanpy/blob/master/docs/installation.rst). In each of the last two cases everything works well except for the import of scanpy._compat module.

Someone knows if I'm doing something wrong here?

答:
In the _compat.py you will note that the following code is provided:

First:

try:
    from typing import Literal

```

<p>And for the exception:</p>

<pre class="lang-py prettyprint-override"><code>except ImportError:
    try:
        from typing_extensions import Literal
    except ImportError:

        class LiteralMeta(type):
            def __getitem__(cls, values):
                if not isinstance(values, tuple):
                    values = (values,)
                return type('Literal_', (Literal,), dict(__args__=values))

        class Literal(metaclass=LiteralMeta):
            pass
</code>```

Consequently, when you are trying to import Literal, you could just as well circumvent the question by simply importing typing and do typing.Literal (python version >3.8 ) for whatever the situation you wanted to apply the code for.

However, the question suggests that scanpy cant be imported at all. Ensure that after installing the environment that you also activate it:

$ conda info --envs to find out the names of the environments you have available
$ conda activate [relevant env name] to activate the relevant conda environment.

To then try the code again:

$ python to enter the pythoninterpreter

> from scanpy._compat import Literal to test whether the import works.

Body:
In the _compat.py you will note that the following code is provided:

First:

try:
    from typing import Literal

And for the exception:

except ImportError:
    try:
        from typing_extensions import Literal
    except ImportError:

        class LiteralMeta(type):
            def __getitem__(cls, values):
                if not isinstance(values, tuple):
                    values = (values,)
                return type('Literal_', (Literal,), dict(__args__=values))

        class Literal(metaclass=LiteralMeta):
            pass

Consequently, when you are trying to import Literal, you could just as well circumvent the question by simply importing typing and do typing.Literal (python version >3.8 ) for whatever the situation you wanted to apply the code for.

However, the question suggests that scanpy cant be imported at all. Ensure that after installing the environment that you also activate it:

$ conda info --envs to find out the names of the environments you have available
$ conda activate [relevant env name] to activate the relevant conda environment.

To then try the code again:

$ python to enter the pythoninterpreter

> from scanpy._compat import Literal to test whether the import works.


问:
"ImportError: No module named twilio.rest"
I have installed python 2.7.10 with PATH access and correctly installed twilio.  However, when I try to execute a code I get this error message

```<code>Traceback (most recent call last):
  File "C:\Users\tmslvo\Google Drive\Desktop\send text.py", line 1, in <module>
    from twilio.rest import TwilioRestClient
ImportError: No module named twilio.rest
</code>```

Now I read that a reason might be that python can't find the twilio package so I tried the

```<code>which -a python
which -a twilio
</code>```

commands (in my Windows command prompt) in which case I get

```<code>'which' is not recognized as an internal or external command,
operable program or batch file.
</code>```

Does anybody have an idea of what I'm doing wrong?

Thank you!

答:
I had this problem as well.

In my case, I had named my file twilio.py and that is what caused the error.

Renaming the file to send_sms.py ( or any other name of your choice) will resolve the issue!

Body:
I have installed python 2.7.10 with PATH access and correctly installed twilio.  However, when I try to execute a code I get this error message

Traceback (most recent call last):
  File "C:\Users\tmslvo\Google Drive\Desktop\send text.py", line 1, in <module>
    from twilio.rest import TwilioRestClient
ImportError: No module named twilio.rest

Now I read that a reason might be that python can't find the twilio package so I tried the

which -a python
which -a twilio

commands (in my Windows command prompt) in which case I get

'which' is not recognized as an internal or external command,
operable program or batch file.

Does anybody have an idea of what I'm doing wrong?

Thank you!


问:
Azure App Service Container Images force pulled from Docker Hub instead of ACR
Does Azure App Service only support images stored in Docker when defined using the Docker Compose Preview.

My images are stored in Azure Container Registry (ACR). Yet when I refer to my image stored in ACR using the Docker compose preview, it trys to pull the images from Docker Hub instead, registry-1.docker.io, where they are not stored and fails.

DockerApiException: Docker API responded with status code=InternalServerError, response={"message":"Get https://registry-1.docker.io/v2/dev/my_container/manifests/latest: unauthorized: incorrect username or password"}

```<code>version: '3.3'
services:
  container_one:
    image: "dev/container_one"
    ports:
      - "80:80"
    restart: always
  container_two:
    image: "dev/container_two"
    ports:
      - "81:81"
    restart: always
</code>```

答:
I needed to include the full link to my ACR. Based on Hong Ooi's comment.

Using my.azurecr.io/dev/container_one solved my issue. My full configuration now looks like:

version: '3.3'
services:
  container_one:
    image: "my.azurecr.io/dev/container_one"
    ports:
      - "80:80"
    restart: always
  container_two:
    image: "my.azurecr.io/dev/container_two"
    ports:
      - "81:81"
    restart: always
```

Body:
Does Azure App Service only support images stored in Docker when defined using the Docker Compose Preview.

My images are stored in Azure Container Registry (ACR). Yet when I refer to my image stored in ACR using the Docker compose preview, it trys to pull the images from Docker Hub instead, registry-1.docker.io, where they are not stored and fails.

DockerApiException: Docker API responded with status code=InternalServerError, response={"message":"Get https://registry-1.docker.io/v2/dev/my_container/manifests/latest: unauthorized: incorrect username or password"}

version: '3.3'
services:
  container_one:
    image: "dev/container_one"
    ports:
      - "80:80"
    restart: always
  container_two:
    image: "dev/container_two"
    ports:
      - "81:81"
    restart: always


问:
Microsoft ReportViewer Web Control Requiring a ScriptManager
I'm trying to render the report viewer programmatically within a custom Page placed in an IHttpHandler context

```<code>ReportViewer rv = new ReportViewer();
ReportDataSource rds = new ReportDataSource();
rds.Name = "Report";
rv.LocalReport.ReportPath = "Report.rdlc";

rds.Value = SomeReportObject;

rv.LocalReport.DataSources.Add(rds);
rv.LocalReport.Refresh();

ScriptManager scriptHandler = new ScriptManager();
MyPage p = new MyPage();
p.Controls.Add(scriptHandler);
p.Controls.Add(rv);

using (TextWriter myTextWriter = new StringWriter())
        {
            using (HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter))
            {
               p.RenderControl(myWriter);
            }
        }
</code>```

Although I have the ScriptManager added to the page but the runtime complains that the ReportViewer needs one, it throws the following exception at p.RenderControl(myWriter) line

The Report Viewer Web Control requires a System.Web.UI.ScriptManager on the web form.

And this is the MyPage Class

```<code>public class MyPage : Page
{

    public override void VerifyRenderingInServerForm(Control control)
    {
        //Empty Method
    }

    public override bool EnableEventValidation
    {
        get { return false; }
        set { /* Do nothing */}
    }
}
</code>```

Any help would be very appreciated. This is done on .NET 4 and I'm using ReportViewer 2010.

答:
The error looks like the Form Tag is missing while doing the Rendering. The ScriptManager requires a Form Tag with runat server to perform the Task.

I would suggest to you add all your controls to the Form property of the Page. In Sequence and ScriptManager should be the first control.

I hope this helps.

Body:
I'm trying to render the report viewer programmatically within a custom Page placed in an IHttpHandler context

ReportViewer rv = new ReportViewer();
ReportDataSource rds = new ReportDataSource();
rds.Name = "Report";
rv.LocalReport.ReportPath = "Report.rdlc";

rds.Value = SomeReportObject;

rv.LocalReport.DataSources.Add(rds);
rv.LocalReport.Refresh();

ScriptManager scriptHandler = new ScriptManager();
MyPage p = new MyPage();
p.Controls.Add(scriptHandler);
p.Controls.Add(rv);

using (TextWriter myTextWriter = new StringWriter())
        {
            using (HtmlTextWriter myWriter = new HtmlTextWriter(myTextWriter))
            {
               p.RenderControl(myWriter);
            }
        }

Although I have the ScriptManager added to the page but the runtime complains that the ReportViewer needs one, it throws the following exception at p.RenderControl(myWriter) line

The Report Viewer Web Control requires a System.Web.UI.ScriptManager on the web form.

And this is the MyPage Class

public class MyPage : Page
{

    public override void VerifyRenderingInServerForm(Control control)
    {
        //Empty Method
    }

    public override bool EnableEventValidation
    {
        get { return false; }
        set { /* Do nothing */}
    }
}

Any help would be very appreciated. This is done on .NET 4 and I'm using ReportViewer 2010.


问:
Why is the width of the table row (tr) of a table element not working, but the height is?
Here's my code:

.table1 {
  background-color: gray;
  display: flex;
  justify-content: ;
  align-items: ;
  height: 400px;
  margin-left: 40px;
  padding-left: ;
}

.table1 tr {
  background-color: blue;
  height: 50px;
  width: 50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table1">

  <tr>
    <th>First Name</th>
    <th>Last Name</th>
    <th>Age</th>
  </tr>

  <tr>
    <td>Jill</td>
    <td>Smith</td>
    <td>50</td>
  </tr>

  <tr>
    <td>Eve</td>
    <td>Jackson</td>
    <td>94</td>
  </tr>

</table></code>```

Why is it that i can change the height of the "TR" but i can't change the width?

And yes, i know i can change the width using padding on the parent block, but why is it not working by just changing the width of the TR elements itself like it does for the height?

答:
As someone else mentioned, a tr is always 100% the width of the table itself, but the height attribute is adjustable. This is why the height attribute in your code works but the width attribute does not.

To adjust the width attributes of your columns all you have to do is target the th element. For example, if you add the following code to your CSS sheet then you'll see your widths change.

```<code>th {
  width:50px;
}
</code>```

Or, for more specificity, you can do the following.

```<code>.table1 tr th {
  width:50px;
}
</code>```

You can also have different widths for each column. For example, your First Name column can be 100px while your Last Name column could be 150px.
It may go  without saying, but the total combined width of all of your columns should not exceed the width of the table itself.

Body:
Here's my code:

.table1 {
  background-color: gray;
  display: flex;
  justify-content: ;
  align-items: ;
  height: 400px;
  margin-left: 40px;
  padding-left: ;
}

.table1 tr {
  background-color: blue;
  height: 50px;
  width: 50px;
}

    First Name
    Last Name
    Age

    Jill
    Smith
    50

    Eve
    Jackson
    94

Why is it that i can change the height of the "TR" but i can't change the width?

And yes, i know i can change the width using padding on the parent block, but why is it not working by just changing the width of the TR elements itself like it does for the height?

Body:
As someone else mentioned, a tr is always 100% the width of the table itself, but the height attribute is adjustable. This is why the height attribute in your code works but the width attribute does not.

To adjust the width attributes of your columns all you have to do is target the th element. For example, if you add the following code to your CSS sheet then you'll see your widths change.

th {
  width:50px;
}

Or, for more specificity, you can do the following.

.table1 tr th {
  width:50px;
}

You can also have different widths for each column. For example, your First Name column can be 100px while your Last Name column could be 150px.
It may go  without saying, but the total combined width of all of your columns should not exceed the width of the table itself.


问:
Android and iOS: show push notification only for selected criteria
Based on specific criteria, I want to show to the user Push Notification or not. For example, User is in a specific region. In this case I want only show to the user Push Notifications that are for its region. If a Push Notification is for an other region, the Push will not be shown.

Is this possible?

答:
Yes this is possible in different way,

you can notify your server by sending some parameter based on your criteria for not to send notification.

You can use unregisterForRemoteNotificationTypes to unregister for remote notification based on your circumstances, you have to register it again to get notifications back using registerForRemoteNotifications.

If you are using firebase then you can use

Messaging.messaging().subscribe(toTopic: "yourNotification")

Messaging.messaging().unsubscribe(fromTopic: "yourNotification")


问:
Painting issue in Qt custom frameless window between monitors
For one of my applications, I wanted to have a window customized under the Windows operating system (like Firefox, Avast, Microsoft Word, etc.). So I reimplemented some messages handling (QWidget::nativeEvent ()) from Win32 API, in order to preserve the functionality of AeroSnap, and others.

Although it works perfectly, when my custom window is transferred from one screen to another (I have two screens), a visual glitch appears (as you can see below). After the glitch appears, resizing the window, correct the bug. Moreover, after some debugging, I noticed that the Qt QWidget::geometry() is not the same as the geometry returned by Win32 API GetWindowRect() when the bug appears.

Both of my monitors are HD (1920x1080, so is not the difference of resolutions which cause the bug, but maybe the DPI difference ?). The glitch seems to appear when the window is moving between the two screens (when windows transfer the window to one screen to another ?).

Screenshot of the window without the glitch

Screenshot of the window with the glitch

The geometry reported initially by QWidget::geometry() is QRect(640,280 800x600), by QWidget::frameGeometry() is QRect(640,280 800x600), and by the Win32 GetWindowRect() is QRect(640,280 800x600). So, the same geometry. But, after the window is moved between the two monitors, the geometry reported by QWidget::geometry() becomes QGeometry(1541,322 784x561). The geometry reported by QWidget::frameGeometry() or GetWindowRect() is unchanged. Of course, after that, when the window is resized, the geometry is re correctly reported, and the painting issue dissapears. Conclusion, Qt seems to assume that a "appear" frame when the window is moved between two monitors.

The BaseFramelessWindow class implementation can be found here. This is a Qt QMainWindow subclass re-implementing some Win32 API native events (QWidget::nativeEvent()).

So someone would be how to avoid this bug? Is this a Qt bug? I have tried many things, and nothing has really worked. And I can't find any mention of this problem on the internet (maybe I'm looking badly?).

Minimal example code:

// main.cpp
#include "MainWindow.h"

#include <QtWidgets/qapplication.h>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}
```

<pre class="lang-cpp prettyprint-override"><code>// MainWindow.h
#pragma once

#include <QtWidgets/qmainwindow.h>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = Q_NULLPTR);

protected:
    void paintEvent(QPaintEvent* event) override;
    bool nativeEvent(const QByteArray& eventType, void* message, long* result) override;
};
</code>```

// MainWindow.cpp
#include "MainWindow.h"

#include <QtGui/qpainter.h>

#include <Windows.h>
#include <Windowsx.h>

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
{
    ::SetWindowLongPtr((HWND)winId(), GWL_STYLE, WS_POPUP | WS_THICKFRAME | WS_CAPTION | WS_SYSMENU | WS_MAXIMIZEBOX | WS_MINIMIZEBOX);
}

void MainWindow::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);

    // Using GetWindowRect() instead of rect() seems to be a valid
    // workaround for the painting issue. However many other things
    // do not work cause of the bad geometry reported by Qt.
    RECT winrect;
    GetWindowRect(reinterpret_cast<HWND>(winId()), &winrect);
    QRect rect = QRect(0, 0, winrect.right - winrect.left, winrect.bottom - winrect.top);

    // Background
    painter.fillRect(rect, Qt::red);

    // Border
    painter.setBrush(Qt::NoBrush);
    painter.setPen(QPen(Qt::blue, 1));
    painter.drawRect(rect.adjusted(0, 0, -1, -1));

    // Title bar
    painter.fillRect(QRect(1, 1, rect.width() - 2, 19), Qt::yellow);
}
bool MainWindow::nativeEvent(const QByteArray& eventType, void* message, long* result)
{
    MSG* msg = reinterpret_cast<MSG*>(message);

    switch (msg->message)
    {
    case WM_NCCALCSIZE:
        *result = 0;
        return true;
    case WM_NCHITTEST: {
        *result = 0;

        RECT winrect;
        GetWindowRect(reinterpret_cast<HWND>(winId()), &winrect);

        // Code allowing to resize the window with the mouse is omitted.

        long x = GET_X_LPARAM(msg->lParam);
        long y = GET_Y_LPARAM(msg->lParam);
        if (x > winrect.left&& x < winrect.right && y > winrect.top&& y < winrect.top + 20) {
            // To allow moving the window.
            *result = HTCAPTION;
            return true;
        }

        repaint();
        return false;
    }
    default:
        break;
    }

    return false;
}
```

答:
I had this exact error after and solved it by implementing Qt's moveEvent to detect screen changes and then call SetWindowPos to redraw the window in the same position.

An example would be:

```<code>class MainWindow : public QMainWindow
{
    // rest of the class

private:

    QScreen* current_screen = nullptr;

    void moveEvent(QMoveEvent* event)
    {
        if (current_screen == nullptr)
        {
            current_screen = screen();
        }
        else if (current_screen != screen())
        {
            current_screen = screen();

            SetWindowPos((HWND) winId(), NULL, 0, 0, 0, 0,
                         SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
                         SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE);
        }

    }
};
</code>```

I'm not sure if the current_screen == nullptr clause is strictly needed, but I had trouble with multiple windows/dialogs without it (sometimes they would become unresponsive). I also do not know which flags for SetWindowPos are necessary.

I also cannot say whether this method is good practice, and it may cause problems elsewhere. Hopefully someone else can comment on this.

Either way it worked for me in a simple situation. Hopefully it provides a solution, or at least a starting point to try and solve this.

Body:
For one of my applications, I wanted to have a window customized under the Windows operating system (like Firefox, Avast, Microsoft Word, etc.). So I reimplemented some messages handling (QWidget::nativeEvent ()) from Win32 API, in order to preserve the functionality of AeroSnap, and others.

Although it works perfectly, when my custom window is transferred from one screen to another (I have two screens), a visual glitch appears (as you can see below). After the glitch appears, resizing the window, correct the bug. Moreover, after some debugging, I noticed that the Qt QWidget::geometry() is not the same as the geometry returned by Win32 API GetWindowRect() when the bug appears.

Both of my monitors are HD (1920x1080, so is not the difference of resolutions which cause the bug, but maybe the DPI difference ?). The glitch seems to appear when the window is moving between the two screens (when windows transfer the window to one screen to another ?).

Screenshot of the window without the glitch

Screenshot of the window with the glitch

The geometry reported initially by QWidget::geometry() is QRect(640,280 800x600), by QWidget::frameGeometry() is QRect(640,280 800x600), and by the Win32 GetWindowRect() is QRect(640,280 800x600). So, the same geometry. But, after the window is moved between the two monitors, the geometry reported by QWidget::geometry() becomes QGeometry(1541,322 784x561). The geometry reported by QWidget::frameGeometry() or GetWindowRect() is unchanged. Of course, after that, when the window is resized, the geometry is re correctly reported, and the painting issue dissapears. Conclusion, Qt seems to assume that a "appear" frame when the window is moved between two monitors.

The BaseFramelessWindow class implementation can be found here. This is a Qt QMainWindow subclass re-implementing some Win32 API native events (QWidget::nativeEvent()).

So someone would be how to avoid this bug? Is this a Qt bug? I have tried many things, and nothing has really worked. And I can't find any mention of this problem on the internet (maybe I'm looking badly?).

Minimal example code:

// main.cpp
#include "MainWindow.h"

#include <QtWidgets/qapplication.h>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

// MainWindow.h
#pragma once

#include <QtWidgets/qmainwindow.h>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = Q_NULLPTR);

protected:
    void paintEvent(QPaintEvent* event) override;
    bool nativeEvent(const QByteArray& eventType, void* message, long* result) override;
};

// MainWindow.cpp
#include "MainWindow.h"

#include <QtGui/qpainter.h>

#include <Windows.h>
#include <Windowsx.h>

MainWindow::MainWindow(QWidget* parent)
    : QMainWindow(parent)
{
    ::SetWindowLongPtr((HWND)winId(), GWL_STYLE, WS_POPUP | WS_THICKFRAME | WS_CAPTION | WS_SYSMENU | WS_MAXIMIZEBOX | WS_MINIMIZEBOX);
}

void MainWindow::paintEvent(QPaintEvent* event)
{
    QPainter painter(this);

    // Using GetWindowRect() instead of rect() seems to be a valid
    // workaround for the painting issue. However many other things
    // do not work cause of the bad geometry reported by Qt.
    RECT winrect;
    GetWindowRect(reinterpret_cast<HWND>(winId()), &winrect);
    QRect rect = QRect(0, 0, winrect.right - winrect.left, winrect.bottom - winrect.top);

    // Background
    painter.fillRect(rect, Qt::red);

    // Border
    painter.setBrush(Qt::NoBrush);
    painter.setPen(QPen(Qt::blue, 1));
    painter.drawRect(rect.adjusted(0, 0, -1, -1));

    // Title bar
    painter.fillRect(QRect(1, 1, rect.width() - 2, 19), Qt::yellow);
}
bool MainWindow::nativeEvent(const QByteArray& eventType, void* message, long* result)
{
    MSG* msg = reinterpret_cast<MSG*>(message);

    switch (msg->message)
    {
    case WM_NCCALCSIZE:
        *result = 0;
        return true;
    case WM_NCHITTEST: {
        *result = 0;

        RECT winrect;
        GetWindowRect(reinterpret_cast<HWND>(winId()), &winrect);

        // Code allowing to resize the window with the mouse is omitted.

        long x = GET_X_LPARAM(msg->lParam);
        long y = GET_Y_LPARAM(msg->lParam);
        if (x > winrect.left&& x < winrect.right && y > winrect.top&& y < winrect.top + 20) {
            // To allow moving the window.
            *result = HTCAPTION;
            return true;
        }

        repaint();
        return false;
    }
    default:
        break;
    }

    return false;
}

Body:
I had this exact error after and solved it by implementing Qt's moveEvent to detect screen changes and then call SetWindowPos to redraw the window in the same position.

An example would be:

class MainWindow : public QMainWindow
{
    // rest of the class

private:

    QScreen* current_screen = nullptr;

    void moveEvent(QMoveEvent* event)
    {
        if (current_screen == nullptr)
        {
            current_screen = screen();
        }
        else if (current_screen != screen())
        {
            current_screen = screen();

            SetWindowPos((HWND) winId(), NULL, 0, 0, 0, 0,
                         SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER |
                         SWP_NOOWNERZORDER | SWP_FRAMECHANGED | SWP_NOACTIVATE);
        }

    }
};

I'm not sure if the current_screen == nullptr clause is strictly needed, but I had trouble with multiple windows/dialogs without it (sometimes they would become unresponsive). I also do not know which flags for SetWindowPos are necessary.

I also cannot say whether this method is good practice, and it may cause problems elsewhere. Hopefully someone else can comment on this.

Either way it worked for me in a simple situation. Hopefully it provides a solution, or at least a starting point to try and solve this.


问:
How to set Spark log4j path in standalone mode on windows?
I've tried changing log4j.properties.template to log4j.properties inside hadoop-home/conf but spark still does not pick it up. I've tried setting

sparkconf.set("log4j.configuration", ".\\config\\log4j.properties");

but that doesn't work either. I also tried adding

```<code>-Dlog4j.configuration=.\config\log4j.properties
</code>```

to eclipse run configuration but doesn't work. Spark is still using its default during startup

```<code>Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
</code>```

I also set SPARK_CONF_DIR to my environmental variable to point to the spark/conf dir but that doesn't seem to work neither.

I am running this in windows standalone mode in eclipse

```<code>SparkConf sparkConf = new SparkConf().setAppName("Test").setMaster("local[1]")
                .set("log4j.configuration", ".\\config\\log4j.properties");
</code>```

答:
I had the problem from scala code (no problem with spark-shell for which log4j.properties was working properly).
For lack of time and given that I was only doing little experimentation locally to my laptop and did not want to change many little didactic programs I went for a very dirty and quick hack: modified the file log4j-defaults.properties inside the jar kindly indicated by the first diagnostic message:

```<code>Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties
</code>```

Obviously I feel guilty, hope my children will never know about this :-), but it was quick and easy (and was only working locally on non-production code)

Body:
I've tried changing log4j.properties.template to log4j.properties inside hadoop-home/conf but spark still does not pick it up. I've tried setting

sparkconf.set("log4j.configuration", ".\\config\\log4j.properties");

but that doesn't work either. I also tried adding

-Dlog4j.configuration=.\config\log4j.properties

to eclipse run configuration but doesn't work. Spark is still using its default during startup

Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties

I also set SPARK_CONF_DIR to my environmental variable to point to the spark/conf dir but that doesn't seem to work neither.

I am running this in windows standalone mode in eclipse

SparkConf sparkConf = new SparkConf().setAppName("Test").setMaster("local[1]")
                .set("log4j.configuration", ".\\config\\log4j.properties");

Body:
I had the problem from scala code (no problem with spark-shell for which log4j.properties was working properly).
For lack of time and given that I was only doing little experimentation locally to my laptop and did not want to change many little didactic programs I went for a very dirty and quick hack: modified the file log4j-defaults.properties inside the jar kindly indicated by the first diagnostic message:

Using Spark's default log4j profile: org/apache/spark/log4j-defaults.properties

Obviously I feel guilty, hope my children will never know about this :-), but it was quick and easy (and was only working locally on non-production code)


问:
What path to install Python 3.6 to on Windows?
The 3.6 installer suggests C:\Users\MyUserName\AppData\Local\Programs\Python\Python36-32 which is unlike any other software on Windows.
I remember that earlier versions installed to C:\PythonXY which is also unusual on Windows. Is any of that really a good idea?

In particular, I don't see why I would want to install this only for my user account. The checkbox "Install launcher for all users (recommended)" is default checked which seems incompatible with installing into %APPDATA%.

What is a good path to install Python to?

I'm a complete Python amateur and I don't want to cause myself problems. I am fearful of adding a space to the path for example.

Clicking further through the installer it turns out there is a checkbox to install for all users. This immediately sets a Program Files (x86) based path to the checkbox.

答:
I think the best path to install python is in C:\Users\<Username>\PythonXX (especially if you are using PC with multiple users and also if you are using your organization PC.

If you install to C:\PythonXX or to C:\Program Files\PythonXX, you will always have permissions issue. As soon as you try to install some packages/libraries using 'pip install ', permissions will not allow to install the packages.

If you leave the installation to be continued in C:\Users\<Username>\AppData\Local\Programs\Python\PythonXX as suggested by python installer, which also doesn't have any permissions issue, but path is not so easy to remember.

Few more important points:

If you are using a personal laptop and you are the only user (you will be administrator as well), then installing python to C:\PythonXX is also a best option.

Always check the option, add python path to Path variable during installation, so that you can also use python from command prompt/powershell.

Always check the option, install pip, so that you can use pip to install/update packages/libraries.


答:
Your regex is:

```<code>String PATTERN = "(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20}";
</code>```

Which means match any character of 8 to 20 in length that fulfills all the conditions given in lookahead.

What you actually need is this:

```<code>String PATTERN = "(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%])[a-zA-Z\\d@#$%]{8,20}";
</code>```

[a-zA-Z\\d@#$%]{8,20} will match only allowed characters inside [...] 8 to 20 in length.

Title: Java Regex validate String

Body:
Your regex is:

String PATTERN = "(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%]).{8,20}";

Which means match any character of 8 to 20 in length that fulfills all the conditions given in lookahead.

What you actually need is this:

String PATTERN = "(?=.*\\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[@#$%])[a-zA-Z\\d@#$%]{8,20}";

[a-zA-Z\\d@#$%]{8,20} will match only allowed characters inside [...] 8 to 20 in length.


问:
Character is not valid in visual studio
The dollar character is underlined with red in my Visual Studio VB.NET project saying:

character is not valid

Why is this happening?

答:
If you are trying to upgrade an older ASP.NET application you may need to install the Microsoft.CodeDom.Providers.DotNetCompilerPlatform NuGet package.

You can find out by going to the Build menu in Visual Studio and if ASP.NET Compilation -> Enable latest C# and VB language features... is present then that's the reason.

You can click that and it will install the latest version of the package for you.

Title: Character is not valid in visual studio


问:
DNS port listener not receiving connections
My objective is to build a server socket listening on DNS port for connections, without responding anything, in order to collect some informations about IP addresses that are looking for DNS servers. The only thing I need to collect is the source IP. I wrote this code:

```<code>import socket

def create_socket():
    global host
    global port
    global s
    try:
        host = ''
        port = 53
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    except socket.error as msg:
        print('Socekt creation error:' + str(msg))

def bind_socket():
    try:
        print('Binding socket to port: ' + str(port) + ', Host: ' + str(host))
        s.bind((host, port))
    except socket.error as msg:
        print('Socket Binding error: ' + str(msg))

def socket_receive():
    while True:
        msg = s.recvfrom(1024)
        print('IP: ' + str(msg[1]) + ',   DATA: ' + msg[0].decode(encoding='cp1252', errors='ignore'))

def main():
    create_socket()
    bind_socket()
    socket_receive()

main()
</code>```

Unfortunately, I have to run this on a VirtualMachine using VirtualBox. I created a port forwarding rule for the port 53 on my router and I think I did it right, because the site "https://canyouseeme.org/" tells me that my ISP is not blocking the port. I created port forwarding rule on the VirtualMachine, so that all the traffic on the port 53 of the host will be redirected to the guest (where my program is). This is what I hope at least. I created a rule even in Windows Firewall allowing connections for the port 53. Finally, I used iptables to allow incoming traffic on the port 53 of my VirtualMachine. I still don't get anything. Probably I'm missing something, maybe I have to use dnslib in python in order to "attract" connections. Or I need to configure something more on Windows or on the router. Maybe I'm missing some important concepts.
Why I don't get any connections?

```<code>PS C:\WINDOWS\system32> ipconfig

Windows IP Configuration

Ethernet adapter Ethernet 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Ethernet adapter Ethernet 3:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::e0ce:c8f6:a594:f24d%17
   IPv4 Address. . . . . . . . . . . : 192.168.56.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :

Wireless LAN adapter Connessione alla rete locale (LAN)* 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Wireless LAN adapter Connessione alla rete locale (LAN)* 3:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Ethernet adapter Ethernet:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Wireless LAN adapter Wi-Fi:

   Connection-specific DNS Suffix  . : domain.name
   Link-local IPv6 Address . . . . . : fe80::d03d:c2c9:163e:3eb6%6
   IPv4 Address. . . . . . . . . . . : 192.168.1.11
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : fe80::b239:56ff:fea9:f35e%6
                                       192.168.1.1

Ethernet adapter Connessione di rete Bluetooth 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :
</code>```

```<code>PS C:\WINDOWS\system32> netstat -na|findstr 53
  TCP    0.0.0.0:53             0.0.0.0:0              LISTENING
  TCP    0.0.0.0:5353           0.0.0.0:0              LISTENING
  TCP    127.0.0.1:5354         0.0.0.0:0              LISTENING
  UDP    0.0.0.0:53             *:*
  UDP    0.0.0.0:5353           *:*
  UDP    0.0.0.0:5353           *:*
  UDP    0.0.0.0:5353           *:*
  UDP    0.0.0.0:5353           *:*
  UDP    0.0.0.0:5353           *:*
  UDP    0.0.0.0:5355           *:*
  UDP    192.168.1.11:5353      *:*
  UDP    192.168.56.1:5353      *:*
  UDP    [::]:5353              *:*
  UDP    [::]:5353              *:*
  UDP    [::]:5353              *:*
  UDP    [::]:5355              *:*
  UDP    [::1]:5353             *:*
</code>```

UFW on the guest:

```<code>diego@diego-VirtualBox:~$ sudo ufw status
[sudo] password di diego:
Stato: attivo

A                          Azione      Da
-                          ------      --
53                         ALLOW       Anywhere
19                         ALLOW       Anywhere
5353                       ALLOW       Anywhere
123                        ALLOW       Anywhere
53 (v6)                    ALLOW       Anywhere (v6)
19 (v6)                    ALLOW       Anywhere (v6)
5353 (v6)                  ALLOW       Anywhere (v6)
123 (v6)                   ALLOW       Anywhere (v6)
</code>```

ifconfig on the guest

```<code>diego@diego-VirtualBox:~$ sudo ifconfig
enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.0.2.15  netmask 255.255.255.0  broadcast 10.0.2.255
        inet6 fe80::7059:da6f:6a4a:8f4e  prefixlen 64  scopeid 0x20<link>
        ether 08:00:27:34:d5:6d  txqueuelen 1000  (Ethernet)
        RX packets 395  bytes 307669 (307.6 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 278  bytes 33866 (33.8 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Loopback locale)
        RX packets 35  bytes 3215 (3.2 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 35  bytes 3215 (3.2 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0
</code>```

iptables on guest:

```<code>diego@diego-VirtualBox:~$ sudo iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination
ufw-before-logging-input  all  --  anywhere             anywhere
ufw-before-input  all  --  anywhere             anywhere
ufw-after-input  all  --  anywhere             anywhere
ufw-after-logging-input  all  --  anywhere             anywhere
ufw-reject-input  all  --  anywhere             anywhere
ufw-track-input  all  --  anywhere             anywhere
ACCEPT     udp  --  anywhere             anywhere             udp dpt:domain
</code>```

答:
The standard way to debug this is to use wireshark (https://www.wireshark.org/#download) or another packet sniffer .  You can install it on both your windows host and the guest instance.  Assuming your network is like this:

```<code>                                ---------------------------
------------      --------      |         |---------------|
|dns client| ---- |router| ---- |win host | guest instance|
------------      --------      ---------------------------
</code>```

Listen for tcp 53 packets on the windows host's lan adapter (192.168.1.11). If no packets show up there, you have a problem with port forwarding/firewall or win host firewall. Keep in mind your home router may be acting as a DNS server and swallowing the packets.

Listen for tcp 53 packets on the guest instance.  (enp0s3) If you see packets at the windows host level, but not the guest, you can try switching the adapter type used bridged instead of NAT or visa versa.

Also, it's best to debug with your DNS client inside the router first, to be sure it's actually making requests to your honeypot.  If you're using nslookup or other standard client, you'll need to make sure you've set your windows host as the domain controller.  e.g.

```<code>% nslookup
> server 192.168.1.1
Default server: 192.168.1.1
Address: 192.168.1.1#53
>
</code>```

If all that works, I guess people simply aren't probing your network or your ISP has smart intrusion prevention that doesn't stop canyouseme, but stops dns scans ala netcat.

Body:
My objective is to build a server socket listening on DNS port for connections, without responding anything, in order to collect some informations about IP addresses that are looking for DNS servers. The only thing I need to collect is the source IP. I wrote this code:

import socket

def create_socket():
    global host
    global port
    global s
    try:
        host = ''
        port = 53
        s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
    except socket.error as msg:
        print('Socekt creation error:' + str(msg))

def bind_socket():
    try:
        print('Binding socket to port: ' + str(port) + ', Host: ' + str(host))
        s.bind((host, port))
    except socket.error as msg:
        print('Socket Binding error: ' + str(msg))

def socket_receive():
    while True:
        msg = s.recvfrom(1024)
        print('IP: ' + str(msg[1]) + ',   DATA: ' + msg[0].decode(encoding='cp1252', errors='ignore'))

def main():
    create_socket()
    bind_socket()
    socket_receive()

main()

Unfortunately, I have to run this on a VirtualMachine using VirtualBox. I created a port forwarding rule for the port 53 on my router and I think I did it right, because the site "https://canyouseeme.org/" tells me that my ISP is not blocking the port. I created port forwarding rule on the VirtualMachine, so that all the traffic on the port 53 of the host will be redirected to the guest (where my program is). This is what I hope at least. I created a rule even in Windows Firewall allowing connections for the port 53. Finally, I used iptables to allow incoming traffic on the port 53 of my VirtualMachine. I still don't get anything. Probably I'm missing something, maybe I have to use dnslib in python in order to "attract" connections. Or I need to configure something more on Windows or on the router. Maybe I'm missing some important concepts.
Why I don't get any connections?

PS C:\WINDOWS\system32> ipconfig

Windows IP Configuration

Ethernet adapter Ethernet 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Ethernet adapter Ethernet 3:

   Connection-specific DNS Suffix  . :
   Link-local IPv6 Address . . . . . : fe80::e0ce:c8f6:a594:f24d%17
   IPv4 Address. . . . . . . . . . . : 192.168.56.1
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . :

Wireless LAN adapter Connessione alla rete locale (LAN)* 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Wireless LAN adapter Connessione alla rete locale (LAN)* 3:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Ethernet adapter Ethernet:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

Wireless LAN adapter Wi-Fi:

   Connection-specific DNS Suffix  . : domain.name
   Link-local IPv6 Address . . . . . : fe80::d03d:c2c9:163e:3eb6%6
   IPv4 Address. . . . . . . . . . . : 192.168.1.11
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : fe80::b239:56ff:fea9:f35e%6
                                       192.168.1.1

Ethernet adapter Connessione di rete Bluetooth 2:

   Media State . . . . . . . . . . . : Media disconnected
   Connection-specific DNS Suffix  . :

PS C:\WINDOWS\system32> netstat -na|findstr 53
  TCP    0.0.0.0:53             0.0.0.0:0              LISTENING
  TCP    0.0.0.0:5353           0.0.0.0:0              LISTENING
  TCP    127.0.0.1:5354         0.0.0.0:0              LISTENING
  UDP    0.0.0.0:53             *:*
  UDP    0.0.0.0:5353           *:*
  UDP    0.0.0.0:5353           *:*
  UDP    0.0.0.0:5353           *:*
  UDP    0.0.0.0:5353           *:*
  UDP    0.0.0.0:5353           *:*
  UDP    0.0.0.0:5355           *:*
  UDP    192.168.1.11:5353      *:*
  UDP    192.168.56.1:5353      *:*
  UDP    [::]:5353              *:*
  UDP    [::]:5353              *:*
  UDP    [::]:5353              *:*
  UDP    [::]:5355              *:*
  UDP    [::1]:5353             *:*

UFW on the guest:

diego@diego-VirtualBox:~$ sudo ufw status
[sudo] password di diego:
Stato: attivo

A                          Azione      Da
-                          ------      --
53                         ALLOW       Anywhere
19                         ALLOW       Anywhere
5353                       ALLOW       Anywhere
123                        ALLOW       Anywhere
53 (v6)                    ALLOW       Anywhere (v6)
19 (v6)                    ALLOW       Anywhere (v6)
5353 (v6)                  ALLOW       Anywhere (v6)
123 (v6)                   ALLOW       Anywhere (v6)

ifconfig on the guest

diego@diego-VirtualBox:~$ sudo ifconfig
enp0s3: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 10.0.2.15  netmask 255.255.255.0  broadcast 10.0.2.255
        inet6 fe80::7059:da6f:6a4a:8f4e  prefixlen 64  scopeid 0x20<link>
        ether 08:00:27:34:d5:6d  txqueuelen 1000  (Ethernet)
        RX packets 395  bytes 307669 (307.6 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 278  bytes 33866 (33.8 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        inet6 ::1  prefixlen 128  scopeid 0x10<host>
        loop  txqueuelen 1000  (Loopback locale)
        RX packets 35  bytes 3215 (3.2 KB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 35  bytes 3215 (3.2 KB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

iptables on guest:

diego@diego-VirtualBox:~$ sudo iptables -L
Chain INPUT (policy DROP)
target     prot opt source               destination
ufw-before-logging-input  all  --  anywhere             anywhere
ufw-before-input  all  --  anywhere             anywhere
ufw-after-input  all  --  anywhere             anywhere
ufw-after-logging-input  all  --  anywhere             anywhere
ufw-reject-input  all  --  anywhere             anywhere
ufw-track-input  all  --  anywhere             anywhere
ACCEPT     udp  --  anywhere             anywhere             udp dpt:domain

Body:
The standard way to debug this is to use wireshark (https://www.wireshark.org/#download) or another packet sniffer .  You can install it on both your windows host and the guest instance.  Assuming your network is like this:

                                ---------------------------
------------      --------      |         |---------------|
|dns client| ---- |router| ---- |win host | guest instance|
------------      --------      ---------------------------

Listen for tcp 53 packets on the windows host's lan adapter (192.168.1.11). If no packets show up there, you have a problem with port forwarding/firewall or win host firewall. Keep in mind your home router may be acting as a DNS server and swallowing the packets.

Listen for tcp 53 packets on the guest instance.  (enp0s3) If you see packets at the windows host level, but not the guest, you can try switching the adapter type used bridged instead of NAT or visa versa.

Also, it's best to debug with your DNS client inside the router first, to be sure it's actually making requests to your honeypot.  If you're using nslookup or other standard client, you'll need to make sure you've set your windows host as the domain controller.  e.g.

% nslookup
> server 192.168.1.1
Default server: 192.168.1.1
Address: 192.168.1.1#53
>

If all that works, I guess people simply aren't probing your network or your ISP has smart intrusion prevention that doesn't stop canyouseme, but stops dns scans ala netcat.


问:
Is there any way to prevent input type=“number” getting more than one dot values?
I want to get only decimal values like 1.5,0.56 etc. but  its allowing more than one dot.  is there any way to prevent it

答:
Originally shared here

You can find very detailed explainations in this Codepen

This solution is simple and will only allow one dot in the number field. It doesn't prevent from clicking back in the number and adding numbers before the ".". It doesn't prevent from executing browser keyboard shortcuts like refresh, copy and pasting (as long as the pasted value is a valid number) and others. It will allow to add "." withing the body of the number, but will remove any exceeding floats over the set limit.

The only behavior that I still can't prevent is if you press the dot key at the end of the input repeatedly, the dot will blink on and off. This happens because a typed value of "13." is a valid number and returns "13" and a typed value of "13.." is not and returns "". In my solution, if a value returns "" without the press of backspace or delete, it gets rolled back to the last valid value, wich is "13", obtained from the typed value "13.".

I've tried solutions where if a dot was pressed once, it was prevented to be triggered a second time, but every time I managed to get stuck with pressing the dot right after an already existing dot followed by nothing and then get stuck with not being able to type a dot unless I pressed any other key first.

I think the blinking on multiple press is the best solution for ther's no way a user would type a dot and nothing happens.

let lastValidInputValue;
let selectedDot = false;

const onKeypress = (e) => {
  if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
  selectedDot = false;

  if (e.key === "e") e.preventDefault();
};

const onInput = (e) => {
  if (
    e.target.value.indexOf(".") < e.target.value.length - e.target.getAttribute("data-toFixed") - 1 &&
    e.target.value.indexOf(".") !== -1
  ) {
    let newValue;
    newValue = e.target.value.slice(
      0,
      e.target.value.indexOf(".") +
        parseInt(e.target.getAttribute("data-toFixed")) +
        1
    );
    newValue = parseFloat(newValue);
    e.target.value = newValue;
  }
  if (e.target.value !== "") {
    lastValidInputValue = e.target.value;
  } else if (e.inputType.match(/delete/g)) {
    lastValidInputValue = "";
  } else {
    e.target.value = lastValidInputValue;
  }
};

 const onSelect = (e) => {
   if(window.getSelection().toString().indexOf(".") > -1) selectedDot = true;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" id="myNumber" name="myNumber" data-toFixed="2" step="any" onkeypress="onKeypress(event)" oninput="onInput(event)" onselect="onSelect(event)"></code>```

Body:
Originally shared here

You can find very detailed explainations in this Codepen

This solution is simple and will only allow one dot in the number field. It doesn't prevent from clicking back in the number and adding numbers before the ".". It doesn't prevent from executing browser keyboard shortcuts like refresh, copy and pasting (as long as the pasted value is a valid number) and others. It will allow to add "." withing the body of the number, but will remove any exceeding floats over the set limit.

The only behavior that I still can't prevent is if you press the dot key at the end of the input repeatedly, the dot will blink on and off. This happens because a typed value of "13." is a valid number and returns "13" and a typed value of "13.." is not and returns "". In my solution, if a value returns "" without the press of backspace or delete, it gets rolled back to the last valid value, wich is "13", obtained from the typed value "13.".

I've tried solutions where if a dot was pressed once, it was prevented to be triggered a second time, but every time I managed to get stuck with pressing the dot right after an already existing dot followed by nothing and then get stuck with not being able to type a dot unless I pressed any other key first.

I think the blinking on multiple press is the best solution for ther's no way a user would type a dot and nothing happens.

let lastValidInputValue;
let selectedDot = false;

const onKeypress = (e) => {
  if (e.key === "." && e.target.value.indexOf(".") !== -1 && !selectedDot) e.preventDefault();
  selectedDot = false;

  if (e.key === "e") e.preventDefault();
};

const onInput = (e) => {
  if (
    e.target.value.indexOf(".") < e.target.value.length - e.target.getAttribute("data-toFixed") - 1 &&
    e.target.value.indexOf(".") !== -1
  ) {
    let newValue;
    newValue = e.target.value.slice(
      0,
      e.target.value.indexOf(".") +
        parseInt(e.target.getAttribute("data-toFixed")) +
        1
    );
    newValue = parseFloat(newValue);
    e.target.value = newValue;
  }
  if (e.target.value !== "") {
    lastValidInputValue = e.target.value;
  } else if (e.inputType.match(/delete/g)) {
    lastValidInputValue = "";
  } else {
    e.target.value = lastValidInputValue;
  }
};

 const onSelect = (e) => {
   if(window.getSelection().toString().indexOf(".") > -1) selectedDot = true;
 }

<input type="number" id="myNumber" name="myNumber" data-toFixed="2" step="any" onkeypress="onKeypress(event)" oninput="onInput(event)" onselect="onSelect(event)">


问:
"Invalid field for upsert, must be an External Id custom or standard indexed field: Name" error
I am trying to enter unique values to the Contact object. Here is the code:

```<code>List<Contact> conList = new List<Contact> {
        new Contact(FirstName='Joe',LastName='Smith',Department='Finance'),
        new Contact(FirstName='Kathy',LastName='Smith',Department='Technology'),
        new Contact(FirstName='Caroline',LastName='Roth',Department='Finance'),
        new Contact()};

// Caroline Roth already exists so I want this code to update her record, not insert another Caroline Roth record
Database.UpsertResult[] srList = Database.upsert(conList, Contact.Fields.Name, false);
</code>```

Salesforce's documentation states
"The upsert statement matches the sObjects with existing records by comparing values of one field. If you don’t specify a field when calling this statement, the upsert statement uses the sObject’s ID to match the sObject with existing records in Salesforce. Alternatively, you can specify a field to use for matching. For custom objects, specify a custom field marked as external ID. For standard objects, you can specify any field that has the idLookup property set to true. For example, the Email field of Contact or User has the idLookup property set."

I have two questions:
1) how can we see which fields on the Contact object have their idLookup property set to true
2) why am I getting the error in the subject line when I execute the code?

答:
1:

```<code>Map<String, Schema.SObjectField> contacFieldsMap = Schema.getGlobalDescribe().get('Contact').getDescribe().fields.getMap();

for (Schema.SObjectField field : contacFieldsMap.values()) {
    Schema.DescribeFieldResult fieldResult = field.getDescribe();
    if (fieldResult.isIdLookup()) System.debug(fieldResult.getName() + ' IS idLookup');
}
</code>```

2: System.debug(Contact.Name.getDescribe().isIdLookup());  // false

Body:
I am trying to enter unique values to the Contact object. Here is the code:

List<Contact> conList = new List<Contact> {
        new Contact(FirstName='Joe',LastName='Smith',Department='Finance'),
        new Contact(FirstName='Kathy',LastName='Smith',Department='Technology'),
        new Contact(FirstName='Caroline',LastName='Roth',Department='Finance'),
        new Contact()};

// Caroline Roth already exists so I want this code to update her record, not insert another Caroline Roth record
Database.UpsertResult[] srList = Database.upsert(conList, Contact.Fields.Name, false);

Salesforce's documentation states
"The upsert statement matches the sObjects with existing records by comparing values of one field. If you don’t specify a field when calling this statement, the upsert statement uses the sObject’s ID to match the sObject with existing records in Salesforce. Alternatively, you can specify a field to use for matching. For custom objects, specify a custom field marked as external ID. For standard objects, you can specify any field that has the idLookup property set to true. For example, the Email field of Contact or User has the idLookup property set."

I have two questions:
1) how can we see which fields on the Contact object have their idLookup property set to true
2) why am I getting the error in the subject line when I execute the code?

Body:
1:

Map<String, Schema.SObjectField> contacFieldsMap = Schema.getGlobalDescribe().get('Contact').getDescribe().fields.getMap();

for (Schema.SObjectField field : contacFieldsMap.values()) {
    Schema.DescribeFieldResult fieldResult = field.getDescribe();
    if (fieldResult.isIdLookup()) System.debug(fieldResult.getName() + ' IS idLookup');
}

2: System.debug(Contact.Name.getDescribe().isIdLookup());  // false