问:
Set authorization header param in interceptor.module.ts
I need to send an authorization token into every request's header and I can't find a proper way to set params into intercepetor.module.ts code.

Here's an extract from my Angular interceptor.module.ts

```<code>intercept(
        req: HttpRequest<any>,
        next: HttpHandler,
    ): Observable<HttpEvent<any>> {

        console.warn("Loader Started - HTTP request: " + req.url);

        let dupReq = req.clone({
            setHeaders:{
                'Content-Type' : 'application/json',
                'Accept'       : 'application/json',
                'Authorization': "Basic "+ myToken
            }
        });

        return next.handle(dupReq).pipe(
            map(event => {
                return event;
            }),
            catchError(error => {
                return Observable.throw(error);
            }),
            finalize(() => {

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

When I go into Chrome's Network tab in debug mode, request's header had no change and it is not showing the 'authorization' param.

I've tried to set the headers thru headers.append() method and it had no difference as well.

答:
You can try this, since you want Basic authorization:

```<code>const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + btoa(myToken)
    })
};
</code>```

Body:
I need to send an authorization token into every request's header and I can't find a proper way to set params into intercepetor.module.ts code.

Here's an extract from my Angular interceptor.module.ts

intercept(
        req: HttpRequest<any>,
        next: HttpHandler,
    ): Observable<HttpEvent<any>> {

        console.warn("Loader Started - HTTP request: " + req.url);

        let dupReq = req.clone({
            setHeaders:{
                'Content-Type' : 'application/json',
                'Accept'       : 'application/json',
                'Authorization': "Basic "+ myToken
            }
        });

        return next.handle(dupReq).pipe(
            map(event => {
                return event;
            }),
            catchError(error => {
                return Observable.throw(error);
            }),
            finalize(() => {

            })
        );
    }

When I go into Chrome's Network tab in debug mode, request's header had no change and it is not showing the 'authorization' param.

I've tried to set the headers thru headers.append() method and it had no difference as well.

Body:
You can try this, since you want Basic authorization:

const httpOptions = {
    headers: new HttpHeaders({
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + btoa(myToken)
    })
};


来源: stackexchange

问:
Real World Haskell book - asymptotic complexity of Logger monad example
I just reached Chapter 14 of Real World Haskell and was wondering about this yesterday.

In the Logger monad example, the bind function is implemented as follows:

```<code>-- (>>=) :: Logger a -> (a -> Logger b) -> Logger b
    m >>= k = let (a, w) = execLogger m
                  n      = k a
                  (b, x) = execLogger n
              in Logger (b, w ++ x)
</code>```

where the 2nd element in the injector function contains our log messages, which are continuously being appended using ++. (Read online around here for more context.)

My question is.. wouldn't that make the runtime complexity using this Logger quadratic to the number of messages?

If I'm wrong, please help provide the correct analysis and big oh notation.

If I'm right, I'm hoping people who have more experience/insights with Haskell and the book can tell me some reasons of choosing that implementation, and why it is ok.
In the previous chapter of the book there's a section that says this way of appending of list is bad, and teaches us the difference list technique. Why is this not being used here?

BTW I love the book, it's going to be a book I'll read cover to cover since a long long time.

答:
Depending on the associativity of the computation, yes, that will have quadratic complexity. For example, if your computation associates to the right:

```<code>log 0 >> (log 1 >> (log 2 >> log 3))
</code>```

then the complexity is linear.  However, if it associates to the left:

```<code>((log 0 >> log 1) >> log 2) >> log 3
</code>```

then the complexity is quadratic.  It is just "forwarding" to the properties of the underlying monoid, here [],(++).

I imagine the reason for stating it this way is for simplicity.  While it may not be efficient, it is completely obvious what is going on. However, as others have answered, this is just the Writer monad over the list monoid.  You can get Writer by replacing [] with mempty and ++ with `mappend`, and then you can instantiate it with [] or DList or whatever you want.  So using the concrete forms is not all that much clearer, IMO.

ContentLicense: CC BY-SA 3.0

Body:
I just reached Chapter 14 of Real World Haskell and was wondering about this yesterday.

In the Logger monad example, the bind function is implemented as follows:

-- (>>=) :: Logger a -> (a -> Logger b) -> Logger b
    m >>= k = let (a, w) = execLogger m
                  n      = k a
                  (b, x) = execLogger n
              in Logger (b, w ++ x)

where the 2nd element in the injector function contains our log messages, which are continuously being appended using ++. (Read online around here for more context.)

My question is.. wouldn't that make the runtime complexity using this Logger quadratic to the number of messages?

If I'm wrong, please help provide the correct analysis and big oh notation.

If I'm right, I'm hoping people who have more experience/insights with Haskell and the book can tell me some reasons of choosing that implementation, and why it is ok.
In the previous chapter of the book there's a section that says this way of appending of list is bad, and teaches us the difference list technique. Why is this not being used here?

BTW I love the book, it's going to be a book I'll read cover to cover since a long long time.

Body:
Depending on the associativity of the computation, yes, that will have quadratic complexity. For example, if your computation associates to the right:

log 0 >> (log 1 >> (log 2 >> log 3))

then the complexity is linear.  However, if it associates to the left:

((log 0 >> log 1) >> log 2) >> log 3

then the complexity is quadratic.  It is just "forwarding" to the properties of the underlying monoid, here [],(++).

I imagine the reason for stating it this way is for simplicity.  While it may not be efficient, it is completely obvious what is going on. However, as others have answered, this is just the Writer monad over the list monoid.  You can get Writer by replacing [] with mempty and ++ with `mappend`, and then you can instantiate it with [] or DList or whatever you want.  So using the concrete forms is not all that much clearer, IMO.


问:
Using "main" for story board fails because View controller isn't the main story board
I embedded a page view controller into a container view. The View controller containing the Container view isn't the main View controller so my program crashes.

```<code>import UIKit

class CarsSwipe: UIPageViewController,  UIPageViewControllerDataSource, UIPageViewControllerDelegate {

  lazy var viewControllersList:[UIViewController] = {
    let sb = UIStoryboard(name: "main", bundle: nil).instantiateViewController(withIdentifier: "carsSwipe")

    let vc1 = sb.instantiateViewController(withIdentifier: "blueView")
    let vc2 = sb.instantiateViewController(withIdentifier: "orangeView")
    let vc3 = sb.instantiateViewController(withIdentifier: "blackView")
    return [vc1, vc2, vc3]
   }()

  func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {

    guard let vcIndex = viewControllersList.firstIndex(of:  viewController) else {return nil}

    let previousIndex = vcIndex - 1
    guard previousIndex >= 0 else {return nil}
    guard viewControllersList.count > previousIndex  else {return  nil}

    return viewControllersList[previousIndex]
   }

  func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
    guard let vcIndex = viewControllersList.firstIndex(of: viewController) else {return nil}
    let nextIndex = vcIndex + 1
    guard viewControllersList.count != nextIndex else {return nil}
    guard viewControllersList.count > nextIndex  else {return nil}
    return viewControllersList[nextIndex]
  }

  override func viewDidLoad() {
    super.viewDidLoad()

    self.delegate = self
    self.dataSource = self

    if let firsViewControlller = viewControllersList.first {
      self.setViewControllers([firsViewControlller], direction: .forward, animated: true, completion: nil)
    }
  }

}
</code>```

I want the PageViewController to scroll in the container inside the View controller

答:
the error is in this line:

```<code>let sb = UIStoryboard(name: "main", bundle: nil).instantiateViewController(withIdentifier: "carsSwipe")
</code>```

remove  .instantiateViewController(withIdentifier: "carsSwipe") and should compile successfully.

Cause sb in the code below isn't a UIStoryboard but a viewcontroller:

```<code>let vc1 = sb.instantiateViewController(withIdentifier: "blueView")
let vc2 = sb.instantiateViewController(withIdentifier: "orangeView")
let vc3 = sb.instantiateViewController(withIdentifier: "blackView")
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I embedded a page view controller into a container view. The View controller containing the Container view isn't the main View controller so my program crashes.

import UIKit

class CarsSwipe: UIPageViewController,  UIPageViewControllerDataSource, UIPageViewControllerDelegate {

  lazy var viewControllersList:[UIViewController] = {
    let sb = UIStoryboard(name: "main", bundle: nil).instantiateViewController(withIdentifier: "carsSwipe")

    let vc1 = sb.instantiateViewController(withIdentifier: "blueView")
    let vc2 = sb.instantiateViewController(withIdentifier: "orangeView")
    let vc3 = sb.instantiateViewController(withIdentifier: "blackView")
    return [vc1, vc2, vc3]
   }()

  func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? {

    guard let vcIndex = viewControllersList.firstIndex(of:  viewController) else {return nil}

    let previousIndex = vcIndex - 1
    guard previousIndex >= 0 else {return nil}
    guard viewControllersList.count > previousIndex  else {return  nil}

    return viewControllersList[previousIndex]
   }

  func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? {
    guard let vcIndex = viewControllersList.firstIndex(of: viewController) else {return nil}
    let nextIndex = vcIndex + 1
    guard viewControllersList.count != nextIndex else {return nil}
    guard viewControllersList.count > nextIndex  else {return nil}
    return viewControllersList[nextIndex]
  }

  override func viewDidLoad() {
    super.viewDidLoad()

    self.delegate = self
    self.dataSource = self

    if let firsViewControlller = viewControllersList.first {
      self.setViewControllers([firsViewControlller], direction: .forward, animated: true, completion: nil)
    }
  }

}

I want the PageViewController to scroll in the container inside the View controller

Body:
the error is in this line:

let sb = UIStoryboard(name: "main", bundle: nil).instantiateViewController(withIdentifier: "carsSwipe")

remove  .instantiateViewController(withIdentifier: "carsSwipe") and should compile successfully.

