问:
I need better understanding on for loops
can someone explain me how this for loop works (Line 9 in code below), and also if you can show me a simple example with it can be very helpfull, thank you anyways!

```<code>1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;

5 int main(){
6     int n, a , b , ma=0,mb=1000000001;
7     cin >> n ;
8     cin >> a;
9     for( n--; n ; --n ){
10         cin >> b;
11         if(abs(a-b) < abs(ma-mb))
12             ma=a , mb=b;
13         else
14             if(abs(a-b) == abs(ma-mb) && ma+mb > a+b)
15                 ma=a , mb=b;
16         a = b;
17     }
18     cout << ma << " " << mb;
19     return 0;
20 }
</code>```

答:
A for loop is simply another way to write a while loop.  So this:

```<code>for( n--; n ; --n ){
    ...
}
</code>```

is the same as this:

```<code>n--;
while(n) {
    ...
    --n;
}
</code>```

Which, in this specific case, is easier to read. First it decrements n, then does the loop, decrementing n again at the end of each loop, until that decrement causes n to evaluate to false by becoming 0.

Body:
can someone explain me how this for loop works (Line 9 in code below), and also if you can show me a simple example with it can be very helpfull, thank you anyways!

1 #include <iostream>
2 #include <cstdlib>
3
4 using namespace std;

5 int main(){
6     int n, a , b , ma=0,mb=1000000001;
7     cin >> n ;
8     cin >> a;
9     for( n--; n ; --n ){
10         cin >> b;
11         if(abs(a-b) < abs(ma-mb))
12             ma=a , mb=b;
13         else
14             if(abs(a-b) == abs(ma-mb) && ma+mb > a+b)
15                 ma=a , mb=b;
16         a = b;
17     }
18     cout << ma << " " << mb;
19     return 0;
20 }

Body:
A for loop is simply another way to write a while loop.  So this:

for( n--; n ; --n ){
    ...
}

is the same as this:

n--;
while(n) {
    ...
    --n;
}

Which, in this specific case, is easier to read. First it decrements n, then does the loop, decrementing n again at the end of each loop, until that decrement causes n to evaluate to false by becoming 0.


来源: stackexchange

问:
Tradingview only shows Quandl CFTC data for last week
i'm using pine script to pull CFTC COT data into my indicator. However, I am noticing that the latest row of data is never pulled from CFTC - the indicator only shows last week's data.

CFTC data is released every Friday 3:30 PM EST. I am viewing this data on a Saturday - so am expecting to see data released in yesterday's report.

Here's the script i'm using (the outcome does not changes if I use resolution=D or W in the security function in pine script)

```<code>//@version=4
study("COT data bug", shorttitle="Bug demo", precision=0)

qticker =
     syminfo.root == "ES" ? "13874A" :
     syminfo.root == "NQ" ? "209742" :
     syminfo.root == "RTY" ? "239742":
     syminfo.root == "YM" ? "124603" :
     syminfo.root == "ZN" ? "043602" :
     syminfo.root

cot = "QUANDL:CFTC/" + qticker + "_FO_ALL|"
oi = security(cot + "0", "W", close)
asset_mgr_lg = security(cot + "4", "W", close)
asset_mgr_sh = security(cot + "5", "W", close)

plot(oi, title="Open Interest", color=color.black)  // output=232,089, expected=230,513
plot(asset_mgr_lg, title="asset_mgr_lg", color=color.blue) // output=71,131, expected=65,170
plot(asset_mgr_sh, title="asset_mgr_sh", color=color.red) // output=29,288, expected=31,260
</code>```

Has anyone else also faced this problem? Any potential solutions?

Thanks!

答:
One thing to try would be to use lookahead=barmerge.lookahead_on in your security() calls. This may fix the problem in the realtime bar, but will OTOH make your calls use future data on historical bars, where you will need to use the form you are currently using to avoid the lookahead bias.

If using lookahead on is indeed the solution, you could use code like this:

```<code>oiH           = security(cot + "0", "W", close)
asset_mgr_lgH = security(cot + "4", "W", close)
asset_mgr_shH = security(cot + "5", "W", close)
oiR           = security(cot + "0", "W", close, lookahead = barmerge.lookahead_on)
asset_mgr_lgR = security(cot + "4", "W", close, lookahead = barmerge.lookahead_on)
asset_mgr_shR = security(cot + "5", "W", close, lookahead = barmerge.lookahead_on)

oi            = 0.
asset_mgr_lg  = 0.
asset_mgr_sh  = 0.
if barstate.islast
    oi            := oiR
    asset_mgr_lg  := asset_mgr_lgR
    asset_mgr_sh  := asset_mgr_shR
else
    oi            := oiH
    asset_mgr_lg  := asset_mgr_lgH
    asset_mgr_sh  := asset_mgr_shH
</code>```

ContentLicense: CC BY-SA 4.0

Body:
i'm using pine script to pull CFTC COT data into my indicator. However, I am noticing that the latest row of data is never pulled from CFTC - the indicator only shows last week's data.

CFTC data is released every Friday 3:30 PM EST. I am viewing this data on a Saturday - so am expecting to see data released in yesterday's report.

Here's the script i'm using (the outcome does not changes if I use resolution=D or W in the security function in pine script)

//@version=4
study("COT data bug", shorttitle="Bug demo", precision=0)

qticker =
     syminfo.root == "ES" ? "13874A" :
     syminfo.root == "NQ" ? "209742" :
     syminfo.root == "RTY" ? "239742":
     syminfo.root == "YM" ? "124603" :
     syminfo.root == "ZN" ? "043602" :
     syminfo.root

cot = "QUANDL:CFTC/" + qticker + "_FO_ALL|"
oi = security(cot + "0", "W", close)
asset_mgr_lg = security(cot + "4", "W", close)
asset_mgr_sh = security(cot + "5", "W", close)

plot(oi, title="Open Interest", color=color.black)  // output=232,089, expected=230,513
plot(asset_mgr_lg, title="asset_mgr_lg", color=color.blue) // output=71,131, expected=65,170
plot(asset_mgr_sh, title="asset_mgr_sh", color=color.red) // output=29,288, expected=31,260

Has anyone else also faced this problem? Any potential solutions?

Thanks!

Body:
One thing to try would be to use lookahead=barmerge.lookahead_on in your security() calls. This may fix the problem in the realtime bar, but will OTOH make your calls use future data on historical bars, where you will need to use the form you are currently using to avoid the lookahead bias.

If using lookahead on is indeed the solution, you could use code like this:

oiH           = security(cot + "0", "W", close)
asset_mgr_lgH = security(cot + "4", "W", close)
asset_mgr_shH = security(cot + "5", "W", close)
oiR           = security(cot + "0", "W", close, lookahead = barmerge.lookahead_on)
asset_mgr_lgR = security(cot + "4", "W", close, lookahead = barmerge.lookahead_on)
asset_mgr_shR = security(cot + "5", "W", close, lookahead = barmerge.lookahead_on)

oi            = 0.
asset_mgr_lg  = 0.
asset_mgr_sh  = 0.
if barstate.islast
    oi            := oiR
    asset_mgr_lg  := asset_mgr_lgR
    asset_mgr_sh  := asset_mgr_shR
else
    oi            := oiH
    asset_mgr_lg  := asset_mgr_lgH
    asset_mgr_sh  := asset_mgr_shH


问:
Projecting included objects
Im looking for a method to project included objects in EntityFramework Core in a way we can project objects (Select function):

```<code>[HttpGet]
    public async Task<IActionResult> GetBooks()
    {
        return Json(new { data = await _db.Books.Select(b => _mapper.Map<BookDto>(b)).ToListAsync() });
    }
</code>```

Here is my code where I tried to project included objects but its not valid:

```<code>[HttpGet]
    public async Task<JsonResult> GetMessagesAsync()
    {
        var msgs = await _db.Messages.OrderBy(m => m.Sent).Include(m => _mapper.Map<AppUserDto>(m.AppUser)).ToListAsync();
        return Json(new { data = msgs });
    }
</code>```

EDIT1:
I want to project included AppUser objects into AppUserDto.

EDIT2:

```<code>public MappingProfile()
    {
        CreateMap<Book, BookDto>();
        CreateMap<BookDto, Book>();

        CreateMap<Client, ClientDto>();
        CreateMap<ClientDto, Client>();

        CreateMap<Reservation, ReservationDto>();
        CreateMap<ReservationDto, Reservation>();

        CreateMap<AppUser, AppUserDto>();
        CreateMap<AppUserDto, AppUser>();
    }
</code>```

答:
If you have your mapper set up correctly you should be able to just do the following:

```<code>var msgs = await _db.Messages
     .OrderBy(m => m.Sent)
     .Include(m => m.AppUser)
     .Select(m => _mapper.Map<MessageDto>(m))
     .ToListAsync();
</code>```

So your MessageDto will need to have AppUserDto AppUser property among others.

Title: Projecting included objects

Body:
Im looking for a method to project included objects in EntityFramework Core in a way we can project objects (Select function):

[HttpGet]
    public async Task<IActionResult> GetBooks()
    {
        return Json(new { data = await _db.Books.Select(b => _mapper.Map<BookDto>(b)).ToListAsync() });
    }

Here is my code where I tried to project included objects but its not valid:

[HttpGet]
    public async Task<JsonResult> GetMessagesAsync()
    {
        var msgs = await _db.Messages.OrderBy(m => m.Sent).Include(m => _mapper.Map<AppUserDto>(m.AppUser)).ToListAsync();
        return Json(new { data = msgs });
    }

EDIT1:
I want to project included AppUser objects into AppUserDto.

EDIT2:

public MappingProfile()
    {
        CreateMap<Book, BookDto>();
        CreateMap<BookDto, Book>();

        CreateMap<Client, ClientDto>();
        CreateMap<ClientDto, Client>();

        CreateMap<Reservation, ReservationDto>();
        CreateMap<ReservationDto, Reservation>();

        CreateMap<AppUser, AppUserDto>();
        CreateMap<AppUserDto, AppUser>();
    }

Body:
If you have your mapper set up correctly you should be able to just do the following:

var msgs = await _db.Messages
     .OrderBy(m => m.Sent)
     .Include(m => m.AppUser)
     .Select(m => _mapper.Map<MessageDto>(m))
     .ToListAsync();