Cause sb in the code below isn't a UIStoryboard but a viewcontroller:

let vc1 = sb.instantiateViewController(withIdentifier: "blueView")
let vc2 = sb.instantiateViewController(withIdentifier: "orangeView")
let vc3 = sb.instantiateViewController(withIdentifier: "blackView")


问:
How to scale up/down all resources in a Azure subscription using Azure DevOps pipelines?
We would need to scale up multiple resources hosted in a Azure subscription on need basis and scale them down later. Do we need to go the ARM way or the Powershell/Azure CLI way? We are using Azure DevOps for CI/CD and any insights into this would be greatly helpful.</p>

答:
IMHO, ARM would be prioritized fit for your requirement because it fits in the requirements like deploy, manage, monitor many of the resources for a solution as a group rather than handling multiple resources individually. For more information with regards to this, I would suggest you to read through all the comments and conversation that has happened in this Stack Overflow thread which includes this and this tutorial references that confirms the same that ARM is the prioritized fit for requirement like yours.

Hope this helps!! Cheers!!


答:
Try this:</p>

```<code>const dupReq = req.clone({
    setHeaders: {
      Authorization: "Basic "+ btoa(myToken),
      'Access-Control-Allow-Origin': '*'
    },
  })
</code>```

Title: Set authorization header param in interceptor.module.ts

Body:
Try this:

const dupReq = req.clone({
    setHeaders: {
      Authorization: "Basic "+ btoa(myToken),
      'Access-Control-Allow-Origin': '*'
    },
  })


问:
hibernate + spring boot store date on UTC time zone troubles
I'm making some tests to define UTC as default time zone for my application. First of all I want my datetime values to be stored with the UTC one.

According to VLAD MIHALCEA (https://vladmihalcea.com/how-to-store-date-time-and-timestamps-in-utc-time-zone-with-jdbc-and-hibernate/) and https://moelholm.com/2016/11/09/spring-boot-controlling-timezones-with-hibernate/ I have set in my properties file:

```<code>spring.jpa.properties.hibernate.jdbc.time_zone= UTC
</code>```

For testing I'm using h2 database, I've created a sample entity with all java 8 dateTime Type.

In my liquibase config they are defined like this:

```<code><column name="instant" type="timestamp"/>
<column name="local_date" type="date"/>
<column name="local_time" type="time"/>
<column name="offset_time" type="time"/>
<column name="local_date_time" type="timestamp"/>
<column name="offset_date_time" type="timestamp"/>
<column name="zoned_date_time" type="timestamp"/>
</code>```

I think I'm using the good type for every fields. It's work for all fields except for "local_time" "offset_time" which are Time sql types not timestamp.

As you can see i added this row at 8:39am (Paris GMT+2) and timestamps have the good UTC value (6:38am).
BUT both "local_time" and "offset_time" have a strange value (7:39am).

I wonder why this behaviour, if some of you have an idea why my two time fields not store values correctly.

PS: version:

Hibernate: 5.2.17.Final

Spring boot: 2.0.4.RELEASE

My sample Entity use to insert data :

```<code>import javax.persistence.*;
import java.io.Serializable;
import java.time.*;
import java.util.Objects;

@Entity
@Table(name = "avdev_myData")
public class MyData implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "instant")
    private Instant instant;

    @Column(name = "local_date")
    private LocalDate localDate;

    @Column(name = "local_time")
    private LocalTime localTime;

    @Column(name = "offset_time")
    private OffsetTime offsetTime;

    @Column(name = "local_date_time")
    private LocalDateTime localDateTime;

    @Column(name = "offset_date_time")
    private OffsetDateTime offsetDateTime;

    @Column(name = "zoned_date_time")
    private ZonedDateTime zonedDateTime;
</code>```

答:
Once the spring context is initialized ....

```<code>import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class ApplicationStartUp {

    @EventListener(ContextRefreshedEvent.class)
    public void contextRefreshedEvent() {

        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

    }

}
</code>```

OR

```<code>@Component
public class InitializingContextBean implements InitializingBean {

    private static final Logger LOG  = Logger.getLogger(InitializingContextBean.class);

    @Autowired
    private Environment environment;

    @Override
    public void afterPropertiesSet() throws Exception {
            TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    }
}
</code>```

Body:
I'm making some tests to define UTC as default time zone for my application. First of all I want my datetime values to be stored with the UTC one.

According to VLAD MIHALCEA (https://vladmihalcea.com/how-to-store-date-time-and-timestamps-in-utc-time-zone-with-jdbc-and-hibernate/) and https://moelholm.com/2016/11/09/spring-boot-controlling-timezones-with-hibernate/ I have set in my properties file:

spring.jpa.properties.hibernate.jdbc.time_zone= UTC

For testing I'm using h2 database, I've created a sample entity with all java 8 dateTime Type.

In my liquibase config they are defined like this:

<column name="instant" type="timestamp"/>
<column name="local_date" type="date"/>
<column name="local_time" type="time"/>
<column name="offset_time" type="time"/>
<column name="local_date_time" type="timestamp"/>
<column name="offset_date_time" type="timestamp"/>
<column name="zoned_date_time" type="timestamp"/>

I think I'm using the good type for every fields. It's work for all fields except for "local_time" "offset_time" which are Time sql types not timestamp.

As you can see i added this row at 8:39am (Paris GMT+2) and timestamps have the good UTC value (6:38am).
BUT both "local_time" and "offset_time" have a strange value (7:39am).

I wonder why this behaviour, if some of you have an idea why my two time fields not store values correctly.

PS: version:

Hibernate: 5.2.17.Final

Spring boot: 2.0.4.RELEASE

My sample Entity use to insert data :

import javax.persistence.*;
import java.io.Serializable;
import java.time.*;
import java.util.Objects;

@Entity
@Table(name = "avdev_myData")
public class MyData implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
    @SequenceGenerator(name = "sequenceGenerator")
    private Long id;

    @Column(name = "name")
    private String name;

    @Column(name = "instant")
    private Instant instant;

    @Column(name = "local_date")
    private LocalDate localDate;

    @Column(name = "local_time")
    private LocalTime localTime;

    @Column(name = "offset_time")
    private OffsetTime offsetTime;

    @Column(name = "local_date_time")
    private LocalDateTime localDateTime;

    @Column(name = "offset_date_time")
    private OffsetDateTime offsetDateTime;

    @Column(name = "zoned_date_time")
    private ZonedDateTime zonedDateTime;

Body:
Once the spring context is initialized ....

import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
public class ApplicationStartUp {

    @EventListener(ContextRefreshedEvent.class)
    public void contextRefreshedEvent() {

        TimeZone.setDefault(TimeZone.getTimeZone("UTC"));

    }

}

OR

@Component
public class InitializingContextBean implements InitializingBean {

    private static final Logger LOG  = Logger.getLogger(InitializingContextBean.class);

    @Autowired
    private Environment environment;

    @Override
    public void afterPropertiesSet() throws Exception {
            TimeZone.setDefault(TimeZone.getTimeZone("UTC"));
    }
}


问:
CRUd issues with Jhipster relationships
I am importing the following jdl to generate a simple jhipster monolith.

I inspected the h2 db after startup and it seems perfect, however when i try to use the ui to create new InventryModel or Inventory entities, the drop downs are not working at all.

It seems when I added the {required} (to enforce non null fks) that this is where it started to go downhill

```<code>  config {
    baseName hipcars
    packageName com.hipcars
    applicationType monolith
    databaseType sql
    devDatabaseType h2Disk
    prodDatabaseType mysql
    cacheProvider ehcache
    enableHibernateCache true
    authenticationType jwt
    clientFramework angularX
    useSass false
    clientPackageManager npm
    enableTranslation false
    languages [ en, zh-cn, es ]
    messageBroker kafka
    searchEngine elasticsearch
    serverPort 8080
    websocket false
    testFrameworks [protractor, cucumber, gatling]
    buildTool gradle
  }
  entities *
}

entity Make {
  name String required unique maxlength(20),
  desc String
}

entity InventoryModel {
  name String required unique maxlength(20),
  vehicleType VehicleType
  desc String
}

enum VehicleType {
  SEDAN,
  COUPE
}

entity Inventory {
    vin String required unique maxlength(17),
  comment   String maxlength(128)
}

relationship ManyToOne {
  InventoryModel{make(name) required} to Make,
  Inventory{inventoryModel(name) required} to InventoryModel
}

dto * with mapstruct

paginate * with pagination
service * with serviceClass
search * with elasticsearch
filter *
</code>```

if I however do this:

```<code>application {
  config {
    baseName hipcars
    packageName com.hipcars
    applicationType monolith
    databaseType sql
    devDatabaseType h2Disk
    prodDatabaseType mysql
    cacheProvider ehcache
    enableHibernateCache true
    authenticationType jwt
    clientFramework angularX
    useSass false
    clientPackageManager npm
    enableTranslation false
    languages [ en, zh-cn, es ]
    messageBroker kafka
    searchEngine elasticsearch
    serverPort 8080
    websocket false
    testFrameworks [protractor, cucumber, gatling]
    buildTool gradle
  }
  entities *
}

entity Make {
  name String required unique maxlength(20),
  desc String
}

entity InventoryModel {
  name String required unique maxlength(20),
  vehicleType VehicleType
  desc String
}

enum VehicleType {
  SEDAN,
  COUPE
}

entity Inventory {
    vin String required unique maxlength(17),
  comment   String maxlength(128)
}

relationship ManyToOne {
  InventoryModel{make(name)} to Make{required},
  Inventory{inventoryModel(name)} to InventoryModel{required}
}

dto * with mapstruct

paginate * with pagination
service * with serviceClass
search * with elasticsearch
filter *
</code>```

the crud screens work fine, BUT there is no 'not null' constraint on Inventory.inventoryModel or InventoryModel.make which is what I really need

答:
Try this:

```<code>relationship ManyToOne {
  InventoryModel{make(name) required} to Make,
  Inventory{inventoryModel(name) required} to InventoryModel
}
</code>```

Instead of this:

```<code>relationship ManyToOne {
  InventoryModel{make(name)} to Make{required},
  Inventory{inventoryModel(name)} to InventoryModel{required}
}
</code>```

Title: CRUd issues with Jhipster relationships

Body:
I am importing the following jdl to generate a simple jhipster monolith.

I inspected the h2 db after startup and it seems perfect, however when i try to use the ui to create new InventryModel or Inventory entities, the drop downs are not working at all.

It seems when I added the {required} (to enforce non null fks) that this is where it started to go downhill

  config {
    baseName hipcars
    packageName com.hipcars
    applicationType monolith
    databaseType sql
    devDatabaseType h2Disk
    prodDatabaseType mysql
    cacheProvider ehcache
    enableHibernateCache true
    authenticationType jwt
    clientFramework angularX
    useSass false
    clientPackageManager npm
    enableTranslation false
    languages [ en, zh-cn, es ]
    messageBroker kafka
    searchEngine elasticsearch
    serverPort 8080
    websocket false
    testFrameworks [protractor, cucumber, gatling]
    buildTool gradle
  }
  entities *
}

entity Make {
  name String required unique maxlength(20),
  desc String
}

entity InventoryModel {
  name String required unique maxlength(20),
  vehicleType VehicleType
  desc String
}

enum VehicleType {
  SEDAN,
  COUPE
}

entity Inventory {
    vin String required unique maxlength(17),
  comment   String maxlength(128)
}

relationship ManyToOne {
  InventoryModel{make(name) required} to Make,
  Inventory{inventoryModel(name) required} to InventoryModel
}

dto * with mapstruct

paginate * with pagination
service * with serviceClass
search * with elasticsearch
filter *

if I however do this:

application {
  config {
    baseName hipcars
    packageName com.hipcars
    applicationType monolith
    databaseType sql
    devDatabaseType h2Disk
    prodDatabaseType mysql
    cacheProvider ehcache
    enableHibernateCache true
    authenticationType jwt
    clientFramework angularX
    useSass false
    clientPackageManager npm
    enableTranslation false
    languages [ en, zh-cn, es ]
    messageBroker kafka
    searchEngine elasticsearch
    serverPort 8080
    websocket false
    testFrameworks [protractor, cucumber, gatling]
    buildTool gradle
  }
  entities *
}

entity Make {
  name String required unique maxlength(20),
  desc String
}

entity InventoryModel {
  name String required unique maxlength(20),
  vehicleType VehicleType
  desc String
}

enum VehicleType {
  SEDAN,
  COUPE
}

entity Inventory {
    vin String required unique maxlength(17),
  comment   String maxlength(128)
}

relationship ManyToOne {
  InventoryModel{make(name)} to Make{required},
  Inventory{inventoryModel(name)} to InventoryModel{required}
}

dto * with mapstruct

paginate * with pagination
service * with serviceClass
search * with elasticsearch
filter *

the crud screens work fine, BUT there is no 'not null' constraint on Inventory.inventoryModel or InventoryModel.make which is what I really need

Body:
Try this:

relationship ManyToOne {
  InventoryModel{make(name) required} to Make,
  Inventory{inventoryModel(name) required} to InventoryModel
}

Instead of this:

relationship ManyToOne {
  InventoryModel{make(name)} to Make{required},
  Inventory{inventoryModel(name)} to InventoryModel{required}
}


问:
Display subchildren by signed user
Hello I am new in firebase and I need help with display subchildren of firebase which contain the same userID as signed user

 here is users and edu1 full show of user
I need display just subchildren of signed user

and here is my code
 private FirebaseAuth fAuth;

```<code>private DatabaseReference fNotesDatabase;
ArrayAdapter adapter;
ListView listView;
ArrayList<String> arraylist = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_education);
    fAuth = FirebaseAuth.getInstance();
    listView = findViewById(R.id.listview);
    fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education");

    fNotesDatabase.addListenerForSingleValueEvent(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for(DataSnapshot datas: dataSnapshot.getChildren()){
                String values = datas.getKey();
                arraylist.add(values);
                adapter = new ArrayAdapter(Education.this, android.R.layout.simple_list_item_single_choice, arraylist);
                listView.setAdapter(adapter);

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

答:
Try the following:

```<code>    FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    String userId = currentFirebaseUser.getUid();
    fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education");

    fNotesDatabase.addListenerForSingleValueEvent(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for(DataSnapshot datas: dataSnapshot.getChildren()){
                String values = datas.getKey();

               db = FirebaseDatabase.getInstance().getReference().child(values).orderByKey().equalTo(userId);
               db.addListenerForSingleValueEvent(new ValueEventListener(){
                   @Override
               public void onDataChange(DataSnapshot dataSnapshot) {
                   //get data
             }

                    @Override
                public void onCancelled(DatabaseError databaseError) {

                }
             });

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
</code>```

Here you add reference to education then retrieve the direct children under education then using orderByKey() you can check if there is a key equal to the current logged in user and retrieve the data.

Title: Display subchildren by signed user

Body:
Hello I am new in firebase and I need help with display subchildren of firebase which contain the same userID as signed user

 here is users and edu1 full show of user
I need display just subchildren of signed user

and here is my code
 private FirebaseAuth fAuth;

private DatabaseReference fNotesDatabase;
ArrayAdapter adapter;
ListView listView;
ArrayList<String> arraylist = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_education);
    fAuth = FirebaseAuth.getInstance();
    listView = findViewById(R.id.listview);
    fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education");

    fNotesDatabase.addListenerForSingleValueEvent(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for(DataSnapshot datas: dataSnapshot.getChildren()){
                String values = datas.getKey();
                arraylist.add(values);
                adapter = new ArrayAdapter(Education.this, android.R.layout.simple_list_item_single_choice, arraylist);
                listView.setAdapter(adapter);

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Body:
Try the following:

    FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
    String userId = currentFirebaseUser.getUid();
    fNotesDatabase = FirebaseDatabase.getInstance().getReference().child("Notes").child("education");

    fNotesDatabase.addListenerForSingleValueEvent(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {

            for(DataSnapshot datas: dataSnapshot.getChildren()){
                String values = datas.getKey();

               db = FirebaseDatabase.getInstance().getReference().child(values).orderByKey().equalTo(userId);
               db.addListenerForSingleValueEvent(new ValueEventListener(){
                   @Override
               public void onDataChange(DataSnapshot dataSnapshot) {
                   //get data
             }

                    @Override
                public void onCancelled(DatabaseError databaseError) {

                }
             });

            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });

Here you add reference to education then retrieve the direct children under education then using orderByKey() you can check if there is a key equal to the current logged in user and retrieve the data.


问:
Creating 2 numbers from a one #C
I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.

```<code>int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;

        while (checkCount > 0)
        {
            if (checkCount % 2 == 0)
                count2++;
            else
                countRest++;
            checkCount /= 10;
        }

        int[] a = new int[count2];
        int[] b = new int[countRest];

        int k2 = 0, kRest = 0;

        for (int j = 0; j < a.Length + b.Length; j++)
        {
            if (num1 % 2 == 0)
            {
                a[k2] = num1 % 10;
                k2++;
            }
            else
            {
                b[kRest] = num1 % 10;
                kRest++;
            }
            num1 /= 10;
        }
</code>```

I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?

Example:
If I have this number - 12345 so
var = 24, other var = 135

If you have another solution without arrays I think it will be better.
Thank you.

答:
Every programmer should write wacky code at least once a day:</p>

```<code>        int checkCount = 12345, numEven, numOdd;
        Boolean result;

        result = int.TryParse(checkCount.ToString().Replace("0", "").Replace("2", "").Replace("4", "").Replace("6", "").Replace("8", ""), out numOdd);
        result = int.TryParse(checkCount.ToString().Replace("1", "").Replace("3", "").Replace("5", "").Replace("7", "").Replace("9", ""), out numEven);
</code>```

Title: Creating 2 numbers from a one #C

Body:
I should create two new numbers from a one, the first group will contain digits which are divisible by 2 and the other group will contain the others.

int checkCount = 94321, num1 = 94321, count2 = 0, countRest = 0;

        while (checkCount > 0)
        {
            if (checkCount % 2 == 0)
                count2++;
            else
                countRest++;
            checkCount /= 10;
        }

        int[] a = new int[count2];
        int[] b = new int[countRest];

        int k2 = 0, kRest = 0;

        for (int j = 0; j < a.Length + b.Length; j++)
        {
            if (num1 % 2 == 0)
            {
                a[k2] = num1 % 10;
                k2++;
            }
            else
            {
                b[kRest] = num1 % 10;
                kRest++;
            }
            num1 /= 10;
        }

I created two arrays with the numbers I should use, now how can I build two INT varabile when each one contains all of the numbers together from the array?

Example:
If I have this number - 12345 so
var = 24, other var = 135

If you have another solution without arrays I think it will be better.
Thank you.

Body:
Every programmer should write wacky code at least once a day:

        int checkCount = 12345, numEven, numOdd;
        Boolean result;

        result = int.TryParse(checkCount.ToString().Replace("0", "").Replace("2", "").Replace("4", "").Replace("6", "").Replace("8", ""), out numOdd);
        result = int.TryParse(checkCount.ToString().Replace("1", "").Replace("3", "").Replace("5", "").Replace("7", "").Replace("9", ""), out numEven);


问:
Entering additional rows in dataframe as mid points between values of adjacent existing rows
Say you have the following time series dataset in r:

```<code>n <- 3
set.seed(1)
df <- data.frame(Day = rep("Mon", n),
           Time = 1:n,
           Temper = round(rnorm(n, 4, 2), 0))
print(df)

  Day Time Temper
  Mon    1      3
  Mon    2      4
  Mon    3      2
</code>```

Now say you wish to add midpoints between adjacent existing values as extra rows in the data frame. For example, say you wish to add the exact midpoint between every pair of adjacent values, to produce the following new dataframe:

```<code>  Day Time Temper
  Mon    1      3
  Mon  1.5    3.5
  Mon    2      4
  Mon  2.5      3
  Mon    3      2
</code>```

What would be some efficient R code that could accomplish this on much larger datasets?

It would be great if this code could also populate the dataframe with values which are not just the exact midpoints, for example the 'one-third' datapoint:

```<code>  Day Time Temper
  Mon    1      3
  Mon 1.33   3.33
  Mon    2      4
  Mon 2.33   3.33
  Mon    3      2
</code>```

答:
You may want to benchmark (cf library microbenchmark) those 3 solutions, depending on the numbers of factors and numeric variables you have.

Using base R

n <- 3
set.seed(1)
dframe <- data.frame(Day = rep("Mon", n),
                     Time = 1:n,
                     Temper = round(rnorm(n, 4, 2), 0))

# --- convert factor to numeric
mframe <- as.data.frame(sapply(dframe, as.numeric))

# --- function to use on variables
pfun <- function(x, coef = 1/4){

        # x <- mframe$Time ; coef <- .25 ;
        newp <- x[1:(length(x)-1)] + diff(x, lag = 1) * coef
        res <- c(rbind(x[1:(length(x) -1) ], newp) , x[length(x)] )

        return( res )
}

# --- base R way

# pfun( mframe$Time )
# sapply(mframe, pfun, .5)
apply(mframe, 2, pfun)

dframe_final <- as.data.frame ( apply(mframe, 2, pfun) )
# str(dframe_final)

# --- get Day's or other factors back
for(col in names(dframe)[sapply(dframe, is.factor)]){
        dframe_final[[col]] <- factor(dframe_final[[col]])
        levels( dframe_final[[col]] ) <- levels(dframe[[col]])
}
```

<h3>dplyr</h3>

<pre class="lang-r prettyprint-override"><code># --- dplyr way
library(dplyr)
library(purrr)

lfactors <- dframe %>%
        map_if(is.factor, levels)

dframe2 <- dframe %>%
         as_tibble %>%
        map_dfr(as.numeric) %>%
        map_dfr(pfun) %>%
        mutate_at(.vars = names(dframe)[sapply(dframe, is.factor)], .funs = factor)

# --- get Day's or other factors back
for(col in names(dframe)[sapply(dframe, is.factor)]){
        dframe2[[col]] <- factor(dframe2[[col]])
        levels( dframe2[[col]] ) <- levels(dframe[[col]])
}
</code>```

data.table

# --- data.table way
library(data.table)

dframe3 <- data.table(dframe)

dframe3 <- dframe3[ , lapply(.SD, as.numeric)]
dframe3 <- dframe3[ , lapply(.SD, pfun)]

# --- get Day's or other factors back
for(col in names(dframe)[sapply(dframe, is.factor)]){
        dframe3[ , (col) := factor(get(col)) ]
        levels( dframe3[[col]] ) <- levels(dframe[[col]])
}
```

Body:
Say you have the following time series dataset in r:

n <- 3
set.seed(1)
df <- data.frame(Day = rep("Mon", n),
           Time = 1:n,
           Temper = round(rnorm(n, 4, 2), 0))
print(df)

  Day Time Temper
  Mon    1      3
  Mon    2      4
  Mon    3      2

Now say you wish to add midpoints between adjacent existing values as extra rows in the data frame. For example, say you wish to add the exact midpoint between every pair of adjacent values, to produce the following new dataframe:

  Day Time Temper
  Mon    1      3
  Mon  1.5    3.5
  Mon    2      4
  Mon  2.5      3
  Mon    3      2

What would be some efficient R code that could accomplish this on much larger datasets?

It would be great if this code could also populate the dataframe with values which are not just the exact midpoints, for example the 'one-third' datapoint:

  Day Time Temper
  Mon    1      3
  Mon 1.33   3.33
  Mon    2      4
  Mon 2.33   3.33
  Mon    3      2

Body:
You may want to benchmark (cf library microbenchmark) those 3 solutions, depending on the numbers of factors and numeric variables you have.

Using base R

n <- 3
set.seed(1)
dframe <- data.frame(Day = rep("Mon", n),
                     Time = 1:n,
                     Temper = round(rnorm(n, 4, 2), 0))

# --- convert factor to numeric
mframe <- as.data.frame(sapply(dframe, as.numeric))

# --- function to use on variables
pfun <- function(x, coef = 1/4){

        # x <- mframe$Time ; coef <- .25 ;
        newp <- x[1:(length(x)-1)] + diff(x, lag = 1) * coef
        res <- c(rbind(x[1:(length(x) -1) ], newp) , x[length(x)] )

        return( res )
}

# --- base R way

# pfun( mframe$Time )
# sapply(mframe, pfun, .5)
apply(mframe, 2, pfun)

dframe_final <- as.data.frame ( apply(mframe, 2, pfun) )
# str(dframe_final)

# --- get Day's or other factors back
for(col in names(dframe)[sapply(dframe, is.factor)]){
        dframe_final[[col]] <- factor(dframe_final[[col]])
        levels( dframe_final[[col]] ) <- levels(dframe[[col]])
}

dplyr

# --- dplyr way
library(dplyr)
library(purrr)

lfactors <- dframe %>%
        map_if(is.factor, levels)

dframe2 <- dframe %>%
         as_tibble %>%
        map_dfr(as.numeric) %>%
        map_dfr(pfun) %>%
        mutate_at(.vars = names(dframe)[sapply(dframe, is.factor)], .funs = factor)

# --- get Day's or other factors back
for(col in names(dframe)[sapply(dframe, is.factor)]){
        dframe2[[col]] <- factor(dframe2[[col]])
        levels( dframe2[[col]] ) <- levels(dframe[[col]])
}

data.table

# --- data.table way
library(data.table)

dframe3 <- data.table(dframe)

dframe3 <- dframe3[ , lapply(.SD, as.numeric)]
dframe3 <- dframe3[ , lapply(.SD, pfun)]

# --- get Day's or other factors back
for(col in names(dframe)[sapply(dframe, is.factor)]){
        dframe3[ , (col) := factor(get(col)) ]
        levels( dframe3[[col]] ) <- levels(dframe[[col]])
}


问:
React TypeError: " this is undefined ", function inside function call not working
Trying to call addChildNodeNext method in addChildNode function, but

```<code>result = this.addChildNodeNext(item.childrens,CurrentID)
</code>```

gives error of this is undefined. I have already bind both function in constructor.

```<code>class TestAdd extends Component {
  constructor(props) {
    super(props)
    this.addChildNode = this.addChildNode.bind(this)
    this.addChildNodeNext = this.addChildNodeNext.bind(this)
  }

  addChildNodeNext = (nodeList, CurrentID) => {
    alert(`Self ${nodeList} : ${CurrentID}`)
    return nodeList
  }

  addChildNode = (nodeList, CurrentID) => {
    const { childIndex } = this.state
    let index = childIndex
    const newTree = nodeList.filter(function (item) {
      alert(`Self ${item.name} : ${CurrentID}`)
      index += 1
      let result = ""
      if (item.name === CurrentID) {
        const newName = `child_${childIndex}_${CurrentID}`
        result = item.childrens.push({ name: newName, parent: newName, childrens: [] })
      } else if (item.childrens.length > 0) {
        result = this.addChildNodeNext(item.childrens, CurrentID)
      } else {
        result = item
      }
      return result
    });
    this.setState({ childIndex: index })
    this.setState({ treeNode: newTree })
  }

}

export default TestAdd;
</code>```

答:
You are using a regular function in your .filter method. This is why you lose this context there. Also, you don't need to bind your functions in the constructor because you are using arrow functions.

```<code>addChildNode = (nodeList, CurrentID) => {
    const { childIndex } = this.state
    let index = childIndex
    const newTree = nodeList.filter(function (item) { // <--- HERE
      alert(`Self ${item.name} : ${CurrentID}`)
      index += 1
      let result = ""
      if (item.name === CurrentID) {
        const newName = `child_${childIndex}_${CurrentID}`
        result = item.childrens.push({ name: newName, parent: newName, childrens: [] })
      } else if (item.childrens.length > 0) {
        result = this.addChildNodeNext(item.childrens, CurrentID)
      } else {
        result = item
      }
      return result
    });
    this.setState({ childIndex: index })
    this.setState({ treeNode: newTree })
  }
</code>```

You can replace it with an arrow function:

```<code>addChildNode = (nodeList, CurrentID) => {
    const { childIndex } = this.state
    let index = childIndex
    const newTree = nodeList.filter(item => {
      alert(`Self ${item.name} : ${CurrentID}`)
      index += 1
      let result = ""
      if (item.name === CurrentID) {
        const newName = `child_${childIndex}_${CurrentID}`
        result = item.childrens.push({ name: newName, parent: newName, childrens: [] })
      } else if (item.childrens.length > 0) {
        result = this.addChildNodeNext(item.childrens, CurrentID)
      } else {
        result = item
      }
      return result
    });
    this.setState({ childIndex: index })
    this.setState({ treeNode: newTree })
  }
</code>```

Body:
Trying to call addChildNodeNext method in addChildNode function, but

result = this.addChildNodeNext(item.childrens,CurrentID)

gives error of this is undefined. I have already bind both function in constructor.

class TestAdd extends Component {
  constructor(props) {
    super(props)
    this.addChildNode = this.addChildNode.bind(this)
    this.addChildNodeNext = this.addChildNodeNext.bind(this)
  }

  addChildNodeNext = (nodeList, CurrentID) => {
    alert(`Self ${nodeList} : ${CurrentID}`)
    return nodeList
  }

  addChildNode = (nodeList, CurrentID) => {
    const { childIndex } = this.state
    let index = childIndex
    const newTree = nodeList.filter(function (item) {
      alert(`Self ${item.name} : ${CurrentID}`)
      index += 1
      let result = ""
      if (item.name === CurrentID) {
        const newName = `child_${childIndex}_${CurrentID}`
        result = item.childrens.push({ name: newName, parent: newName, childrens: [] })
      } else if (item.childrens.length > 0) {
        result = this.addChildNodeNext(item.childrens, CurrentID)
      } else {
        result = item
      }
      return result
    });
    this.setState({ childIndex: index })
    this.setState({ treeNode: newTree })
  }

}

export default TestAdd;

Body:
You are using a regular function in your .filter method. This is why you lose this context there. Also, you don't need to bind your functions in the constructor because you are using arrow functions.

addChildNode = (nodeList, CurrentID) => {
    const { childIndex } = this.state
    let index = childIndex
    const newTree = nodeList.filter(function (item) { // <--- HERE
      alert(`Self ${item.name} : ${CurrentID}`)
      index += 1
      let result = ""
      if (item.name === CurrentID) {
        const newName = `child_${childIndex}_${CurrentID}`
        result = item.childrens.push({ name: newName, parent: newName, childrens: [] })
      } else if (item.childrens.length > 0) {
        result = this.addChildNodeNext(item.childrens, CurrentID)
      } else {
        result = item
      }
      return result
    });
    this.setState({ childIndex: index })
    this.setState({ treeNode: newTree })
  }

You can replace it with an arrow function:

addChildNode = (nodeList, CurrentID) => {
    const { childIndex } = this.state
    let index = childIndex
    const newTree = nodeList.filter(item => {
      alert(`Self ${item.name} : ${CurrentID}`)
      index += 1
      let result = ""
      if (item.name === CurrentID) {
        const newName = `child_${childIndex}_${CurrentID}`
        result = item.childrens.push({ name: newName, parent: newName, childrens: [] })
      } else if (item.childrens.length > 0) {
        result = this.addChildNodeNext(item.childrens, CurrentID)
      } else {
        result = item
      }
      return result
    });
    this.setState({ childIndex: index })
    this.setState({ treeNode: newTree })
  }


问:
Programatically get/set Mac OSX default system keyboard shortcut
I'm trying to find a way to programatically get/set the default OSX system keyboard shortcuts (hotkeys) found in the System Preferences -> Keyboard & Mouse -> Keyboard Shortcuts tab.  I need to be able to do this in the background, so GUI scripting is not a solution.

I'm unable to find a plist or anything where this info might be stored.  I tried using Instruments "File Activity" trace while using System Preferences, but again came up empty handed.

Any help is appreciated.

答:
Actually there's a Plist for that, informations are stored in com.apple.symbolichotkeys AppleSymbolicHotKeys which is a complex nested dicts and lists as :

```<code>$ defaults read com.apple.symbolichotkeys AppleSymbolicHotKeys
{
    10 =     {
        enabled = 1;
        value =         {
            parameters =             (
                65535,
                96,
                8650752
            );
            type = standard;
        };
    };
    11 =     {
        enabled = 1;
        value =         {
            parameters =             (
                65535,
                97,
                8650752
            );
            type = standard;
        };
    };
[...]
}
</code>```

Let's say you want to programatically modify the "Show Help Menu" shortcut in System Preferences -> Keyboard -> Shortcuts tab -> App Shortcut -> All Applications. To find the correct entry print all the Plist in a text file, modify the shortcut in the System Preferences, print again the the Plist in a second file and diff them:

```<code>$ defaults read com.apple.symbolichotkeys AppleSymbolicHotKeys > 1
$ # modify System Preferences
$ defaults read com.apple.symbolichotkeys AppleSymbolicHotKeys > 2
$ diff -U 5 1 2
--- 1   2019-05-27 23:37:58.000000000 -0300
+++ 2   2019-05-27 23:38:24.000000000 -0300
@@ -5063,13 +5063,13 @@
             };
             98 =             {
                 enabled = 1;
                 value =                 {
                     parameters =                     (
-                        32,
-                        49,
-                        524288
+                        105,
+                        34,
+                        655360
                     );
                     type = standard;
                 };
             };
         };
</code>```

So the entry to be modified is 98, since it's a complex structure you'll have to use /usr/libexec/PlistBuddy to do it:

```<code># Set "alt + Space" as shortcut for "Help menu"
/usr/libexec/PlistBuddy -c "Delete :AppleSymbolicHotKeys:98:value:parameters" ~/Library/Preferences/com.apple.symbolichotkeys.plist
/usr/libexec/PlistBuddy -c "Add :AppleSymbolicHotKeys:98:value:parameters array" ~/Library/Preferences/com.apple.symbolichotkeys.plist
/usr/libexec/PlistBuddy -c "Add :AppleSymbolicHotKeys:98:value:parameters: integer 32" ~/Library/Preferences/com.apple.symbolichotkeys.plist
/usr/libexec/PlistBuddy -c "Add :AppleSymbolicHotKeys:98:value:parameters: integer 49" ~/Library/Preferences/com.apple.symbolichotkeys.plist
/usr/libexec/PlistBuddy -c "Add :AppleSymbolicHotKeys:98:value:parameters: integer 524288" ~/Library/Preferences/com.apple.symbolichotkeys.plist
/usr/libexec/PlistBuddy -c "Delete :AppleSymbolicHotKeys:98:enabled" ~/Library/Preferences/com.apple.symbolichotkeys.plist
/usr/libexec/PlistBuddy -c "Add :AppleSymbolicHotKeys:98:enabled bool true" ~/Library/Preferences/com.apple.symbolichotkeys.plist
</code>```

Note:

I had to delete the bool parameter in order to modify it

Computer must be restarted for the changes to be applied

ContentLicense: CC BY-SA 2.5

Body:
Actually there's a Plist for that, informations are stored in com.apple.symbolichotkeys AppleSymbolicHotKeys which is a complex nested dicts and lists as :

$ defaults read com.apple.symbolichotkeys AppleSymbolicHotKeys
{
    10 =     {
        enabled = 1;
        value =         {
            parameters =             (
                65535,
                96,
                8650752
            );
            type = standard;
        };
    };
    11 =     {
        enabled = 1;
        value =         {
            parameters =             (
                65535,
                97,
                8650752
            );
            type = standard;
        };
    };
[...]
}

Let's say you want to programatically modify the "Show Help Menu" shortcut in System Preferences -> Keyboard -> Shortcuts tab -> App Shortcut -> All Applications. To find the correct entry print all the Plist in a text file, modify the shortcut in the System Preferences, print again the the Plist in a second file and diff them:

$ defaults read com.apple.symbolichotkeys AppleSymbolicHotKeys > 1
$ # modify System Preferences
$ defaults read com.apple.symbolichotkeys AppleSymbolicHotKeys > 2
$ diff -U 5 1 2
--- 1   2019-05-27 23:37:58.000000000 -0300
+++ 2   2019-05-27 23:38:24.000000000 -0300
@@ -5063,13 +5063,13 @@
             };
             98 =             {
                 enabled = 1;
                 value =                 {
                     parameters =                     (
-                        32,
-                        49,
-                        524288
+                        105,
+                        34,
+                        655360
                     );
                     type = standard;
                 };
             };
         };

So the entry to be modified is 98, since it's a complex structure you'll have to use /usr/libexec/PlistBuddy to do it:

# Set "alt + Space" as shortcut for "Help menu"
/usr/libexec/PlistBuddy -c "Delete :AppleSymbolicHotKeys:98:value:parameters" ~/Library/Preferences/com.apple.symbolichotkeys.plist
/usr/libexec/PlistBuddy -c "Add :AppleSymbolicHotKeys:98:value:parameters array" ~/Library/Preferences/com.apple.symbolichotkeys.plist
/usr/libexec/PlistBuddy -c "Add :AppleSymbolicHotKeys:98:value:parameters: integer 32" ~/Library/Preferences/com.apple.symbolichotkeys.plist
/usr/libexec/PlistBuddy -c "Add :AppleSymbolicHotKeys:98:value:parameters: integer 49" ~/Library/Preferences/com.apple.symbolichotkeys.plist
/usr/libexec/PlistBuddy -c "Add :AppleSymbolicHotKeys:98:value:parameters: integer 524288" ~/Library/Preferences/com.apple.symbolichotkeys.plist
/usr/libexec/PlistBuddy -c "Delete :AppleSymbolicHotKeys:98:enabled" ~/Library/Preferences/com.apple.symbolichotkeys.plist
/usr/libexec/PlistBuddy -c "Add :AppleSymbolicHotKeys:98:enabled bool true" ~/Library/Preferences/com.apple.symbolichotkeys.plist

Note:

I had to delete the bool parameter in order to modify it

Computer must be restarted for the changes to be applied


问:
Form input realtime feedback
I'm constructing a form with an input field for a username. I want to restrict the username to a pretty small range of characters using regex, changing the color of the text from red to green based on the validity of the input compared to the regex as the user types.

So far it isn't picking up any characters that aren't valid despite positive testing of the regex.

https://regex101.com/r/XPFy6c/1/

```<code>/^[A-Z0-9 -]+$/igm
</code>```

Here's the code, with a JSFiddle here.

const form = document.querySelector('form');
const input = document.querySelector('input');

const check = /^[A-Z0-9 -]+$/ig;

form.addEventListener("input", e => {
    const checkName = check.test(input.value);
    if(!check) {
        input.classList.add('invalid-name');
        input.classList.remove('valid-name');
    } else {
        input.classList.add('valid-name');
        input.classList.remove('invalid-name');
    }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.invalid-name {
  color: red;
}

.valid-name {
  color: green;
}</code>```

<form id="form">
    <input class="col-12 edit-name-field" id="name" name="edit-name" maxlength="12" autocomplete="off">
</form>```

Update: Although this question is solved, if you try the code you will notice that there remains an issue with the regex alternating true/false. The solution to this problem is here.

答:
In your event listener, you are testing the value alright, however, after that your condition is based on the reference holding the regex not the test result. i.e. check instead of checkName. Since the regex will always evaluate to truthy value, the else part of your condition gets executed. Try your code with following changes:

```<code>form.addEventListener("input", e => {
    const checkName = check.test(input.value);
    if(!checkName) {
        input.classList.add('invalid-name');
        input.classList.remove('valid-name');
    } else {
        input.classList.add('valid-name');
        input.classList.remove('invalid-name');
    }
});
</code>```

Additionally, you should also consider selecting your form, and the input with more specific selectors. Right now your selector basically returns the 'first input field' or 'first form' in the body, this might not always be the element that you expected.

Title: Form input realtime feedback

Body:
I'm constructing a form with an input field for a username. I want to restrict the username to a pretty small range of characters using regex, changing the color of the text from red to green based on the validity of the input compared to the regex as the user types.

So far it isn't picking up any characters that aren't valid despite positive testing of the regex.

https://regex101.com/r/XPFy6c/1/

/^[A-Z0-9 -]+$/igm

Here's the code, with a JSFiddle here.

const form = document.querySelector('form');
const input = document.querySelector('input');

const check = /^[A-Z0-9 -]+$/ig;

form.addEventListener("input", e => {
    const checkName = check.test(input.value);
    if(!check) {
        input.classList.add('invalid-name');
        input.classList.remove('valid-name');
    } else {
        input.classList.add('valid-name');
        input.classList.remove('invalid-name');
    }
})

.invalid-name {
  color: red;
}

.valid-name {
  color: green;
}

<form id="form">
    <input class="col-12 edit-name-field" id="name" name="edit-name" maxlength="12" autocomplete="off">
</form>

Update: Although this question is solved, if you try the code you will notice that there remains an issue with the regex alternating true/false. The solution to this problem is here.

Body:
In your event listener, you are testing the value alright, however, after that your condition is based on the reference holding the regex not the test result. i.e. check instead of checkName. Since the regex will always evaluate to truthy value, the else part of your condition gets executed. Try your code with following changes:

form.addEventListener("input", e => {
    const checkName = check.test(input.value);
    if(!checkName) {
        input.classList.add('invalid-name');
        input.classList.remove('valid-name');
    } else {
        input.classList.add('valid-name');
        input.classList.remove('invalid-name');
    }
});

Additionally, you should also consider selecting your form, and the input with more specific selectors. Right now your selector basically returns the 'first input field' or 'first form' in the body, this might not always be the element that you expected.


问:
Getting memory leaks with okhttp
When I make a get request to an API, over and over again I see that every request the memory goes up and up until 1gb of ram usage.

closing the response
and autoclosable

```<code>final OkHttpClient client = new OkHttpClient().newBuilder()
        .connectTimeout(5, TimeUnit.SECONDS)
        .writeTimeout(5, TimeUnit.SECONDS)
        .build();

Request request = new Request.Builder()
        .url("https://api.ipify.org?format=json")
        .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.137 Mobile Safari/537.36")
        .build();

try (Response response = client.newCall(request).execute()) {
    ResponseBody s = response.body();
    assert s != null;
    System.out.println(s.toString());
    s.close();
} catch (IOException e) {
    e.printStackTrace();
}
</code>```

答:
You didn't close the connection, use response.close(); </p>

```<code>            final OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .writeTimeout(5, TimeUnit.SECONDS)
                    .build();

            Request request = new Request.Builder()
                    .url("https://api.ipify.org")
                    .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.137 Mobile Safari/537.36")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                ResponseBody reponseBody = response.body();
                assert reponseBody != null;

                String ip = reponseBody.string();
                System.out.println(ip);
                response.close();
                reponseBody.close();
            } catch (IOException e) {
                e.printStackTrace();
            }```
</code>```

Title: Getting memory leaks with okhttp

Body:
When I make a get request to an API, over and over again I see that every request the memory goes up and up until 1gb of ram usage.

closing the response
and autoclosable

final OkHttpClient client = new OkHttpClient().newBuilder()
        .connectTimeout(5, TimeUnit.SECONDS)
        .writeTimeout(5, TimeUnit.SECONDS)
        .build();

Request request = new Request.Builder()
        .url("https://api.ipify.org?format=json")
        .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.137 Mobile Safari/537.36")
        .build();

try (Response response = client.newCall(request).execute()) {
    ResponseBody s = response.body();
    assert s != null;
    System.out.println(s.toString());
    s.close();
} catch (IOException e) {
    e.printStackTrace();
}

Body:
You didn't close the connection, use response.close();

            final OkHttpClient client = new OkHttpClient().newBuilder()
                    .connectTimeout(5, TimeUnit.SECONDS)
                    .writeTimeout(5, TimeUnit.SECONDS)
                    .build();

            Request request = new Request.Builder()
                    .url("https://api.ipify.org")
                    .addHeader("User-Agent", "Mozilla/5.0 (Linux; Android 8.0.0; SM-G960F Build/R16NW) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/64.0.3282.137 Mobile Safari/537.36")
                    .build();

            try (Response response = client.newCall(request).execute()) {
                ResponseBody reponseBody = response.body();
                assert reponseBody != null;

                String ip = reponseBody.string();
                System.out.println(ip);
                response.close();
                reponseBody.close();
            } catch (IOException e) {
                e.printStackTrace();
            }```


问:
How can I keep some columns as is and dynamically pivot the last column in SQL Server 2012
I have a table with 5 columns with values 0 or 1 and the last column QuoteStatus is of type VARCHAR.

I want to keep ControlNo and the other 4 columns as is, but the last column I need to pivot and also assign value either 0 or 1.

It can be more than 2 values: Lost or No Action.

So the data looks like this now:

```<code>DECLARE @Table1 TABLE
                (
                    ControlNo INT,
                    Bound INT,
                    Declined INT,
                    Rated INT,
                    Quoted INT,
                    QuoteStatus VARCHAR(50)
                )

INSERT INTO @Table1 (ControlNo, Bound, Declined, Rated, Quoted, QuoteStatus)
VALUES
(1111,1,0,1,1,'Lost'),
(2222,0,1,0,1,'No Action'),
(3333,1,1,0,0,NULL),
(4444,1,0,0,1,'Lost'),
(5555,0,1,1,1,'No Action')
</code>```

But I want it to look like this:

答:
We should use dynamic query to achieve the result.

In Dynamic Query :

Table variables are only visible in the scope where they are defined. They're like normal variables. Instead of table variable, I used temp tables.

IF OBJECT_ID('tempdb..##A') IS NOT NULL DROP TABLE ##A

IF OBJECT_ID('tempdb..#table1') IS NOT NULL DROP TABLE #table1

Create table #Table1
                (
                    ControlNo INT,
                    Bound INT,
                    Declined INT,
                    Rated INT,
                    Quoted INT,
                    QuoteStatus VARCHAR(50)
                )

INSERT INTO #Table1 (ControlNo, Bound, Declined, Rated, Quoted, QuoteStatus)
VALUES
(1111,1,0,1,1,'Lost'),
(2222,0,1,0,1,'No Action'),
(3333,1,1,0,0,NULL),
(4444,1,0,0,1,'Lost'),
(5555,0,1,1,1,'No Action')

DECLARE @columns AS NVARCHAR(MAX),
    @finalquery  AS NVARCHAR(MAX);

SET @columns = STUFF((SELECT distinct ',' + QUOTENAME(QuoteStatus)
            FROM #Table1
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @finalquery = '
select
    p.controlno,p.Bound, p.Declined, p.Rated,p.Quoted,' + @columns + '

into ##A
from
    (
    select
        ControlNo, Bound, Declined, Rated, Quoted, QuoteStatus

from  #Table1

    )a
pivot
    (
    max(QuoteStatus)
        for QuoteStatus IN (' + @columns + ')
    )p '

exec(@finalquery)

select
    ControlNo,Bound, Declined, Rated,Quoted,
    case when Lost = 'LOST' then 1 else 0 end as Lost,
    case when [no action] = 'No Action' then 1 else 0 end as [No Action]
from ##a

Body:
I have a table with 5 columns with values 0 or 1 and the last column QuoteStatus is of type VARCHAR.

I want to keep ControlNo and the other 4 columns as is, but the last column I need to pivot and also assign value either 0 or 1.

It can be more than 2 values: Lost or No Action.

So the data looks like this now:

DECLARE @Table1 TABLE
                (
                    ControlNo INT,
                    Bound INT,
                    Declined INT,
                    Rated INT,
                    Quoted INT,
                    QuoteStatus VARCHAR(50)
                )

INSERT INTO @Table1 (ControlNo, Bound, Declined, Rated, Quoted, QuoteStatus)
VALUES
(1111,1,0,1,1,'Lost'),
(2222,0,1,0,1,'No Action'),
(3333,1,1,0,0,NULL),
(4444,1,0,0,1,'Lost'),
(5555,0,1,1,1,'No Action')

But I want it to look like this:


问:
Cannot open user default database. Login failed. SQL 2005
I have taken a copy of a database home with me so I can do some testing. However when I try to run a stored procedure I get Cannot open user default database. Login failed..

I have checked and checked and checked I can open tables in the databases login to sql management studio and access the default as well as other databases any ideas?

Possibly a corrupt user it was from sql 2000 at work to 2005 at home

答:
I just solved this issue.   My default database was AdventureWorks2008, so as an Administrator, I ended up removing my login from the server.   Then running the following to recreate my user</p>

```<code>CREATE LOGIN [NT\mylogin] FROM WINDOWS WITH DEFAULT_DATABASE=[Master], DEFAULT_LANGUAGE=[us_english]
GO
</code>```

LastEditorDisplayName: Andy Lester

Body:
I just solved this issue.   My default database was AdventureWorks2008, so as an Administrator, I ended up removing my login from the server.   Then running the following to recreate my user

CREATE LOGIN [NT\mylogin] FROM WINDOWS WITH DEFAULT_DATABASE=[Master], DEFAULT_LANGUAGE=[us_english]
GO


问:
need to pass ~a id="myID" onclick=cEdit("var1","var2")>Display Text Display Text~/a~

I can build a string that (using the text visualizer) looks like this, but what is actually being passed to the plugin property is:

~a id=\"myID\" onclick=cEdit(\"var1\",\"var2\")>Display Text~/a~

This results in the HTML being written  as:

~a id=\"myID\" onclick=cEdit(\"var1\",\"var2\")>Display Text~/a~

This obviously does not work.

I have tried

```<code>    string ss = @"~a id=""myID"" onclick=cEdit(""var1"",""var2"")>Display Text ~/a~";

    string ss = @"~a id=\"myID\" onclick=cEdit(\"var1\",\"var2\")>Display Text ~/a~";

    string ss = @"~a id=\"myID\" onclick=cEdit(\"var1\",\"var2\")>Display Text ~/a~";

    ss = ss.replace(“\\”,”\”)
</code>```

My Code:

(controller)

```<code>private OrgModel.OrgChild GetChild(string mgrId, string Org_CD, string Div, string strClass)
    {

        OrgModel.OrgChild rtnChild = new OrgModel.OrgChild();
        …
         Detail code
        …

  string ss = @"<a id=""myID"" onclick=cEdit(""var1"",""var2"")>Display Text </a>";

        rtnChild.name = ss;
        rtnChild.title = strName;
        rtnChild.className = strClass;

        return rtnChild;
    }
</code>```

My Code ( JavaScript)

```<code>~script~function cEdit(var1,var2) {alert(var1 + " - " + var2);}~/script~
</code>```

I want to pass the exact string to the plugin as:

~a id="myID" onclick=cEdit("var1","var2")>Display Text ~/a~

NOTE: Please replace ~ Character with the appropriate < or > character. They are swapped to ensure proper display.

答:
From what I understand is that you are trying to pass a html value set on your controller to a plugin on your view.

What I have checked so far is that hidden input can hold the model html value correctly.

```<code>@model MyModel
@{
    string myHTML = Model.MyHTMLValue;
    ViewBag.Title = "Index";
}

@Html.Hidden("someHTML", myHTML)

<script>
    $(function () {
        console.log($('#someHTML').val());
    });
</script>
</code>```

Further, have a look at Decode

Title: need to pass ~a id="myID" onclick=cEdit("var1","var2")>Display Text </a~ as an exact string to a plug-in

Body:
Good morning Team,
    I am new to this site, but have found it helpful over the last several months.  I have a challenge with MVC .net core 2.2 and c#.  I am hopeful this forum may be able to help.

I need to pass the following string into a property of a plug-in:

~a id="myID" onclick=cEdit("var1","var2")>Display Text~/a~

I can build a string that (using the text visualizer) looks like this, but what is actually being passed to the plugin property is:

~a id=\"myID\" onclick=cEdit(\"var1\",\"var2\")>Display Text~/a~

This results in the HTML being written  as:

~a id=\"myID\" onclick=cEdit(\"var1\",\"var2\")>Display Text~/a~

This obviously does not work.

I have tried

    string ss = @"~a id=""myID"" onclick=cEdit(""var1"",""var2"")>Display Text ~/a~";

    string ss = @"~a id=\"myID\" onclick=cEdit(\"var1\",\"var2\")>Display Text ~/a~";

    string ss = @"~a id=\"myID\" onclick=cEdit(\"var1\",\"var2\")>Display Text ~/a~";

    ss = ss.replace(“\\”,”\”)

My Code:

(controller)

private OrgModel.OrgChild GetChild(string mgrId, string Org_CD, string Div, string strClass)
    {

        OrgModel.OrgChild rtnChild = new OrgModel.OrgChild();
        …
         Detail code
        …

  string ss = @"Display Text ";

        rtnChild.name = ss;
        rtnChild.title = strName;
        rtnChild.className = strClass;

        return rtnChild;
    }

My Code ( JavaScript)

~script~function cEdit(var1,var2) {alert(var1 + " - " + var2);}~/script~

I want to pass the exact string to the plugin as:

~a id="myID" onclick=cEdit("var1","var2")>Display Text ~/a~

NOTE: Please replace ~ Character with the appropriate < or > character. They are swapped to ensure proper display.

Body:
From what I understand is that you are trying to pass a html value set on your controller to a plugin on your view.

What I have checked so far is that hidden input can hold the model html value correctly.

@model MyModel
@{
    string myHTML = Model.MyHTMLValue;
    ViewBag.Title = "Index";
}

@Html.Hidden("someHTML", myHTML)

<script>
    $(function () {
        console.log($('#someHTML').val());
    });
</script>

Further, have a look at Decode


问:
GIT - Keeps asking username even after global storage
I have saved my username globally in GIT when I check by using git config --global user.name command, it shows me correct username but it still keeps me asking username every time when I push or commit the code.

Does anyone have an idea?

Thanks in advance.

答:
Asking for your username when pushing is about authentication, not commit authorship.

Regarding authentication (credentials, username/password provided to a remote Git repository hosting service), you need to check your git config credential.helper: that setting can setup a cache, avoiding to request your credentials every time you are pushing.

As the OP Pribhav comments, you can as in this answer, embed the username in the URL (https://username@site/...).

Nut the credential.helper is still needed to avoid asking for your password.


问:
[PHP][LARAVEL] "Class 'App\User' not found" but there is clearly 'use App\User;' in the code
I'm using some very simple code in "api.php" in Laravel and this error is driving me nuts.

Code:

```<code><?php

use Illuminate\Http\Request;
use App\User;

// list new user
Route::get('users', function() {
    // If the Content-Type and Accept headers are set to 'application/json',
    // this will return a JSON structure. This will be cleaned up later.
    return User::all();
});

// create new user
Route::post('users/add', function(Request $request) {
    return User::create($request->all);
});
</code>```

Error:

Class 'App\User' not found

How is this even possible?

答: check the namespace in model User.php.It should be App\User

Body:
I'm using some very simple code in "api.php" in Laravel and this error is driving me nuts.

Code:

<?php

use Illuminate\Http\Request;
use App\User;

// list new user
Route::get('users', function() {
    // If the Content-Type and Accept headers are set to 'application/json',
    // this will return a JSON structure. This will be cleaned up later.
    return User::all();
});

// create new user
Route::post('users/add', function(Request $request) {
    return User::create($request->all);
});

Error:

Class 'App\User' not found

How is this even possible?


问:
Java 8 Stream Map Collector Error - role cannot be resolved to a variable
I am new to spring security. I was trying to creating my first project using spring  boot and spring security with the help of this tutorial

In UserServiceImpl file there is a function mapRolesToAuthorities, it takes Collection < Role > roles as a parameter.

Now the problem is, when I try to stream and map the roles like this

```<code>private Collection < ? extends GrantedAuthority >
mapRolesToAuthorities(Collection < Role > roles)
    {
    return roles.stream().map(role - > new
    SimpleGrantedAuthority(role.getRolename()))
    .collect(Collectors.toList());
    }
</code>```

It shows error that

role cannot be resolved to a variable

.

How can I resolve this issue?

答:
There is a typo with extra space in lambda operator:

```<code>role - >
</code>```

should be

```<code>role ->
</code>```

Body:
I am new to spring security. I was trying to creating my first project using spring  boot and spring security with the help of this tutorial

In UserServiceImpl file there is a function mapRolesToAuthorities, it takes Collection < Role > roles as a parameter.

Now the problem is, when I try to stream and map the roles like this

private Collection < ? extends GrantedAuthority >
mapRolesToAuthorities(Collection < Role > roles)
    {
    return roles.stream().map(role - > new
    SimpleGrantedAuthority(role.getRolename()))
    .collect(Collectors.toList());
    }

It shows error that

role cannot be resolved to a variable

.

How can I resolve this issue?

Body:
There is a typo with extra space in lambda operator:

role - >

should be

role ->


问:
Parse XML response from service asp.net
I am trying to integrate a web service with my project. The web service returns an XML response:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:ns1="http://www.tpg.ua/"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
                   SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <SOAP-ENV:Body>
        <ns1:getCitiesResponse>
            <return xsi:type="xsd:string">
                [
                    {
                        "cityTitle": "Тирана",
                        "countryId": "7",
                        "cityId": "2493",
                        "IATA": "TIA"
                    },
                    {
                        "cityTitle": "Ла-Романа",
                        "countryId": "48",
                        "cityId": "1280",
                        "IATA": "LRM"
                    },
                    {
                        "cityTitle": "Херсон",
                        "countryId": "145",
                        "cityId": "2719",
                        "IATA": "KHE"
                    },
                    {
                        "cityTitle": "Шарм",
                        "countryId": "49",
                        "cityId": "2851",
                        "IATA": "SSH"
                    }
                ]
            </return>
        </ns1:getCitiesResponse>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>
```

<p>I am trying to parse that response. I want to get the <code>cityId</code> and the <code>countryId</code></p>

<pre class="lang-cs prettyprint-override"><code>XmlDocument listXML = new XmlDocument();
listXML.LoadXml(response);

string baseNode = @"return/";

XmlNode item1 = listXML.SelectSingleNode(baseNode + "countryId");
XmlNode item2 = listXML.SelectSingleNode(baseNode + "cityId");

string s = item1.InnerText.ToString();
string s1 = item2.InnerText.ToString();
</code>```

But it is null; what should I do?

答:
The return element of your SOAP response contains a JSON string, so you cannot use XmlDocument and an XPath query to extract data from that.

You need to query the JSON data with a JSON deserializer, for example I have used JSON.NET in this example - you can add this to your project by installing the NuGet package Newtonsoft.Json.

So there are two steps here - firstly extract the content of the return element from the XML response. I use XDocument rather than XmlDocument as you have used, as XDocument is a more modern API and plays nicer with modern language features such as Linq.

Second step is to deserialise the JSON content, and extract the content into variables.

```<code>var xDoc = XDocument.Parse(response);
var returnJson = xDoc.Descendants("return")
    .Single()
    .Value;

var cities = JArray.Parse(returnJson);
foreach (var city in cities)
{
    var cityId = city["cityId"].Value<string>();
    var countryId = city["countryId"].Value<string>();
}
</code>```

Title: Parse XML response from service asp.net

Body:
I am trying to integrate a web service with my project. The web service returns an XML response:

<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"
                   xmlns:ns1="http://www.tpg.ua/"
                   xmlns:xsd="http://www.w3.org/2001/XMLSchema"
                   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                   xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/"
                   SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
    <SOAP-ENV:Body>
        <ns1:getCitiesResponse>
            <return xsi:type="xsd:string">
                [
                    {
                        "cityTitle": "Тирана",
                        "countryId": "7",
                        "cityId": "2493",
                        "IATA": "TIA"
                    },
                    {
                        "cityTitle": "Ла-Романа",
                        "countryId": "48",
                        "cityId": "1280",
                        "IATA": "LRM"
                    },
                    {
                        "cityTitle": "Херсон",
                        "countryId": "145",
                        "cityId": "2719",
                        "IATA": "KHE"
                    },
                    {
                        "cityTitle": "Шарм",
                        "countryId": "49",
                        "cityId": "2851",
                        "IATA": "SSH"
                    }
                ]
            </return>
        </ns1:getCitiesResponse>
    </SOAP-ENV:Body>
</SOAP-ENV:Envelope>

I am trying to parse that response. I want to get the cityId and the countryId

XmlDocument listXML = new XmlDocument();
listXML.LoadXml(response);

string baseNode = @"return/";

XmlNode item1 = listXML.SelectSingleNode(baseNode + "countryId");
XmlNode item2 = listXML.SelectSingleNode(baseNode + "cityId");

string s = item1.InnerText.ToString();
string s1 = item2.InnerText.ToString();

But it is null; what should I do?

Body:
The return element of your SOAP response contains a JSON string, so you cannot use XmlDocument and an XPath query to extract data from that.

You need to query the JSON data with a JSON deserializer, for example I have used JSON.NET in this example - you can add this to your project by installing the NuGet package Newtonsoft.Json.

So there are two steps here - firstly extract the content of the return element from the XML response. I use XDocument rather than XmlDocument as you have used, as XDocument is a more modern API and plays nicer with modern language features such as Linq.

Second step is to deserialise the JSON content, and extract the content into variables.

var xDoc = XDocument.Parse(response);
var returnJson = xDoc.Descendants("return")
    .Single()
    .Value;

var cities = JArray.Parse(returnJson);
foreach (var city in cities)
{
    var cityId = city["cityId"].Value<string>();
    var countryId = city["countryId"].Value<string>();
}


问:
Render a HtmlSelectOneMenu with only one entry as readonly inputfield in jsf?
Well we're trying to render a shitload of lists. Some of them have only one entry and we want them to appear as read only input fields (so users don't get fooled and it's easier to read).
But it seems kinda hard to access the inner selectitems size from outside.
I had my go with overwriting the htmlselectonemenu tag... Is there a different nicer way? Even possible to access it on tag level?

```<code>/**
 * In case there is only one or less elements in the select list -> set readonly(true)
 */
public class HtmlSelectOneMenuModf extends HtmlSelectOneMenu {

    @Override
    public boolean isReadonly() {
        for (Iterator iterator = getChildren().iterator(); iterator.hasNext();) {
            Object obj = iterator.next();
            if ( obj instanceof UISelectItems) {
                UISelectItemsi = (UISelectItems) obj;
                if(i.getSelectItems().size() <=1)
                    super.setReadonly(true);
            }
        }
        return super.isReadonly();
    }
}
</code>```

We're chilling on JSF 1.2 btw...

答:
Use JSTL fn:length().

```<code><%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<h:selectOneMenu value="#{bean.item}" readonly="#{fn:length(bean.items) le 1}">
    <f:selectItems value="#{bean.items}" />
</h:selectOneMenu>
</code>```

Body:
Well we're trying to render a shitload of lists. Some of them have only one entry and we want them to appear as read only input fields (so users don't get fooled and it's easier to read).
But it seems kinda hard to access the inner selectitems size from outside.
I had my go with overwriting the htmlselectonemenu tag... Is there a different nicer way? Even possible to access it on tag level?

/**
 * In case there is only one or less elements in the select list -> set readonly(true)
 */
public class HtmlSelectOneMenuModf extends HtmlSelectOneMenu {

    @Override
    public boolean isReadonly() {
        for (Iterator iterator = getChildren().iterator(); iterator.hasNext();) {
            Object obj = iterator.next();
            if ( obj instanceof UISelectItems) {
                UISelectItemsi = (UISelectItems) obj;
                if(i.getSelectItems().size() <=1)
                    super.setReadonly(true);
            }
        }
        return super.isReadonly();
    }
}

We're chilling on JSF 1.2 btw...

Body:
Use JSTL fn:length().

<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
...
<h:selectOneMenu value="#{bean.item}" readonly="#{fn:length(bean.items) le 1}">
    <f:selectItems value="#{bean.items}" />
</h:selectOneMenu>


问:
How to mock rest clients when unittesting a Quarkus application?
Quarkus getting started unittest describes how to mock injected services. However when trying to apply this to an injected rest client this does not seem to work.

In my application the class attribute to be injected is defined like this

  @Inject
  @RestClient
  MyService myService;
```

<p>In my test code I created a mock service like this:</p>

<pre class="lang-java prettyprint-override"><code>@Alternative()
@Priority(1)
@ApplicationScoped
public class MockMyService extends MyService {

    @Override
    public MyObject myServicemethos() {
        return new MyObject();
    }
}
</code>```

Please note that this service is not registered or annotated as a RestClient. Running my unittests like this gives the following error:

```<code>org.junit.jupiter.api.extension.TestInstantiationException: TestInstanceFactory [io.quarkus.test.junit.QuarkusTestExtension] failed to instantiate test class [...MyMediatorTest]: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
    [error]: Build step io.quarkus.arc.deployment.ArcAnnotationProcessor#build threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type ...MyService and qualifiers [@RestClient]
    - java member: ...MyMediator#myService
    - declared on CLASS bean [types=[java.lang.Object, ...MyMediator], qualifiers=[@Default, @Any], target=...MyMediator]

    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeTestInstanceFactory(ClassTestDescriptor.java:314)
  ...
</code>```

I can probably overcome this by adding an additional service layer. But that feels like heading in the wrong direction.

How can I solve this.

Kind regards,

misl

答:
You don't need another level of indirection.

You can simply do:

```<code>@Alternative()
@Priority(1)
@ApplicationScoped
@RestClient
public class MockMyService extends MyService {

    @Override
    public MyObject myServicemethos() {
        return new MyObject();
    }
}
</code>```

Note that I added the @RestClient annotation.

Update

It's probably more intuitive to use @RegisterRestClient instead of @RestClient as mentioned in the comments and in the answer by @Tushar

Update 2

Quarkus also has builtin mock support for CDI beans, see https://quarkus.io/guides/getting-started-testing#further-simplification-with-injectmock and https://quarkus.io/blog/mocking/

Body:
Quarkus getting started unittest describes how to mock injected services. However when trying to apply this to an injected rest client this does not seem to work.

In my application the class attribute to be injected is defined like this

  @Inject
  @RestClient
  MyService myService;

In my test code I created a mock service like this:

@Alternative()
@Priority(1)
@ApplicationScoped
public class MockMyService extends MyService {

    @Override
    public MyObject myServicemethos() {
        return new MyObject();
    }
}

Please note that this service is not registered or annotated as a RestClient. Running my unittests like this gives the following error:

org.junit.jupiter.api.extension.TestInstantiationException: TestInstanceFactory [io.quarkus.test.junit.QuarkusTestExtension] failed to instantiate test class [...MyMediatorTest]: io.quarkus.builder.BuildException: Build failure: Build failed due to errors
    [error]: Build step io.quarkus.arc.deployment.ArcAnnotationProcessor#build threw an exception: javax.enterprise.inject.spi.DeploymentException: javax.enterprise.inject.UnsatisfiedResolutionException: Unsatisfied dependency for type ...MyService and qualifiers [@RestClient]
    - java member: ...MyMediator#myService
    - declared on CLASS bean [types=[java.lang.Object, ...MyMediator], qualifiers=[@Default, @Any], target=...MyMediator]

    at org.junit.jupiter.engine.descriptor.ClassTestDescriptor.invokeTestInstanceFactory(ClassTestDescriptor.java:314)
  ...

I can probably overcome this by adding an additional service layer. But that feels like heading in the wrong direction.

How can I solve this.

Kind regards,

misl

Body:
You don't need another level of indirection.

You can simply do:

@Alternative()
@Priority(1)
@ApplicationScoped
@RestClient
public class MockMyService extends MyService {

    @Override
    public MyObject myServicemethos() {
        return new MyObject();
    }
}

Note that I added the @RestClient annotation.

Update

It's probably more intuitive to use @RegisterRestClient instead of @RestClient as mentioned in the comments and in the answer by @Tushar

Update 2

Quarkus also has builtin mock support for CDI beans, see https://quarkus.io/guides/getting-started-testing#further-simplification-with-injectmock and https://quarkus.io/blog/mocking/