So your MessageDto will need to have AppUserDto AppUser property among others.


问:
Hibernate Collection Persistence
While going through the Hibernate documentation I came across this statement which states that "Two entities cannot share a reference to the same collection instance", yet when I use the below code no error occurs.

Everything works fine including Hibernate persistence for both entities and corresponding collection references in the DB without any issue.

Am I misunderstanding something? Can this statement be explained and in which scenario is it applicable?

Entity 1:

```<code>public class Person {
    @Id
    @GeneratedValue
    private Long id;

    @CreationTimestamp
    private LocalDateTime date;

    @ElementCollection
    private List<String> phones = new ArrayList<>();

    @ElementCollection
    private Set<LocalDateTime> personOrderDates;
}
</code>```

Entity 2:

```<code>public class Home {
    @Id
    @GeneratedValue
    private long id;

    @ElementCollection
    private List<String> homePhoneList;
}
</code>```

Hibernate persist code:

```<code>Person person1 = entityManager.find(Person.class, 48l);
Person person2 = entityManager.find(Person.class, 49l);

List<String> newPhoneList = new ArrayList();
newPhoneList.add("x");
newPhoneList.add("y");
newPhoneList.add("z");

person1.setPhones(newPhoneList);
person2.setPhones(newPhoneList);
Home home1 = Home.builder().homePhoneList(newPhoneList).build();

entityManager.persist(home1);
entityManager.persist(person1);
entityManager.persist(person2);
</code>```

Here we clearly are able to share the same collection reference between two instances of the same entity (Person), as well as with entirely different entity type (Home) without any issue. All three entities are saving/updating in the DB.

答:
Two entities cannot share a reference to the same collection instance

This is still correct. it means that if you load one of these entities and change phone collection, other entity's phone collection remains unchanged.

You are simply share a reference in your java and not in the database. Next time this shared reference will be gone and all of your entities consist of an individual reference to their own lists.

Title: Hibernate Collection Persistence

Body:
While going through the Hibernate documentation I came across this statement which states that "Two entities cannot share a reference to the same collection instance", yet when I use the below code no error occurs.

Everything works fine including Hibernate persistence for both entities and corresponding collection references in the DB without any issue.

Am I misunderstanding something? Can this statement be explained and in which scenario is it applicable?

Entity 1:

public class Person {
    @Id
    @GeneratedValue
    private Long id;

    @CreationTimestamp
    private LocalDateTime date;

    @ElementCollection
    private List<String> phones = new ArrayList<>();

    @ElementCollection
    private Set<LocalDateTime> personOrderDates;
}

Entity 2:

public class Home {
    @Id
    @GeneratedValue
    private long id;

    @ElementCollection
    private List<String> homePhoneList;
}

Hibernate persist code:

Person person1 = entityManager.find(Person.class, 48l);
Person person2 = entityManager.find(Person.class, 49l);

List<String> newPhoneList = new ArrayList();
newPhoneList.add("x");
newPhoneList.add("y");
newPhoneList.add("z");

person1.setPhones(newPhoneList);
person2.setPhones(newPhoneList);
Home home1 = Home.builder().homePhoneList(newPhoneList).build();

entityManager.persist(home1);
entityManager.persist(person1);
entityManager.persist(person2);

Here we clearly are able to share the same collection reference between two instances of the same entity (Person), as well as with entirely different entity type (Home) without any issue. All three entities are saving/updating in the DB.


问:
how to force sleep or any other type of timer to execute at particular time in c++?
I am doing socket programming in C and I want to do the following thing:

```<code>pid = fork();
if(pid == 0){
    //child process
    for(int m=0;m<2;m++){
        j=0;
        for(i=0;i<len_neighbors;i++){
            socket_des1[i] = get_socket_connection_client(hostname1, neighbor_socket[i],(char *) "udp");
            //sending data to other routers
            cout<<"\nMessage: Sending routing table to neighbor, "<<neighbors[i];
            if (send(socket_des1[i], &message1[0], message1.length(), 0) < 0){
                perror("\nError:Message sending failed\n");
                exit(1);
            }
            j++;
        }
        for(i=0;i<len_neighbors;i++){
            close(socket_des1[i]);
        }
        sleep(30);
        cout<<"Hello";
    }
}else{
    // code for parent process
}
</code>```

So basically the process will send data to all the neighbors and the goto sleep. What is happening here is the process sends data to first neighbor and then sleeps for 30secs. How do I force the process to finish sending and then execute sleep(30) statement.

I am using forking for the process. And the code above is part of child process.

答: I can only guess what is the problem (please add the child code creation to check), I think that when this code is executed by the first child the number of neighbors is 0, with the second the number will be 1, and so on. I would try with a sleep at the beginning so this gives enough time to the others children to fork before sending all the msg.</p>

ContentLicense: CC BY-SA 3.0

Body:
I am doing socket programming in C and I want to do the following thing:

pid = fork();
if(pid == 0){
    //child process
    for(int m=0;m<2;m++){
        j=0;
        for(i=0;i<len_neighbors;i++){
            socket_des1[i] = get_socket_connection_client(hostname1, neighbor_socket[i],(char *) "udp");
            //sending data to other routers
            cout<<"\nMessage: Sending routing table to neighbor, "<<neighbors[i];
            if (send(socket_des1[i], &message1[0], message1.length(), 0) < 0){
                perror("\nError:Message sending failed\n");
                exit(1);
            }
            j++;
        }
        for(i=0;i<len_neighbors;i++){
            close(socket_des1[i]);
        }
        sleep(30);
        cout<<"Hello";
    }
}else{
    // code for parent process
}

So basically the process will send data to all the neighbors and the goto sleep. What is happening here is the process sends data to first neighbor and then sleeps for 30secs. How do I force the process to finish sending and then execute sleep(30) statement.

I am using forking for the process. And the code above is part of child process.


问:
Android, check if back button was pressed before in other Activity
I have started to play around with Firebase and made a simple activity to create an account and log in.
I all works as expected however, I noticed something once a user had logged in and got to the menu screen. If the user pressed on the back button on the android device you would expect that the app would close or go back to where you were before, but because the of the onStart() in LoginActivity it throws back the user to the menu page again. I don't want to change the onStart() method as I like that it logs you if you already have an account. So what I tried was to close the app when back button is pressed in the menu activity like so:

```<code>@Override
    public void onBackPressed() {
        finish();
        System.exit(0);
    }

</code>```

However, this did not work and I still can't close the app then pressing back button in the menu activty as the LoginActivity still brings me back.

This is the LoginActivity:

```<code>public class LoginActivity extends AppCompatActivity {

    // [START declare_auth]
    private FirebaseAuth mAuth;
    // [END declare_auth]

    private static final String TAG = "EmailPassword";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // [START initialize_auth]
        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();
        // [END initialize_auth]

    }

    //here we immediately check if user is already logged in then log in
    @Override
    protected void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        if (currentUser != null)
            updateUI(currentUser);
    }

    private void updateUI(FirebaseUser currentUser) {
        Intent mainIntent = new Intent(LoginActivity.this, MenuActivity.class);
        Toast.makeText(this, "This is current user: " + currentUser, Toast.LENGTH_LONG).show();
        startActivity(mainIntent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    public void createAccount(View view) {
        final EditText emailEdit = (EditText) findViewById(R.id.email_field);
        final String email = emailEdit.getText().toString();
        final EditText passwordEdit = (EditText) findViewById(R.id.password_field);
        final String password = passwordEdit.getText().toString();
        Log.d(TAG, "createAccount:" + email);

        // [START create_user_with_email]
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "createUserWithEmail:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            updateUI(user);
                        } else {

                            try
                            {
                                throw Objects.requireNonNull(task.getException());
                            }
                            // if user enters wrong email.
                            catch (FirebaseAuthWeakPasswordException weakPassword)
                            {
                                Log.d(TAG, "onComplete: weak_password");

                                Toast.makeText(LoginActivity.this, "Password to weak", Toast.LENGTH_LONG).show();
                            }
                            // if user enters wrong password.
                            catch (FirebaseAuthInvalidCredentialsException malformedEmail)
                            {
                                Log.d(TAG, "onComplete: malformed_email");

                                Toast.makeText(LoginActivity.this, "Wrong email", Toast.LENGTH_LONG).show();
                            }
                            catch (FirebaseAuthUserCollisionException existEmail)
                            {
                                Log.d(TAG, "onComplete: exist_email");

                                Toast.makeText(LoginActivity.this, "Email already exists", Toast.LENGTH_LONG).show();
                            }
                            catch (Exception e)
                            {
                                Log.d(TAG, "onComplete: " + e.getMessage());
                                Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
                                Toast.makeText(LoginActivity.this, "Please try again", Toast.LENGTH_SHORT).show();
                            }
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "createUserWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                });
        // [END create_user_with_email]
    }

}

</code>```

Is there a way I can close the app in the menu activity or a way to check in the onStart() method in LoginActivity if we got there through pressing the back button on the phone?

答:
LoginActivity will never show anymore with the back button. unless you reopen the application or make an intent there. You can try Adding this.</p>

```<code><activity
   android:name=".LoginActivity"
   android:noHistory="true" />
</code>```

Body:
I have started to play around with Firebase and made a simple activity to create an account and log in.
I all works as expected however, I noticed something once a user had logged in and got to the menu screen. If the user pressed on the back button on the android device you would expect that the app would close or go back to where you were before, but because the of the onStart() in LoginActivity it throws back the user to the menu page again. I don't want to change the onStart() method as I like that it logs you if you already have an account. So what I tried was to close the app when back button is pressed in the menu activity like so:

@Override
    public void onBackPressed() {
        finish();
        System.exit(0);
    }

However, this did not work and I still can't close the app then pressing back button in the menu activty as the LoginActivity still brings me back.

This is the LoginActivity:

public class LoginActivity extends AppCompatActivity {

    // [START declare_auth]
    private FirebaseAuth mAuth;
    // [END declare_auth]

    private static final String TAG = "EmailPassword";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        // [START initialize_auth]
        // Initialize Firebase Auth
        mAuth = FirebaseAuth.getInstance();
        // [END initialize_auth]

    }

    //here we immediately check if user is already logged in then log in
    @Override
    protected void onStart() {
        super.onStart();
        // Check if user is signed in (non-null) and update UI accordingly.
        FirebaseUser currentUser = mAuth.getCurrentUser();
        if (currentUser != null)
            updateUI(currentUser);
    }

    private void updateUI(FirebaseUser currentUser) {
        Intent mainIntent = new Intent(LoginActivity.this, MenuActivity.class);
        Toast.makeText(this, "This is current user: " + currentUser, Toast.LENGTH_LONG).show();
        startActivity(mainIntent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
    }

    public void createAccount(View view) {
        final EditText emailEdit = (EditText) findViewById(R.id.email_field);
        final String email = emailEdit.getText().toString();
        final EditText passwordEdit = (EditText) findViewById(R.id.password_field);
        final String password = passwordEdit.getText().toString();
        Log.d(TAG, "createAccount:" + email);

        // [START create_user_with_email]
        mAuth.createUserWithEmailAndPassword(email, password)
                .addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
                    @Override
                    public void onComplete(@NonNull Task<AuthResult> task) {
                        if (task.isSuccessful()) {
                            // Sign in success, update UI with the signed-in user's information
                            Log.d(TAG, "createUserWithEmail:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                            updateUI(user);
                        } else {

                            try
                            {
                                throw Objects.requireNonNull(task.getException());
                            }
                            // if user enters wrong email.
                            catch (FirebaseAuthWeakPasswordException weakPassword)
                            {
                                Log.d(TAG, "onComplete: weak_password");

                                Toast.makeText(LoginActivity.this, "Password to weak", Toast.LENGTH_LONG).show();
                            }
                            // if user enters wrong password.
                            catch (FirebaseAuthInvalidCredentialsException malformedEmail)
                            {
                                Log.d(TAG, "onComplete: malformed_email");

                                Toast.makeText(LoginActivity.this, "Wrong email", Toast.LENGTH_LONG).show();
                            }
                            catch (FirebaseAuthUserCollisionException existEmail)
                            {
                                Log.d(TAG, "onComplete: exist_email");

                                Toast.makeText(LoginActivity.this, "Email already exists", Toast.LENGTH_LONG).show();
                            }
                            catch (Exception e)
                            {
                                Log.d(TAG, "onComplete: " + e.getMessage());
                                Toast.makeText(LoginActivity.this, "Error", Toast.LENGTH_SHORT).show();
                                Toast.makeText(LoginActivity.this, "Please try again", Toast.LENGTH_SHORT).show();
                            }
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "createUserWithEmail:failure", task.getException());
                            Toast.makeText(LoginActivity.this, "Authentication failed.",
                                    Toast.LENGTH_SHORT).show();
                        }

                    }
                });
        // [END create_user_with_email]
    }

}

Is there a way I can close the app in the menu activity or a way to check in the onStart() method in LoginActivity if we got there through pressing the back button on the phone?

Body:
LoginActivity will never show anymore with the back button. unless you reopen the application or make an intent there. You can try Adding this.

<activity
   android:name=".LoginActivity"
   android:noHistory="true" />


问:
Improve performance finding matches in a big list/array
I am building a tool to find images in a big folder of images (400k images). On that folder I have images like this:

c:\images\100001_01.jpg

c:\images\100001_05.jpg

c:\images\100001_07.jpg

c:\images\100005_05.jpg

c:\images\100010_00.jpg

Then I have my references in a text box, but only the 6 digit number:
100001

100005

100006

Etc

So I have let's say 1000 references I need to have the images for, I want to loop through all the image folder and take the file if exists. I have built this using both an array with loops and a list and getting the index. I thought getting the index of the list would be much faster, but they are actually the same.

Here are the two routines I have developed, one is using a list and then getting FindIndex to get the index. The second option is looping through all the references and at the same time looping through all images to check if any contains that reference - that is 400 million loops if I use a set of 1000 references!

Using a list takes 69 seconds, however looping through the arrays takes 64 seconds. Nevertheless taking all images on the directory using GetFile takes 120 seconds already.

Can you think of any way to make this faster?

```<code> Private Sub ExtractImagesUsingList()

    Dim ListOfReferences As New List(Of String) 'the actual list of references is in a textbox, ie.: 100001, 100002, etc

    For Each line In txtBox.Lines
        ListOfReferences.Add(line.ToString)
    Next

    Dim ListOfimages As New List(Of String)

    For Each file In IO.Directory.GetFiles("c:\images\")
        ListOfimages.Add(file)
    Next

    For Each ref In ListOfReferences
        Dim index As Integer = ListOfimages.FindIndex(Function(x As String) x.Contains(ref))
    Next
End Sub

Private Sub ExtractImagesUsingArrayLoop()

    Dim ListOfreferences As New List(Of String)'the actual list of references is in a textbox

    For Each line In txtBox.Lines
        If line.Length > 1 Then
            ListOfReferences.Add(line.ToString)
        End If
    Next

    Dim ArrayImages() As String = IO.Directory.GetFiles("c:\images\")

    For Each reference In ListOfReferences
        For Each image In ArrayImages
            If image.Contains(reference) Then
                 Exit For ' I exist the FOR here because I am only interested in one image per reference
            End If
        Next
    Next
End Sub
</code>```

答:
It's not 100% clear what you're trying to accomplish, but you could improve performance by implementing Directory.EnumerateFiles.

Additionally, you could pair this with the built-in search function using a wildcard match against the known reference key from the reference list.

Finally, if the image directory is not subject to frequent changes, you could cache the images in a dictionary to speed up future searches.

Here is a rough example of those ideas.  Note I've removed any references to form controls, and assume parameters are instead being passed in.

```<code>Private _imageMap As Dictionary(Of String, ICollection(Of String))

Public ReadOnly Property ImageMap As Dictionary(Of String, ICollection(Of String))
    Get
        If _imageMap Is Nothing Then
            _imageMap = New Dictionary(Of String, ICollection(Of String))()
        End If

        Return _imageMap
    End Get
End Property

Public Sub RefreshImageMap()
    _imageMap = Nothing
End Sub

Public Function GetImagePaths(imageFolder As String, referenceKey As String) As ICollection(Of String)

    Dim imagePaths As ICollection(Of String) = Nothing
    If Not ImageMap.TryGetValue(referenceKey, imagePaths) Then

        imagePaths = Directory.EnumerateFiles(imageFolder, $"{referenceKey}_*.jpg").ToList()
        ImageMap.Add(referenceKey, imagePaths)

    End If

    Return imagePaths

End Function
</code>```

Also if you wanted to run multiple reference keys through a function, but also needed to keep the original reference key passed in, you could add something like this:

```<code>Public Iterator Function GetImagePaths(imageFolder As String, referenceKeys As IEnumerable(Of String)) As IEnumerable(Of KeyValuePair(Of String, ICollection(Of String)))

    For Each referenceKey As String In referenceKeys

        Dim imagePaths = GetImagePaths(imageFolder, referenceKey)
        Yield New KeyValuePair(Of String, ICollection(Of String))(referenceKey, imagePaths)
    Next

End Function
</code>```

None of this is tested, and this lacks proper parameter checks on functions, but it should give you a direction to try.

Body:
I am building a tool to find images in a big folder of images (400k images). On that folder I have images like this:

c:\images\100001_01.jpg

c:\images\100001_05.jpg

c:\images\100001_07.jpg

c:\images\100005_05.jpg

c:\images\100010_00.jpg

Then I have my references in a text box, but only the 6 digit number:
100001

100005

100006

Etc

So I have let's say 1000 references I need to have the images for, I want to loop through all the image folder and take the file if exists. I have built this using both an array with loops and a list and getting the index. I thought getting the index of the list would be much faster, but they are actually the same.

Here are the two routines I have developed, one is using a list and then getting FindIndex to get the index. The second option is looping through all the references and at the same time looping through all images to check if any contains that reference - that is 400 million loops if I use a set of 1000 references!

Using a list takes 69 seconds, however looping through the arrays takes 64 seconds. Nevertheless taking all images on the directory using GetFile takes 120 seconds already.

Can you think of any way to make this faster?

 Private Sub ExtractImagesUsingList()

    Dim ListOfReferences As New List(Of String) 'the actual list of references is in a textbox, ie.: 100001, 100002, etc

    For Each line In txtBox.Lines
        ListOfReferences.Add(line.ToString)
    Next

    Dim ListOfimages As New List(Of String)

    For Each file In IO.Directory.GetFiles("c:\images\")
        ListOfimages.Add(file)
    Next

    For Each ref In ListOfReferences
        Dim index As Integer = ListOfimages.FindIndex(Function(x As String) x.Contains(ref))
    Next
End Sub

Private Sub ExtractImagesUsingArrayLoop()

    Dim ListOfreferences As New List(Of String)'the actual list of references is in a textbox

    For Each line In txtBox.Lines
        If line.Length > 1 Then
            ListOfReferences.Add(line.ToString)
        End If
    Next

    Dim ArrayImages() As String = IO.Directory.GetFiles("c:\images\")

    For Each reference In ListOfReferences
        For Each image In ArrayImages
            If image.Contains(reference) Then
                 Exit For ' I exist the FOR here because I am only interested in one image per reference
            End If
        Next
    Next
End Sub

Body:
It's not 100% clear what you're trying to accomplish, but you could improve performance by implementing Directory.EnumerateFiles.

Additionally, you could pair this with the built-in search function using a wildcard match against the known reference key from the reference list.

Finally, if the image directory is not subject to frequent changes, you could cache the images in a dictionary to speed up future searches.

Here is a rough example of those ideas.  Note I've removed any references to form controls, and assume parameters are instead being passed in.

Private _imageMap As Dictionary(Of String, ICollection(Of String))

Public ReadOnly Property ImageMap As Dictionary(Of String, ICollection(Of String))
    Get
        If _imageMap Is Nothing Then
            _imageMap = New Dictionary(Of String, ICollection(Of String))()
        End If

        Return _imageMap
    End Get
End Property

Public Sub RefreshImageMap()
    _imageMap = Nothing
End Sub

Public Function GetImagePaths(imageFolder As String, referenceKey As String) As ICollection(Of String)

    Dim imagePaths As ICollection(Of String) = Nothing
    If Not ImageMap.TryGetValue(referenceKey, imagePaths) Then

        imagePaths = Directory.EnumerateFiles(imageFolder, $"{referenceKey}_*.jpg").ToList()
        ImageMap.Add(referenceKey, imagePaths)

    End If

    Return imagePaths

End Function

Also if you wanted to run multiple reference keys through a function, but also needed to keep the original reference key passed in, you could add something like this:

Public Iterator Function GetImagePaths(imageFolder As String, referenceKeys As IEnumerable(Of String)) As IEnumerable(Of KeyValuePair(Of String, ICollection(Of String)))

    For Each referenceKey As String In referenceKeys

        Dim imagePaths = GetImagePaths(imageFolder, referenceKey)
        Yield New KeyValuePair(Of String, ICollection(Of String))(referenceKey, imagePaths)
    Next

End Function

None of this is tested, and this lacks proper parameter checks on functions, but it should give you a direction to try.


问:
Jinja Template Variable Email ID not rendering when using ON_FAILURE_CALLBACK
Need help on rendering the jinja template email ID in the On_failure_callback.

I understand that rendering templates work fine in the SQL file or with the operator having template_fields .How do I get below code rendered the jinja template variable

It works fine with Variable.get('email_edw_alert'), but I don't want to use Variable method to avoid hitting DB

Below is the Dag file

```<code>import datetime
import os
from functools import partial
from datetime import timedelta
from airflow.models import DAG,Variable
from airflow.contrib.operators.snowflake_operator import SnowflakeOperator
from alerts.email_operator import dag_failure_email

def get_db_dag(
    *,
    dag_id,
    start_date,
    schedule_interval,
    max_taskrun,
    max_dagrun,
    proc_nm,
    load_sql
):

    default_args = {
        'owner': 'airflow',
        'start_date': start_date,
        'provide_context': True,
        'execution_timeout': timedelta(minutes=max_taskrun),
        'retries': 0,
        'retry_delay': timedelta(minutes=3),
        'retry_exponential_backoff': True,
        'email_on_retry': False,
    }

    dag = DAG(
        dag_id=dag_id,
        schedule_interval=schedule_interval,
        dagrun_timeout=timedelta(hours=max_dagrun),
        template_searchpath=tmpl_search_path,
        default_args=default_args,
        max_active_runs=1,
        catchup='{{var.value.dag_catchup}}',
        on_failure_callback=partial(dag_failure_email, config={'email_address': '{{var.value.email_edw_alert}}'}),
    )

    load_table = SnowflakeOperator(
        task_id='load_table',
        sql=load_sql,
        snowflake_conn_id=CONN_ID,
        autocommit=True,
        dag=dag,
    )

    load_table

    return dag

# ======== DAG DEFINITIONS #

edw_table_A = get_db_dag(
    dag_id='edw_table_A',
    start_date=datetime.datetime(2020, 5, 21),
    schedule_interval='0 5 * * *',
    max_taskrun=3,  # Minutes
    max_dagrun=1,  # Hours
    load_sql='recon/extract.sql',
)
</code>```

Below is the python code alerts.email_operator

```<code>import logging
from airflow.utils.email import send_email
from airflow.models import Variable

logger = logging.getLogger(__name__)

TIME_FORMAT = "%Y-%m-%d %H:%M:%S"

def dag_failure_email(context, config=None):

    config = {} if config is None else config
    task_id = context.get('task_instance').task_id
    dag_id = context.get("dag").dag_id
    execution_time = context.get("execution_date").strftime(TIME_FORMAT)
    reason = context.get("exception")

    alerting_email_address = config.get('email_address')

    dag_failure_html_body = f"""<html>
    <header><title>The following DAG has failed!</title></header>
    <body>
    <b>DAG Name</b>: {dag_id}<br/>
    <b>Task Id</b>: {task_id}<br/>
    <b>Execution Time (UTC)</b>: {execution_time}<br/>
    <b>Reason for Failure</b>: {reason}<br/>
    </body>
    </html>
    """

    try:
        if reason != 'dagrun_timeout':
            send_email(
                to=alerting_email_address,
                subject=f"Airflow alert: <DagInstance: {dag_id} - {execution_time} [failed]",
                html_content=dag_failure_html_body,
            )
    except Exception as e:
        logger.error(
            f'Error in sending email to address {alerting_email_address}: {e}',
            exc_info=True,
        )
</code>```

I have also tried other way too , even below one is not working

```<code>   try:
        if reason != 'dagrun_timeout':
            send_email = EmailOperator(
               to=alerting_email_address,
               task_id='email_task',
               subject=f"Airflow alert: <DagInstance: {dag_id} - {execution_time} [failed]",
               params={'content1': 'random'},
               html_content=dag_failure_html_body,
           )
            send_email.dag = context['dag']
            #send_email.to = send_email.get_template_env().from_string(send_email.to).render(**context)
            send_email.to = send_email.render_template(alerting_email_address, send_email.to, context)
            send_email.execute(context)
    except Exception as e:
        logger.error(
            f'Error in sending email to address {alerting_email_address}: {e}',
            exc_info=True,
        )
</code>```

答:
I don't think templates would work in this way - you'll have to have something specifically parse the template.  Usually jinja templates in Airflow are used to pass templated fields through to operators, and rendered using the render_template function (https://airflow.apache.org/docs/stable/_modules/airflow/models/baseoperator.html#BaseOperator.render_template)

Since your callback function isn't an operator, it won't have this method by default.

I think the best thing to do here would be to either explicitly call Variable.get during runtime of the callback function itself, rather than in the DAG definition, or  implement some version of that render_template_fields function in your callback.  Both of these solutions would result only in hitting the DB during runtime of this task, rather than whenever the DAG is created.

Edit: Just saw your attempt to do the rendering explicitly via the operator.  Are the fields that you want to be templated specified as templated_fields within email operator?

Body:
Need help on rendering the jinja template email ID in the On_failure_callback.

I understand that rendering templates work fine in the SQL file or with the operator having template_fields .How do I get below code rendered the jinja template variable

It works fine with Variable.get('email_edw_alert'), but I don't want to use Variable method to avoid hitting DB

Below is the Dag file

import datetime
import os
from functools import partial
from datetime import timedelta
from airflow.models import DAG,Variable
from airflow.contrib.operators.snowflake_operator import SnowflakeOperator
from alerts.email_operator import dag_failure_email

def get_db_dag(
    *,
    dag_id,
    start_date,
    schedule_interval,
    max_taskrun,
    max_dagrun,
    proc_nm,
    load_sql
):

    default_args = {
        'owner': 'airflow',
        'start_date': start_date,
        'provide_context': True,
        'execution_timeout': timedelta(minutes=max_taskrun),
        'retries': 0,
        'retry_delay': timedelta(minutes=3),
        'retry_exponential_backoff': True,
        'email_on_retry': False,
    }

    dag = DAG(
        dag_id=dag_id,
        schedule_interval=schedule_interval,
        dagrun_timeout=timedelta(hours=max_dagrun),
        template_searchpath=tmpl_search_path,
        default_args=default_args,
        max_active_runs=1,
        catchup='{{var.value.dag_catchup}}',
        on_failure_callback=partial(dag_failure_email, config={'email_address': '{{var.value.email_edw_alert}}'}),
    )

    load_table = SnowflakeOperator(
        task_id='load_table',
        sql=load_sql,
        snowflake_conn_id=CONN_ID,
        autocommit=True,
        dag=dag,
    )

    load_table

    return dag

# ======== DAG DEFINITIONS #

edw_table_A = get_db_dag(
    dag_id='edw_table_A',
    start_date=datetime.datetime(2020, 5, 21),
    schedule_interval='0 5 * * *',
    max_taskrun=3,  # Minutes
    max_dagrun=1,  # Hours
    load_sql='recon/extract.sql',
)

Below is the python code alerts.email_operator

import logging
from airflow.utils.email import send_email
from airflow.models import Variable

logger = logging.getLogger(__name__)

TIME_FORMAT = "%Y-%m-%d %H:%M:%S"

def dag_failure_email(context, config=None):

    config = {} if config is None else config
    task_id = context.get('task_instance').task_id
    dag_id = context.get("dag").dag_id
    execution_time = context.get("execution_date").strftime(TIME_FORMAT)
    reason = context.get("exception")

    alerting_email_address = config.get('email_address')

    dag_failure_html_body = f"""
    <title>The following DAG has failed!</title>

    DAG Name: {dag_id}

    Task Id: {task_id}

    Execution Time (UTC): {execution_time}

    Reason for Failure: {reason}

    """

    try:
        if reason != 'dagrun_timeout':
            send_email(
                to=alerting_email_address,
                subject=f"Airflow alert: <DagInstance: {dag_id} - {execution_time} [failed]",
                html_content=dag_failure_html_body,
            )
    except Exception as e:
        logger.error(
            f'Error in sending email to address {alerting_email_address}: {e}',
            exc_info=True,
        )

I have also tried other way too , even below one is not working

   try:
        if reason != 'dagrun_timeout':
            send_email = EmailOperator(
               to=alerting_email_address,
               task_id='email_task',
               subject=f"Airflow alert: <DagInstance: {dag_id} - {execution_time} [failed]",
               params={'content1': 'random'},
               html_content=dag_failure_html_body,
           )
            send_email.dag = context['dag']
            #send_email.to = send_email.get_template_env().from_string(send_email.to).render(**context)
            send_email.to = send_email.render_template(alerting_email_address, send_email.to, context)
            send_email.execute(context)
    except Exception as e:
        logger.error(
            f'Error in sending email to address {alerting_email_address}: {e}',
            exc_info=True,
        )


问:
How to make image from internet responsive on Android layout?
I have an Imageview on my layout which I fill with a .jpg that I download from the web. The thing is that I am trying to make the image container responsive to the screen size since in larger phones the image is seen small.

```<code>    public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
    }

    public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String imageUrl="https:url";

        new DownloadImageTask((ImageView) findViewById(R.id.imvAd))
                .execute(imageUrl);
    }
    }
</code>```

I do not want to give fixed values.

Any help or suggestions on what to look for would be great

This is the layout

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".startActivities.LoginActivity"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:background="@color/white"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imvLogo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@mipmap/logo"
                tools:ignore="ContentDescription" />

            <LinearLayout
                android:id="@+id/lytProgressBarLogin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:visibility="gone">

                <ProgressBar
                    android:id="@+id/pgbLogin"
                    style="?android:attr/progressBarStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center_vertical"
                android:orientation="vertical"
                android:padding="10dp">

                <TextView
                    android:id="@+id/txtwelcome"
                    style="@style/styleTextview1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@string/welcome" />

                <EditText
                    android:id="@+id/edtPwdworker"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:hint="@string/password"
                    android:inputType="numberPassword" />

                <Button
                    android:id="@+id/btnLogin"
                    style="@style/styleButtonConsult"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:text="@string/login" />
            </LinearLayout>

            <TextView
                android:id="@+id/txtInfoRoute"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="10dp"
                android:layout_weight="90"
                android:gravity="center" />

            <TextView
                android:id="@+id/txtPinDeviceLogin"
                style="@style/styleTextviewsubTitlebold"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dp"
                android:gravity="center"
                android:text="@string/pinDevice" />

            <ImageView
                android:id="@+id/imvAd"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:padding="10dp"
                tools:ignore="ContentDescription" />
        </LinearLayout>

    </ScrollView>

    <TextView
        android:id="@+id/txtVersionLogin"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="95"
        android:gravity="center" />

</LinearLayout>
</code>```

答:
you can use glide

use Gradle:

```<code>repositories {
  mavenCentral()
  google()
}

dependencies {
  implementation 'com.github.bumptech.glide:glide:4.11.0'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}
</code>```

can resize Image
java:

```<code>Glide
.with(context)
.load(path)
.apply(new RequestOptions().override(600, 200))
.into(imageViewResizeCenterCrop);
</code>```

xml :

```<code>  <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:weightSum="10"
    android:orientation="vertical">
    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="6"
        android:weightSum="10"
        android:orientation="horizontal">

        <View
            android:layout_width="0dp"
            android:layout_height="10dp"
            android:layout_weight="2"/>
        <ImageView
            android:id="@+id/imvAd"
            android:layout_width="0dp"
            android:layout_weight="6"
            android:layout_height="match_parent"
            android:padding="10dp" />

        <View
            android:layout_width="0dp"
            android:layout_height="10dp"
            android:layout_weight="2"/>
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"/>

</LinearLayout>
</code>```

Body:
I have an Imageview on my layout which I fill with a .jpg that I download from the web. The thing is that I am trying to make the image container responsive to the screen size since in larger phones the image is seen small.

    public class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {

    ImageView bmImage;

    public DownloadImageTask(ImageView bmImage) {
        this.bmImage = bmImage;
    }

    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;
        try {
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        } catch (Exception e) {
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result) {
        bmImage.setImageBitmap(result);
    }
    }

    public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        String imageUrl="https:url";

        new DownloadImageTask((ImageView) findViewById(R.id.imvAd))
                .execute(imageUrl);
    }
    }

I do not want to give fixed values.

Any help or suggestions on what to look for would be great

This is the layout

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".startActivities.LoginActivity"
    android:orientation="vertical">

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="5"
        android:background="@color/white"
        android:orientation="vertical">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <ImageView
                android:id="@+id/imvLogo"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:src="@mipmap/logo"
                tools:ignore="ContentDescription" />

            <LinearLayout
                android:id="@+id/lytProgressBarLogin"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="vertical"
                android:visibility="gone">

                <ProgressBar
                    android:id="@+id/pgbLogin"
                    style="?android:attr/progressBarStyle"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_gravity="center" />

            </LinearLayout>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:gravity="center_vertical"
                android:orientation="vertical"
                android:padding="10dp">

                <TextView
                    android:id="@+id/txtwelcome"
                    style="@style/styleTextview1"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:gravity="center"
                    android:text="@string/welcome" />

                <EditText
                    android:id="@+id/edtPwdworker"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:ems="10"
                    android:hint="@string/password"
                    android:inputType="numberPassword" />

                <Button
                    android:id="@+id/btnLogin"
                    style="@style/styleButtonConsult"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp"
                    android:text="@string/login" />
            </LinearLayout>

            <TextView
                android:id="@+id/txtInfoRoute"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginBottom="10dp"
                android:layout_weight="90"
                android:gravity="center" />

            <TextView
                android:id="@+id/txtPinDeviceLogin"
                style="@style/styleTextviewsubTitlebold"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginBottom="5dp"
                android:gravity="center"
                android:text="@string/pinDevice" />

            <ImageView
                android:id="@+id/imvAd"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="center"
                android:padding="10dp"
                tools:ignore="ContentDescription" />
        </LinearLayout>

    </ScrollView>

    <TextView
        android:id="@+id/txtVersionLogin"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="95"
        android:gravity="center" />

</LinearLayout>

Body:
you can use glide

use Gradle:

repositories {
  mavenCentral()
  google()
}

dependencies {
  implementation 'com.github.bumptech.glide:glide:4.11.0'
  annotationProcessor 'com.github.bumptech.glide:compiler:4.11.0'
}

can resize Image
java:

Glide
.with(context)
.load(path)
.apply(new RequestOptions().override(600, 200))
.into(imageViewResizeCenterCrop);

xml :

  <LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:weightSum="10"
    android:orientation="vertical">
    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="6"
        android:weightSum="10"
        android:orientation="horizontal">

        <View
            android:layout_width="0dp"
            android:layout_height="10dp"
            android:layout_weight="2"/>
        <ImageView
            android:id="@+id/imvAd"
            android:layout_width="0dp"
            android:layout_weight="6"
            android:layout_height="match_parent"
            android:padding="10dp" />

        <View
            android:layout_width="0dp"
            android:layout_height="10dp"
            android:layout_weight="2"/>
    </LinearLayout>

    <View
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="2"/>

</LinearLayout>


问:
Can someone help me to install the netflix's VMAF library in Ubuntu
First of all, I have to say that I am not very experienced in ubuntu.
I would like to install this library to use with FFMPEG.

I am following these steps, but I can manage to install it well...

https://github.com/Netflix/vmaf/blob/master/resource/doc/VMAF_Python_library.md

Could someone tell me what are the exact steps (commands) that I have to follow.

On the other hand, someone knows if there are other metrics that can ffmpeg calculates directly (apart from PSNR or SSIM)?

Many thanks

答: Download an already compiled ffmpeg from johnvansickle.com. It supports the libvmaf filter. For instructions on how to install it see the FAQ.


问:
2nd level view in ASP.net MVC
I have an address "http://localhost:3579/MusicStore/StoreManager" which is really showing "http://localhost:3579/MusicStore/StoreManager/Index".

I want to go to another another address on the same level from the index: "http://localhost:3579/MusicStore/StoreManager/Edit". Edit is a view inside the StoreManager folder, so a 2nd level view.

I'm confused as to which controller I'd even put the method in. I tried putting my "public ActionResult Edit" in MusicStoreController, but it wasn't recognized. How can I do this?

答:
It sounds like your action is in the right place, but you will need to make sure there is a route specified to route your URL to that action.  Make sure a route like this is specified in your global.asax or area registration file if your project is using areas:</p>

```<code>context.MapRoute(
                "MusicStore_Edit",
                "MusicStore/StoreManager/{action}",
                new { action = "Index"}
            );
</code>```

Title: 2nd level view in ASP.net MVC

Body:
It sounds like your action is in the right place, but you will need to make sure there is a route specified to route your URL to that action.  Make sure a route like this is specified in your global.asax or area registration file if your project is using areas:

context.MapRoute(
                "MusicStore_Edit",
                "MusicStore/StoreManager/{action}",
                new { action = "Index"}
            );


问:
Should web based applications follow web standards?
By day, I am a front-end web developer but in my off time I dabble with other languages such as C, Objective-C, Python, etc. When I first got into web development the idea of web applications was just getting started.

Since then two amazing frameworks have appeared, SproutIt's SproutCore and 280 North's Cappuccino (+Objective-J). SproutCore is being used by Apple for it's MobileMe application and 280 North released 280 Slides. Both of these applications are amazing and they are a testament to what is possible on the web. So the momentum is shifting. Web applications starting to look and act like desktop applications.

So my question is this: should web based applications follow web standards, separation of markup (content), presentation (design), and behavior (functionality) or no?

I am not sure about SproutCore since I have not look at the source code, but I know that if you go to 280slides.com and turn off the JavaScript everything basically disappears. You are left with some meaningless words.

Let me clarify, I understand that web based applications such as 280 Slides is meant to have JavaScript on and not meant to be functional without it but in my day job my main focus is writing clean markup, separating content, presentation, and behavior so that our site and applications can be used by as many people as possible.

答:
Javascript is a Web standard — certainly more so than, say, Flash, which was previously (and still often is) used for rich Web applications. In this regard, SproutCore and Cappuccino are giant improvements in my book.

The question here really seems to be how important accessibility is. And that is largely a personal decision based, as Andrew said, on knowing your users. For some apps, accessibility really doesn't make that much sense — 280 Slides is a good example of this. It's a graphic design app that's largely about visual behaviors. It doesn't make very much sense for it to degrade to plaintext. (At least, a text-based app meant to accomplish what 280 Slides does would be really be a completely different thing.)

OwnerDisplayName: lark

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Chuck


问:
how can you Given two integers a and b, which can be positive or negative,and find the sum of all the numbers between including them too and return it
function getSum( a , b){
} //so how do you get along this</p>

答:
A for-loop does the sum.

Assuming a < b

let sum = 0,
    a = -3,
    b = 4;

for (let i = a; i <= b; i++) {
  sum += i;
}

console.log(sum);```


问:
Zoom to fit all markers in Mapbox or Leaflet
How do I set view to see all markers on map in Mapbox or Leaflet? Like Google Maps API does with bounds?

E.g:

```<code>var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < latlng.length; i++) {
  latlngbounds.extend(latlng[i]);
}
map.fitBounds(latlngbounds);
</code>```

答:
To fit to the visible markers only, I've this method.</p>

```<code>fitMapBounds() {
    // Get all visible Markers
    const visibleMarkers = [];
    this.map.eachLayer(function (layer) {
        if (layer instanceof L.Marker) {
            visibleMarkers.push(layer);
        }
    });

    // Ensure there's at least one visible Marker
    if (visibleMarkers.length > 0) {

        // Create bounds from first Marker then extend it with the rest
        const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]);
        visibleMarkers.forEach((marker) => {
            markersBounds.extend(marker.getLatLng());
        });

        // Fit the map with the visible markers bounds
        this.map.flyToBounds(markersBounds, {
            padding: L.point(36, 36), animate: true,
        });
    }
}
</code>```

Body:
How do I set view to see all markers on map in Mapbox or Leaflet? Like Google Maps API does with bounds?

E.g:

var latlngbounds = new google.maps.LatLngBounds();
for (var i = 0; i < latlng.length; i++) {
  latlngbounds.extend(latlng[i]);
}
map.fitBounds(latlngbounds);

Body:
To fit to the visible markers only, I've this method.

fitMapBounds() {
    // Get all visible Markers
    const visibleMarkers = [];
    this.map.eachLayer(function (layer) {
        if (layer instanceof L.Marker) {
            visibleMarkers.push(layer);
        }
    });

    // Ensure there's at least one visible Marker
    if (visibleMarkers.length > 0) {

        // Create bounds from first Marker then extend it with the rest
        const markersBounds = L.latLngBounds([visibleMarkers[0].getLatLng()]);
        visibleMarkers.forEach((marker) => {
            markersBounds.extend(marker.getLatLng());
        });

        // Fit the map with the visible markers bounds
        this.map.flyToBounds(markersBounds, {
            padding: L.point(36, 36), animate: true,
        });
    }
}


问:
micropython ds18x20 wrong rom/address/serial
I have  ESP23 dev kit with micropython firmware esp32-idf3-20200329-v1.12-317-g688323307.
I also have ds18b20 waterproof sensor. datasheet link

I wrote this code for it:

```<code>import time, onewire, ds18x20
import machine

from machine import Pin

ds_pin=Pin(19)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))

roms = ds_sensor.scan()

for rom in roms:
    print(rom)
</code>```

It returns tis info:

```<code>[bytearray(b'(\xbcN6\x14\x19\x01\xba')]
</code>```

Before reading temp data from sensor, we first need to use the scan() function to scan for DS18B20 sensors. The addresses found are saved on the roms variable (the roms variable is of type list). scan() function sends request and sensor returns its unique 64-bit serial code.

I used manual here

Today I bought two more ds18x20 waterproof sensors (I don’t know what type of sensor - ds18a20/ds18b20 or else - are they, ‘cause eager chinese manufacturers sealed sensors inside metal bullet too good, so I can’t just look inside).
I tried to run the same code with them, but it returned the following:

```<code>bytearray(b'(\xff\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xfe\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xfc\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xf8\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xf0\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xd0\xff\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xff\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xfe\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xf6\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xe6\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xc6\xff\xff\xff\xff\xff')
bytearray(b'(\x90\x86\xff\xff\xff\xff\xff')
bytearray(b'(\x90\x86\xfd\xff\xff\xff\xff')
bytearray(b'(\x90\x86\xf9\xff\xff\xff\xff')
bytearray(b'(\x90\x86y\xff\xff\xff\xff')
bytearray(b'(\x90\x86y\xfe\xff\xff\xff')
bytearray(b'(\x90\x86y\xfa\xff\xff\xff')
bytearray(b'(\x90\x86y\xf2\xff\xff\xff')
bytearray(b'(\x90\x86y\xe2\xff\xff\xff')
bytearray(b'(\x90\x86y\xa2\xff\xff\xff')
bytearray(b'(\x90\x86y\xa2\xfd\xff\xff')
bytearray(b'(\x90\x86y\xa2\xf9\xff\xff')
bytearray(b'(\x90\x86y\xa2\xf1\xff\xff')
bytearray(b'(\x90\x86y\xa2\xe1\xff\xff')
bytearray(b'(\x90\x86y\xa2\xc1\xff\xff')
bytearray(b'(\x90\x86y\xa2\x81\xff\xff')
bytearray(b'(\x90\x86y\xa2\x01\xff\xff')
bytearray(b'(\x90\x86y\xa2\x01\xfb\xff')
bytearray(b'(\x90\x86y\xa2\x01\xf3\xff')
bytearray(b'(\x90\x86y\xa2\x01\xe3\xff')
bytearray(b'(\x90\x86y\xa2\x01\xc3\xff')
bytearray(b'(\x90\x86y\xa2\x01\x83\xff')
bytearray(b'(\x90\x86y\xa2\x01\x03\xff')
bytearray(b'(\x90\x86y\xa2\x01\x03\xfe')
bytearray(b'(\x90\x86y\xa2\x01\x03\xfc')
bytearray(b'(\x90\x86y\xa2\x01\x03\xdc')
bytearray(b'(\x90\x86y\xa2\x01\x03\\')
</code>```

When I try to read temperature using this values it returns ‘CRC error’.

What can be done? Is the problem with code, or the sensors are failed somehow?

答:
Connect one sensor at a time when you do the scan.

You haven't shared how you're wired the DS18x20 sensor. Make sure its positive power connection is to 3.3V not 5V.

Make sure you've connected a resistor (4.7K should be good) between the data pin of the sensor and 3.3V. OneWire devices absolutely won't work reliably without this resistor - you might see the kind of problem you're seeing.

If you're sure it's wired correctly the next step would be to try it with different firmware, for instance a Dallas one-wire scanner using the Arduino Core. That would eliminate the possibility of problems with the library you're using and MicroPython.

Body:
I have  ESP23 dev kit with micropython firmware esp32-idf3-20200329-v1.12-317-g688323307.
I also have ds18b20 waterproof sensor. datasheet link

I wrote this code for it:

import time, onewire, ds18x20
import machine

from machine import Pin

ds_pin=Pin(19)
ds_sensor = ds18x20.DS18X20(onewire.OneWire(ds_pin))

roms = ds_sensor.scan()

for rom in roms:
    print(rom)

It returns tis info:

[bytearray(b'(\xbcN6\x14\x19\x01\xba')]

Before reading temp data from sensor, we first need to use the scan() function to scan for DS18B20 sensors. The addresses found are saved on the roms variable (the roms variable is of type list). scan() function sends request and sensor returns its unique 64-bit serial code.

I used manual here

Today I bought two more ds18x20 waterproof sensors (I don’t know what type of sensor - ds18a20/ds18b20 or else - are they, ‘cause eager chinese manufacturers sealed sensors inside metal bullet too good, so I can’t just look inside).
I tried to run the same code with them, but it returned the following:

bytearray(b'(\xff\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xfe\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xfc\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xf8\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xf0\xff\xff\xff\xff\xff\xff')
bytearray(b'(\xd0\xff\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xff\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xfe\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xf6\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xe6\xff\xff\xff\xff\xff')
bytearray(b'(\x90\xc6\xff\xff\xff\xff\xff')
bytearray(b'(\x90\x86\xff\xff\xff\xff\xff')
bytearray(b'(\x90\x86\xfd\xff\xff\xff\xff')
bytearray(b'(\x90\x86\xf9\xff\xff\xff\xff')
bytearray(b'(\x90\x86y\xff\xff\xff\xff')
bytearray(b'(\x90\x86y\xfe\xff\xff\xff')
bytearray(b'(\x90\x86y\xfa\xff\xff\xff')
bytearray(b'(\x90\x86y\xf2\xff\xff\xff')
bytearray(b'(\x90\x86y\xe2\xff\xff\xff')
bytearray(b'(\x90\x86y\xa2\xff\xff\xff')
bytearray(b'(\x90\x86y\xa2\xfd\xff\xff')
bytearray(b'(\x90\x86y\xa2\xf9\xff\xff')
bytearray(b'(\x90\x86y\xa2\xf1\xff\xff')
bytearray(b'(\x90\x86y\xa2\xe1\xff\xff')
bytearray(b'(\x90\x86y\xa2\xc1\xff\xff')
bytearray(b'(\x90\x86y\xa2\x81\xff\xff')
bytearray(b'(\x90\x86y\xa2\x01\xff\xff')
bytearray(b'(\x90\x86y\xa2\x01\xfb\xff')
bytearray(b'(\x90\x86y\xa2\x01\xf3\xff')
bytearray(b'(\x90\x86y\xa2\x01\xe3\xff')
bytearray(b'(\x90\x86y\xa2\x01\xc3\xff')
bytearray(b'(\x90\x86y\xa2\x01\x83\xff')
bytearray(b'(\x90\x86y\xa2\x01\x03\xff')
bytearray(b'(\x90\x86y\xa2\x01\x03\xfe')
bytearray(b'(\x90\x86y\xa2\x01\x03\xfc')
bytearray(b'(\x90\x86y\xa2\x01\x03\xdc')
bytearray(b'(\x90\x86y\xa2\x01\x03\\')

When I try to read temperature using this values it returns ‘CRC error’.

What can be done? Is the problem with code, or the sensors are failed somehow?


问:
Firebase get data by timestamp
I need to filter data using to get specific data for the timestamp match.

For example I need the data where arrivalTime matches with exact date and time fields, timestamp field in database.

I am trying below but it returns no data.

```<code>  _arrivalTIme = moment(
            `${todaysDate.format('YYYY/MM/DD')} ${_arrivalTIme}:00`,
          ).toDate();

// _arrivalTIme: Thu May 28 2020 09:00:00 GMT-0600 (Mountain Daylight Time)

return firestore()
  .collection('mainCol')
  .doc(todayDate)
  .collection('subCol')
  .where('arrivalTime', '==', `${_arrivalTIme}`) ...
</code>```

my db record looks like this:

What am I doing wrong?

答:
You're comparing a date field in your database with a string from your code. That comparison will never be true.

You'll either need to get a Timestamp value that is exactly the same as the value in the database, or (more commonly) do a range check:

```<code>return firestore()
  .collection('mainCol')
  .doc(todayDate)
  .collection('subCol')
  .where('arrivalTime', '>=', new Date('2020-05-28 08:00:00')
  .where('arrivalTime', '<', new Date('2020-05-28 08:01:00')
</code>```

Title: Firebase get data by timestamp

Body:
I need to filter data using to get specific data for the timestamp match.

For example I need the data where arrivalTime matches with exact date and time fields, timestamp field in database.

I am trying below but it returns no data.

  _arrivalTIme = moment(
            `${todaysDate.format('YYYY/MM/DD')} ${_arrivalTIme}:00`,
          ).toDate();

// _arrivalTIme: Thu May 28 2020 09:00:00 GMT-0600 (Mountain Daylight Time)

return firestore()
  .collection('mainCol')
  .doc(todayDate)
  .collection('subCol')
  .where('arrivalTime', '==', `${_arrivalTIme}`) ...

my db record looks like this:

What am I doing wrong?

Body:
You're comparing a date field in your database with a string from your code. That comparison will never be true.

You'll either need to get a Timestamp value that is exactly the same as the value in the database, or (more commonly) do a range check:

return firestore()
  .collection('mainCol')
  .doc(todayDate)
  .collection('subCol')
  .where('arrivalTime', '>=', new Date('2020-05-28 08:00:00')
  .where('arrivalTime', '<', new Date('2020-05-28 08:01:00')


问:
laravel echo : "Uncaught ReferenceError: Echo is not defined"
im trying to work laravel echo with pusher , im working on windows localhost (wamp / laravel 5.8)

so i've installed required libs

my package.json

```<code>{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.19",
        "bootstrap": "^4.1.0",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-echo": "^1.8.0",
        "laravel-mix": "^4.0.7",
        "lodash": "^4.17.13",
        "popper.js": "^1.12",
        "pusher-js": "^6.0.3",
        "resolve-url-loader": "^2.3.1",
        "sass": "^1.15.2",
        "sass-loader": "^7.1.0",
        "vue": "^2.5.17",
        "vue-template-compiler": "^2.6.11"
    }
}
</code>```

resources/js/app.js

```<code>require('./bootstrap');

window.Vue = require('vue');
</code>```

resources/js/bootstrap.js

```<code>window._ = require('lodash');
try {
    window.Popper = require('popper.js').default;
    window.$ = window.jQuery = require('jquery');

    require('bootstrap');
} catch (e) {}

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
import Echo from 'laravel-echo';
window.xxx = 'xxx';
window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    encrypted: true
});
</code>```

i ran

```<code>npm run dev
</code>```

here is the result

in my view i have

```<code><!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>
        <meta name="csrf-token" content="{{ csrf_token() }}">
        <script src="{{ asset('js/app.js') }}" defer></script>
        <link href="{{ asset('css/app.css') }}" rel="stylesheet">
    </head>
    <body>

    <script>
        console.log(Echo);
    </script>

    </body>
</html>
</code>```

i keep getting

```<code>Uncaught ReferenceError: Echo is not defined
</code>```

i even added

```<code>window.xxx = 'xxx';
</code>```

in bootstrap.js to see if i can eccess xxx variable in my view but thats undefined as well (btw im not sure if thats how it works !!  just trying some stuff )

any idea ?

my folders structure is like

```<code>/pusher (root folder)
  +app
  +vendor
  +node_modules
  +resources/js
  -public
    index.php
    css/app.css
    js/app.js
</code>```

答: Try removing defer from the

Body:
im trying to work laravel echo with pusher , im working on windows localhost (wamp / laravel 5.8)

so i've installed required libs

my package.json

{
    "private": true,
    "scripts": {
        "dev": "npm run development",
        "development": "cross-env NODE_ENV=development node_modules/webpack/bin/webpack.js --progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js",
        "watch": "npm run development -- --watch",
        "watch-poll": "npm run watch -- --watch-poll",
        "hot": "cross-env NODE_ENV=development node_modules/webpack-dev-server/bin/webpack-dev-server.js --inline --hot --config=node_modules/laravel-mix/setup/webpack.config.js",
        "prod": "npm run production",
        "production": "cross-env NODE_ENV=production node_modules/webpack/bin/webpack.js --no-progress --hide-modules --config=node_modules/laravel-mix/setup/webpack.config.js"
    },
    "devDependencies": {
        "axios": "^0.19",
        "bootstrap": "^4.1.0",
        "cross-env": "^5.1",
        "jquery": "^3.2",
        "laravel-echo": "^1.8.0",
        "laravel-mix": "^4.0.7",
        "lodash": "^4.17.13",
        "popper.js": "^1.12",
        "pusher-js": "^6.0.3",
        "resolve-url-loader": "^2.3.1",
        "sass": "^1.15.2",
        "sass-loader": "^7.1.0",
        "vue": "^2.5.17",
        "vue-template-compiler": "^2.6.11"
    }
}

resources/js/app.js

require('./bootstrap');

window.Vue = require('vue');

resources/js/bootstrap.js

window._ = require('lodash');
try {
    window.Popper = require('popper.js').default;
    window.$ = window.jQuery = require('jquery');

    require('bootstrap');
} catch (e) {}

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
import Echo from 'laravel-echo';
window.xxx = 'xxx';
window.Pusher = require('pusher-js');

window.Echo = new Echo({
    broadcaster: 'pusher',
    key: process.env.MIX_PUSHER_APP_KEY,
    cluster: process.env.MIX_PUSHER_APP_CLUSTER,
    encrypted: true
});

i ran

npm run dev

here is the result

in my view i have

<!DOCTYPE html>
getLocale()) }}">

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>Laravel</title>
        <meta name="csrf-token" content="{{ csrf_token() }}">

        <link href="{{ asset('css/app.css') }}" rel="stylesheet">

i keep getting

Uncaught ReferenceError: Echo is not defined

i even added

window.xxx = 'xxx';

in bootstrap.js to see if i can eccess xxx variable in my view but thats undefined as well (btw im not sure if thats how it works !!  just trying some stuff )

any idea ?

my folders structure is like

/pusher (root folder)
  +app
  +vendor
  +node_modules
  +resources/js
  -public
    index.php
    css/app.css
    js/app.js

Body: Try removing defer from the <script .. portion.


问:
Apply styles from base components to all components who inherit from it
So I have build a general button component in Angular:

```<code>import { Component, Output, EventEmitter, Input } from '@angular/core';

@Component({
  selector: 'app-general-button',
  templateUrl: './general-button.component.html',
  styleUrls: ['./general-button.component.scss']
})
export class GeneralButtonComponent  {

  @Input() public buttonTitle: string;
  @Input() public disabledButton = false;
  @Input() public fullWidth = false;
  @Input() public tooltipMessage: string;
  @Output() public buttonClick =  new EventEmitter();

  constructor() {

  }

  public buttonClicked(): void {
    this.buttonClick.emit();
  }

}
</code>```

And I also have a cancel button that extends from that component:

```<code>import { Component } from '@angular/core';
import { GeneralButtonComponent } from '../general-button/general-button.component';

@Component({
  selector: 'app-cancel-button',
  templateUrl: '../general-button/general-button.component.html',
  styleUrls: ['./cancel-button.component.scss']
})
export class CancelButtonComponent extends GeneralButtonComponent {

  constructor() {
    super();
  }

}
</code>```

In my global styles I have a styled the general button component to be hidden when and visible when I hover on the row it's on:

```<code>nb-accordion app-general-button,
table app-general-button {
  visibility: hidden;
}

nb-accordion nb-accordion-item:hover app-general-button,
table tr:hover app-general-button {
  visibility: visible;
}
</code>```

However this style does not seem to apply to the cancel button component. Is there a way to tell angular to apply the styles from a base component to all of the components that extend from it?

答: You might have to add the parent component's CSS file along with the styleUrls in the child component. Or would have to turn ViewEncapsulation to none (which is generally not suggested)</p>

Body:
So I have build a general button component in Angular:

import { Component, Output, EventEmitter, Input } from '@angular/core';

@Component({
  selector: 'app-general-button',
  templateUrl: './general-button.component.html',
  styleUrls: ['./general-button.component.scss']
})
export class GeneralButtonComponent  {

  @Input() public buttonTitle: string;
  @Input() public disabledButton = false;
  @Input() public fullWidth = false;
  @Input() public tooltipMessage: string;
  @Output() public buttonClick =  new EventEmitter();

  constructor() {

  }

  public buttonClicked(): void {
    this.buttonClick.emit();
  }

}

And I also have a cancel button that extends from that component:

import { Component } from '@angular/core';
import { GeneralButtonComponent } from '../general-button/general-button.component';

@Component({
  selector: 'app-cancel-button',
  templateUrl: '../general-button/general-button.component.html',
  styleUrls: ['./cancel-button.component.scss']
})
export class CancelButtonComponent extends GeneralButtonComponent {

  constructor() {
    super();
  }

}

In my global styles I have a styled the general button component to be hidden when and visible when I hover on the row it's on:

nb-accordion app-general-button,
table app-general-button {
  visibility: hidden;
}

nb-accordion nb-accordion-item:hover app-general-button,
table tr:hover app-general-button {
  visibility: visible;
}

However this style does not seem to apply to the cancel button component. Is there a way to tell angular to apply the styles from a base component to all of the components that extend from it?


问:
Nginx proxy_pass cannot load asset VueJS
I have 3 website and running on docker port 8000, 8001, and 8002.

I'm configuring nginx with this config:

```<code>server {
server_name my.domain.net;

location / {
  proxy_pass              http://localhost:8000;
  proxy_set_header        Host $host;
  proxy_set_header        X-Real-IP $remote_addr;
  proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header        X-Forwarded-Proto $scheme;
}

location /old {
    proxy_pass            http://127.0.0.1:8001;
    proxy_set_header      Host $host;
    proxy_set_header      X-Real-IP $remote_addr;
    proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header      X-Forwarded-Proto $scheme;
}

location /new {
    proxy_pass            http://127.0.0.1:8002;
    proxy_set_header      Host $host;
    proxy_set_header      X-Real-IP $remote_addr;
    proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header      X-Forwarded-Proto $scheme;
}
}
</code>```

It works for location /, but for location /old and /new without all assets. I inspect element, for location /old the assets redirect to http://my.domain.net (absolutely 404 not found), where it should be http://my.domain.net/old/asset.css.

Need advice

Please help.

答:
In your new and old applications hosted at 8081 and 8082 respectively, add assetsDir in your configuration.

vue.config.js:

```<code>module.exports = {
  assetsDir: 'new'
}
</code>```

Body:
I have 3 website and running on docker port 8000, 8001, and 8002.

I'm configuring nginx with this config:

server {
server_name my.domain.net;

location / {
  proxy_pass              http://localhost:8000;
  proxy_set_header        Host $host;
  proxy_set_header        X-Real-IP $remote_addr;
  proxy_set_header        X-Forwarded-For $proxy_add_x_forwarded_for;
  proxy_set_header        X-Forwarded-Proto $scheme;
}

location /old {
    proxy_pass            http://127.0.0.1:8001;
    proxy_set_header      Host $host;
    proxy_set_header      X-Real-IP $remote_addr;
    proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header      X-Forwarded-Proto $scheme;
}

location /new {
    proxy_pass            http://127.0.0.1:8002;
    proxy_set_header      Host $host;
    proxy_set_header      X-Real-IP $remote_addr;
    proxy_set_header      X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header      X-Forwarded-Proto $scheme;
}
}

It works for location /, but for location /old and /new without all assets. I inspect element, for location /old the assets redirect to http://my.domain.net (absolutely 404 not found), where it should be http://my.domain.net/old/asset.css.

Need advice

Please help.

Body:
In your new and old applications hosted at 8081 and 8082 respectively, add assetsDir in your configuration.

vue.config.js:

module.exports = {
  assetsDir: 'new'
}


问:
AppFabric: Xml or SQL Server?
I’m setting up AppFabric and I’m wondering if using xml (instead of SQL Express) for the “Caching Service Configuration Provider” has any impact on performance or may lead to other problems eventually? To keep dependencies (and things that can go wrong) to a minimum, using a plain xml file seems like a simpler solution.</p>

答:
XML is fine in non-HA scenarios; make sure the share is available to all account contexts on all hosts and you're good to go. Performance is a non-issue -- configuration is only checked/utilized at certain times, like startup, or adding/removing a host. SQL Server configuration is really targeted at higher availability (though itself is subject to crashing the service when SQL Server becomes unavailable, sillily enough.)

Incidentally, disk filestore will almost always be faster than DB access for this sort of work.

Title: AppFabric: Xml or SQL Server?


问:
Vue Remove duplicates from an array of string
I am using [...new Map] on date which should pass an unique values of date only. But console.log(uniqueObjects); does not print out unique date values. There is something that I am doing wrong at [...new Map(date.map(item => [item.date, item])).values()]; which is not passing the unique date values. Is there a way to print unique date value using class='filter'?

SCRIPT

```<code>new Vue({
  el: "#app",
  data: {
    todos: [
      { id:"1", date:"2020-05-28T18:30:00.000Z", peopleName: "David" },
      { id:"2", date:"2020-05-28T18:30:00.000Z", peopleName: "Jack" },
      { id:"3", date:"2020-05-28T20:00:00.000Z", peopleName: "John" },
      { id:"4", date:"2020-05-28T20:00:00.000Z", peopleName: "Thomas" },
      { id:"5", date:"2020-05-28T20:00:00.000Z", peopleName: "Will" },
      { id:"6", date:"2020-05-28T21:30:00.000Z", peopleName: "Hary" },
    ]
  },
  computed:{
    filter: {
    moment: function (date) {
        console.log("its not printing");

        /** return moment(date).format('h:mm A') **/

        console.log(date);

        const uniqueObjects = [...new Map(date.map(item => [item.date, item])).values()];

       /** i am using new Map to remove the same value for date but it's not working **/

       console.log(uniqueObjects);
    }
  }
 },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  }
})
</code>```

VIEW

```<code><div id="app">
  <div v-for="reservation in todos" v-bind:key="reservation.id">
     <p class="filter">{{ reservation.date | moment }}</p>
     <p>{{reservation.peopleName}}</p>
  </div>
</div>
</code>```

Below is the link for the code on jsfidddle

https://jsfiddle.net/ujjumaki/ro5p4kxt/21/

答:
Does it now work right? If you write v-for="reservation in filter" that show you filtered values, if v-for="reservation in todos" - all values.

new Vue({
  el: "#app",
  data: {
    todos: [
      { id:"1", date:"2020-05-28T18:30:00.000Z", peopleName: "David" },
      { id:"2", date:"2020-05-28T18:30:00.000Z", peopleName: "Jack" },
      { id:"3", date:"2020-05-28T20:00:00.000Z", peopleName: "John" },
      { id:"4", date:"2020-05-28T20:00:00.000Z", peopleName: "Thomas" },
      { id:"5", date:"2020-05-28T20:00:00.000Z", peopleName: "Will" },
      { id:"6", date:"2020-05-28T21:30:00.000Z", peopleName: "Hary" },
    ]
  },
  computed:{
   filter()  {
      return [...new Map(this.todos.map(item => [item.date, item])).values()];
  }
 }
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="reservation in filter" v-bind:key="reservation.id">
     <p>{{reservation.date}}</p>
     <p>{{reservation.peopleName}}</p>
  </div>
</div></code>```

Body:
I am using [...new Map] on date which should pass an unique values of date only. But console.log(uniqueObjects); does not print out unique date values. There is something that I am doing wrong at [...new Map(date.map(item => [item.date, item])).values()]; which is not passing the unique date values. Is there a way to print unique date value using class='filter'?

SCRIPT

new Vue({
  el: "#app",
  data: {
    todos: [
      { id:"1", date:"2020-05-28T18:30:00.000Z", peopleName: "David" },
      { id:"2", date:"2020-05-28T18:30:00.000Z", peopleName: "Jack" },
      { id:"3", date:"2020-05-28T20:00:00.000Z", peopleName: "John" },
      { id:"4", date:"2020-05-28T20:00:00.000Z", peopleName: "Thomas" },
      { id:"5", date:"2020-05-28T20:00:00.000Z", peopleName: "Will" },
      { id:"6", date:"2020-05-28T21:30:00.000Z", peopleName: "Hary" },
    ]
  },
  computed:{
    filter: {
    moment: function (date) {
        console.log("its not printing");

        /** return moment(date).format('h:mm A') **/

        console.log(date);

        const uniqueObjects = [...new Map(date.map(item => [item.date, item])).values()];

       /** i am using new Map to remove the same value for date but it's not working **/

       console.log(uniqueObjects);
    }
  }
 },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  }
})

VIEW

{{ reservation.date | moment }}

{{reservation.peopleName}}

Below is the link for the code on jsfidddle

https://jsfiddle.net/ujjumaki/ro5p4kxt/21/

Body:
Does it now work right? If you write v-for="reservation in filter" that show you filtered values, if v-for="reservation in todos" - all values.

new Vue({
  el: "#app",
  data: {
    todos: [
      { id:"1", date:"2020-05-28T18:30:00.000Z", peopleName: "David" },
      { id:"2", date:"2020-05-28T18:30:00.000Z", peopleName: "Jack" },
      { id:"3", date:"2020-05-28T20:00:00.000Z", peopleName: "John" },
      { id:"4", date:"2020-05-28T20:00:00.000Z", peopleName: "Thomas" },
      { id:"5", date:"2020-05-28T20:00:00.000Z", peopleName: "Will" },
      { id:"6", date:"2020-05-28T21:30:00.000Z", peopleName: "Hary" },
    ]
  },
  computed:{
   filter()  {
      return [...new Map(this.todos.map(item => [item.date, item])).values()];
  }
 }
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<div id="app">
  <div v-for="reservation in filter" v-bind:key="reservation.id">
     <p>{{reservation.date}}</p>
     <p>{{reservation.peopleName}}</p>
  </div>
</div>


答:
The idea is to create a loop between a and b and add all of them in a 3rd variable.

But first, you need to determine what is the start and the end of the loop, I create a min, max var for that depending if a > b or not and loop from min to max:

function getSum(a, b) {
  const min = a < b ? a : b;
  const max = a < b ? b : a;

  let sum = 0;
  for(let i = min; i <= max; i++) {
    sum += i;
  }
  return sum;
}
```

Title: how can you Given two integers a and b, which can be positive or negative,and find the sum of all the numbers between including them too and return it

Body:
function getSum( a , b){
} //so how do you get along this


答: Just start a loop from the lowest number till the highest number. Keep on adding all the numbers and return the sum.</p>


问:
Localized currency symbol from NumberFormatter
how to set NumberFormatter to return currency symbol not the iso one but local which is visible in iOS locale settings pane. Like for Polish currency I need to have “zł” symbol not the “PLN”.

I cannot find any way to get it from system as this cannot be hardcoded. IAP localized price also uses “zł” not “PLN”

I tried this way:

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencySymbol = Locale.current.currencySymbol
formatter.maximumFractionDigits = 2

let price = formatter.string(from: (offeringPrice / 12) as NSNumber) ?? ""
```

but whatever I try to use as currency symbol I always get in return "PLN"

答:
I've found this solution

    func getCurrencySymbol(from currencyCode: String) -> String? {
        let locale = NSLocale(localeIdentifier: currencyCode)
        if locale.displayName(forKey: .currencySymbol, value: currencyCode) == currencyCode {
            let newlocale = NSLocale(localeIdentifier: currencyCode.dropLast() + "_en")
            return newlocale.displayName(forKey: .currencySymbol, value: currencyCode)
        }
        return locale.displayName(forKey: .currencySymbol, value: currencyCode)
    }
```

original answer here: https://stackoverflow.com/a/49146857/1285959

Body:
how to set NumberFormatter to return currency symbol not the iso one but local which is visible in iOS locale settings pane. Like for Polish currency I need to have “zł” symbol not the “PLN”.

I cannot find any way to get it from system as this cannot be hardcoded. IAP localized price also uses “zł” not “PLN”

I tried this way:

let formatter = NumberFormatter()
formatter.numberStyle = .currency
formatter.currencySymbol = Locale.current.currencySymbol
formatter.maximumFractionDigits = 2

let price = formatter.string(from: (offeringPrice / 12) as NSNumber) ?? ""

but whatever I try to use as currency symbol I always get in return "PLN"

Body:
I've found this solution

    func getCurrencySymbol(from currencyCode: String) -> String? {
        let locale = NSLocale(localeIdentifier: currencyCode)
        if locale.displayName(forKey: .currencySymbol, value: currencyCode) == currencyCode {
            let newlocale = NSLocale(localeIdentifier: currencyCode.dropLast() + "_en")
            return newlocale.displayName(forKey: .currencySymbol, value: currencyCode)
        }
        return locale.displayName(forKey: .currencySymbol, value: currencyCode)
    }

original answer here: https://stackoverflow.com/a/49146857/1285959