问:
How do I use the bitwise operator XOR in Lua?
How can I implement bitwise operators in Lua language?

Specifically, I need a XOR operator/method.

答:
If you're needing an efficient way to do bitwise shifts, I wrote an article about that a while ago. Here's some functions which wrap the technique:</p>

```<code>function lshift(x, by)
  return x * 2 ^ by
end

function rshift(x, by)
  return math.floor(x / 2 ^ by)
end
</code>```

Body:
If you're needing an efficient way to do bitwise shifts, I wrote an article about that a while ago. Here's some functions which wrap the technique:

function lshift(x, by)
  return x * 2 ^ by
end

function rshift(x, by)
  return math.floor(x / 2 ^ by)
end


来源: stackexchange

问:
Is there a way to do this in a simple query?
I have a BIG (23 millions rows) table CONTRATOS which has these columns:

```<code>SELECT
    CONTRATO,
    CODIGO_ORIGEN,
    ORIGEN
FROM CONTRATOS;
</code>```

There are multiple rows with the same value for the column CODIGO_ORIGEN:

```<code>CODIGO_ORIGEN     CONTRATO       ORIGEN
-------------    ----------     --------
     1               345          CONT
     1               363          BKP
     1               645          BKP
     1               365          CONT
</code>```

I need to get only one CONTRATO per CODIGO_ORIGEN but always prioritizing the 'CONT' value. So in this sample it would be the CONTRATO with value 365

I was trying to to something like this:

```<code>SELECT
   CODIGO_ORIGEN,
   CASE
    WHEN ORIGEN = 'CONT' THEN
        FIRST_VALUE (CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CONTRATO DESC)
    WHEN ORIGEN = 'BKP' THEN
        FIRST_VALUE (CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CAMPO1 DESC, CAMPO2 DESC, CONTRATO DESC)
   END AS CONTRATO
FROM CONTRATOS;
</code>```

In case ORIGEN is 'CONTR' i should sort by the highest CONTRATO and get the CONTRATO column.
In case ORIGEN is 'BKP' i should sort by different columns and get the CONTRATO column.

Finally, i should be able to have one unique row with CODIGO_ORIGEN -> CONTRATO (1:1).

Is there a simple way to do this (1 query)?

Thanks in advance!

答:
Check if there is origen = 'CONT', use analytic count(). If yes - use analytic function with first ordering method, if no - second ordering:

```<code>select mgr_cuenta_ctl.*,
       case
       when count(case origen when 'CONT' then 1 end) over (partition by codigo_origen) > 0
       then first_value(contrato) over (
            partition by codigo_origen
            order by case origen when 'CONT' then 1 end, contrato desc)
       else first_value(contrato) over (
            partition by codigo_origen
            order by case origen when 'BKP' then 1 end, campo1 desc, campo2 desc, contrato desc)
       end as best
  from mgr_cuenta_ctl
</code>```

If you want only grouped values, without details, remove partition by clauses:

```<code>select codigo_origen,
       case when count(case origen when 'CONT' then 1 end) > 0
       then max(contrato) keep (dense_rank first
                order by case origen when 'CONT' then 1 end, contrato desc)
       else max(contrato) keep (dense_rank first
                order by case origen when 'BKP' then 1 end, campo1 desc, campo2 desc)
       end as best
  from mgr_cuenta_ctl
  group by codigo_origen
</code>```

dbfiddle demo

BTW. I tried to analyse your query, but it throwed some strange errors and I gave up. Here you touch table only once, no self-joins, so it should be faster.

ContentLicense: CC BY-SA 4.0

Body:
I have a BIG (23 millions rows) table CONTRATOS which has these columns:

SELECT
    CONTRATO,
    CODIGO_ORIGEN,
    ORIGEN
FROM CONTRATOS;

There are multiple rows with the same value for the column CODIGO_ORIGEN:

CODIGO_ORIGEN     CONTRATO       ORIGEN
-------------    ----------     --------
     1               345          CONT
     1               363          BKP
     1               645          BKP
     1               365          CONT

I need to get only one CONTRATO per CODIGO_ORIGEN but always prioritizing the 'CONT' value. So in this sample it would be the CONTRATO with value 365

I was trying to to something like this:

SELECT
   CODIGO_ORIGEN,
   CASE
    WHEN ORIGEN = 'CONT' THEN
        FIRST_VALUE (CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CONTRATO DESC)
    WHEN ORIGEN = 'BKP' THEN
        FIRST_VALUE (CONTRATO) OVER (PARTITION BY CODIGO_ORIGEN ORDER BY CAMPO1 DESC, CAMPO2 DESC, CONTRATO DESC)
   END AS CONTRATO
FROM CONTRATOS;

In case ORIGEN is 'CONTR' i should sort by the highest CONTRATO and get the CONTRATO column.
In case ORIGEN is 'BKP' i should sort by different columns and get the CONTRATO column.

Finally, i should be able to have one unique row with CODIGO_ORIGEN -> CONTRATO (1:1).

Is there a simple way to do this (1 query)?

Thanks in advance!

Body:
Check if there is origen = 'CONT', use analytic count(). If yes - use analytic function with first ordering method, if no - second ordering:

select mgr_cuenta_ctl.*,
       case
       when count(case origen when 'CONT' then 1 end) over (partition by codigo_origen) > 0
       then first_value(contrato) over (
            partition by codigo_origen
            order by case origen when 'CONT' then 1 end, contrato desc)
       else first_value(contrato) over (
            partition by codigo_origen
            order by case origen when 'BKP' then 1 end, campo1 desc, campo2 desc, contrato desc)
       end as best
  from mgr_cuenta_ctl

If you want only grouped values, without details, remove partition by clauses:

select codigo_origen,
       case when count(case origen when 'CONT' then 1 end) > 0
       then max(contrato) keep (dense_rank first
                order by case origen when 'CONT' then 1 end, contrato desc)
       else max(contrato) keep (dense_rank first
                order by case origen when 'BKP' then 1 end, campo1 desc, campo2 desc)
       end as best
  from mgr_cuenta_ctl
  group by codigo_origen

dbfiddle demo

BTW. I tried to analyse your query, but it throwed some strange errors and I gave up. Here you touch table only once, no self-joins, so it should be faster.


问:
Best Way To Go About Caching Millions of Web Pages
I'm trying to come up with a somewhat simple solution to do a two week cache on millions of pages of content. The site in question is hitting MYSQL every time a page is hit some of the pages with more complex queries are taking 2-3 seconds load, My end goal is to get load times to under a second. I was thinking about using Memcached, but I would like to avoid this approach if possible. I basically would prefer a solution that crawls all the pages in question and automatically creates a fresh cache every two weeks. I'm open to all approaches including using a service. </p>

答:
Memcached or Redis are perfectly viable solutions to store "projected formats of data" that would require lots of JOINs, GROUP BYs, or ORDER BYs in MySQL.

However, even when accessing caches like Memcached or Redis, the code still has to be accessed. At high scale, for large amounts of data, the PHP runtime and your webserver can become a bottleneck.

Varnish to the rescue

You did mention the term pages, which implies you're actually trying to cache full pages instead of just data sets. In that case I would advise you to have a look at Varnish.

Varnish is a reverse caching proxy that is purposely built to caches pages at enormous scale. You can use a crawler to warm up the cache and you can leverage Cache-Control headers to control the Time To Live of objects in the cache.

Here's an example that sets the TTL for an HTTP response to 2 weeks:

Cache-Control: public, s-maxage=1209600

You can also set the TTL much higher, and then invalidate specific objects in the cache by purging them.

Caching millions of objects

Varnish is perfectly able to cache millions of objects, maybe even billions. The feasibility primarily depends on the size of your HTTP responses, and the amount of memory your system has.

By default Varnish stores its objects in memory. A configurable parameter in Varnish is the amount of memory that is allocated. You can easily allocate 80% of your system's memory to the Varnish process. The overhead of storing an object in cache is just 1 KB per object.

If your cached objects are just plain text, there should be no issue. If it's binary data (e.g.: images), then you can run out of memory quite quickly.

Running out of memory is not disastrous: an LRU mechanism will ensure that when the cache is full, the Least Recently Used objects are removed to clear space.

Conclusion

Varnish has become the de facto standard for page caching. The user guide on the website is a great resource to quickly learn how to setup and configure Varnish.


问:
Create an isometric projection tile for a tile map with Pixi JS?
I decided against using sprites and to create the tile dynamically with PIXI.Graphics, but I'm not sure where to start. I can create basic shapes like squares and rectangles but I need some help in a tile.

The closest I can get is this

```<code>var graphics = new PIXI.Graphics();

graphics.beginFill(0x989865);
graphics.lineStyle(1, 0x8E8E5E);
graphics.endFill();

graphics.drawRect(50, 50, 50, 50);

app.stage.addChild(graphics);
</code>```

Something like the image below is what I'm looking for

答:
This is my first attempt, made by trial and error (it seems to work as intended).

PIXI.utils.skipHello();

var app = new PIXI.Application({
    width: 800,
    height: 600,
    backgroundColor: 0x000000,
    antialias: true,
    autoDensity: true,
    resolution: 2
});

document.body.appendChild(app.view);

var stage = app.stage;

renderIsometricTile(stage, 20, 20, 50, 5, 0x989865, 0x767643, 0x545421);
renderIsometricTile(stage, 60, 40, 50, 5, 0x2A63FF, 0x0841DD, 0x0620AA);
renderIsometricTile(stage, 148, 39, 50, 5, 0x59CD90, 0x37AB70, 0x257750);
renderIsometricTile(stage, 200, 200, 150, 10, 0x3D3D8B, 0x1B1B6A, 0x1B1B48);
renderIsometricTile(stage, 100, 150, 75, 20, 0xFFD23F, 0xDDB01D, 0xBB7A0A);

function renderIsometricTile(stage, x, y, size, height, topColor, leftColor, rightColor) {
  var topSide = new PIXI.Graphics();

  topSide.beginFill(topColor);
  topSide.drawRect(0, 0, size, size);
  topSide.endFill();
  topSide.setTransform(x, y + size * 0.5, 1, 1, 0, 1.1, -0.5, 0, 0);

  var leftSide = new PIXI.Graphics();

  leftSide.beginFill(leftColor);
  leftSide.drawRect(0, 0, height, size);
  leftSide.endFill();
  leftSide.setTransform(x, y + size * 0.5, 1, 1, 0, 1.1, 1.57, 0, 0);

  var rightSide = new PIXI.Graphics();

  rightSide.beginFill(rightColor);
  rightSide.drawRect(0, 0, size, height);
  rightSide.endFill();
  rightSide.setTransform(x, y + size * 0.5, 1, 1, 0, -0.0, -0.5, -(size + (size * 0.015)), -(size - (size * 0.06)));

  stage.addChild(topSide);
  stage.addChild(leftSide);
  stage.addChild(rightSide);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.2.1/pixi.min.js"></script></code>```

Body:
I decided against using sprites and to create the tile dynamically with PIXI.Graphics, but I'm not sure where to start. I can create basic shapes like squares and rectangles but I need some help in a tile.

The closest I can get is this

var graphics = new PIXI.Graphics();

graphics.beginFill(0x989865);
graphics.lineStyle(1, 0x8E8E5E);
graphics.endFill();

graphics.drawRect(50, 50, 50, 50);

app.stage.addChild(graphics);

Something like the image below is what I'm looking for

Body:
This is my first attempt, made by trial and error (it seems to work as intended).

PIXI.utils.skipHello();

var app = new PIXI.Application({
    width: 800,
    height: 600,
    backgroundColor: 0x000000,
    antialias: true,
    autoDensity: true,
    resolution: 2
});

document.body.appendChild(app.view);

var stage = app.stage;

renderIsometricTile(stage, 20, 20, 50, 5, 0x989865, 0x767643, 0x545421);
renderIsometricTile(stage, 60, 40, 50, 5, 0x2A63FF, 0x0841DD, 0x0620AA);
renderIsometricTile(stage, 148, 39, 50, 5, 0x59CD90, 0x37AB70, 0x257750);
renderIsometricTile(stage, 200, 200, 150, 10, 0x3D3D8B, 0x1B1B6A, 0x1B1B48);
renderIsometricTile(stage, 100, 150, 75, 20, 0xFFD23F, 0xDDB01D, 0xBB7A0A);

function renderIsometricTile(stage, x, y, size, height, topColor, leftColor, rightColor) {
  var topSide = new PIXI.Graphics();

  topSide.beginFill(topColor);
  topSide.drawRect(0, 0, size, size);
  topSide.endFill();
  topSide.setTransform(x, y + size * 0.5, 1, 1, 0, 1.1, -0.5, 0, 0);

  var leftSide = new PIXI.Graphics();

  leftSide.beginFill(leftColor);
  leftSide.drawRect(0, 0, height, size);
  leftSide.endFill();
  leftSide.setTransform(x, y + size * 0.5, 1, 1, 0, 1.1, 1.57, 0, 0);

  var rightSide = new PIXI.Graphics();

  rightSide.beginFill(rightColor);
  rightSide.drawRect(0, 0, size, height);
  rightSide.endFill();
  rightSide.setTransform(x, y + size * 0.5, 1, 1, 0, -0.0, -0.5, -(size + (size * 0.015)), -(size - (size * 0.06)));

  stage.addChild(topSide);
  stage.addChild(leftSide);
  stage.addChild(rightSide);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.2.1/pixi.min.js"></script>


问:
Environment variable which contains spaces can not be used in command
I set an env var which contains spaces. I can output it correctly.

```<code>export dpath="/path/with/spaces/is here/clear"
echo $dpath
/path/with/spaces/is here/clear
</code>```

Now use the env var here:

```<code>sshpass -p 'xxxx' sftp -q -a -P22 -r "account@12.34.56.78:${dpath}" .
File "/path/with/spaces/is" not found.
</code>```

Now the space is ignored (and split). How can I fix this?

答:
To be able to make it not split we need quotes.
Try to store env var as:
export dpath='"/path/with/spaces/is here/clear"'

Use " inside '.

OR if you can't store export var in this way then try to use the double quotes around the variable in the scp command:
sshpass -p 'xxxx' sftp -q -a -P22 -r account@12.34.56.78:"${dpath}" .

Hope this helps

Body:
I set an env var which contains spaces. I can output it correctly.

export dpath="/path/with/spaces/is here/clear"
echo $dpath
/path/with/spaces/is here/clear

Now use the env var here:

sshpass -p 'xxxx' sftp -q -a -P22 -r "account@12.34.56.78:${dpath}" .
File "/path/with/spaces/is" not found.

Now the space is ignored (and split). How can I fix this?


问:
Is there any way to detect window layover on a browser?
I am working on a web-app which should do some function when the user moves away from that tab.
I managed to detect tab switching, and also browser switching through

```<code>window.addEventListener('visibilitychange', () => this.dothis())
</code>```

But still i can't detect if a user opens system-settings like preferences or settings, or any other built-in system tool. Is there a way to detect those?

答:
You can try if the blur event does what you need. It triggers when the active tab loses focus to another tab, another window or another application.

If needed, you can combine it with the focus event, which is triggered when the opposite happens (a non-focused tab gains focus).

```<code>window.addEventListener('blur', () => /* ... */ );

window.addEventListener('focus', () => /* ... */ );
</code>```

Body:
I am working on a web-app which should do some function when the user moves away from that tab.
I managed to detect tab switching, and also browser switching through

window.addEventListener('visibilitychange', () => this.dothis())

But still i can't detect if a user opens system-settings like preferences or settings, or any other built-in system tool. Is there a way to detect those?

Body:
You can try if the blur event does what you need. It triggers when the active tab loses focus to another tab, another window or another application.

If needed, you can combine it with the focus event, which is triggered when the opposite happens (a non-focused tab gains focus).

window.addEventListener('blur', () => /* ... */ );

window.addEventListener('focus', () => /* ... */ );


问:
CONCATENATE is not working in Excel VBA
Excel 16.0
Windows 10
Lenovo Z70-80
Intel(R) Core i7-5500U CPU @ 2.40 Ghz, 2401 Mhz, 2 Cores, 4 Logical

I am trying to use an excel GUID subroutine i found. It works perfect when used as a formula in a cell, but will not work when called as a Subroutine module.

```<code>= CONCATENATE(DEC2HEX(RANDBETWEEN(0, 4294967295), 8), "-", DEC2HEX(RANDBETWEEN(0, 42949), 4), "-", DEC2HEX(RANDBETWEEN(0, 42949), 4), "-", DEC2HEX(RANDBETWEEN(0, 42949), 4), "-", DEC2HEX(RANDBETWEEN(0, 4294967295), 8), DEC2HEX(RANDBETWEEN(0, 42949), 4))
</code>```

I have teased this apart and discovered the problem is the CONCATENATE function which gets a Run-time error '438': Object doesn't support this property or method.

I have both atpvbaen.xls and VBAProject Add-Ons installed. The add-ons show up checked under Tools References and they show up in the VBA Editor file explorer above my project folders.

Some of the add-on functions work such as Dec2Hex and RandBetween.

Calling from a SubRoutine

Works --> p = Application.WorksheetFunction.RandBetween(1, 999)

Works --> p = Application.WorksheetFunction.Dec2Hex(1234, 5)

NO Work --> p = Application.WorksheetFunction.CONCATENATE("-", "a")

As a Formula in a Cell

Works --> =CONCATENATE("-","a")

Works --> =CONCATENATE(8,"a")

Works --> =CONCATENATE((RANDBETWEEN(1, 999)),"XXX")

I have spent hours searching for help and testing and I would greatly appreciate some guidance.
Thanks - Gary

答:
CONCATENATE might not be a VBA function but CONCAT is:</p>

```<code>ConcatedCells = WorksheetFunction.Concat(range("A1:C1"))
</code>```

ContentLicense: CC BY-SA 3.0

Title: CONCATENATE is not working in Excel VBA

Body:
Excel 16.0
Windows 10
Lenovo Z70-80
Intel(R) Core i7-5500U CPU @ 2.40 Ghz, 2401 Mhz, 2 Cores, 4 Logical

I am trying to use an excel GUID subroutine i found. It works perfect when used as a formula in a cell, but will not work when called as a Subroutine module.

= CONCATENATE(DEC2HEX(RANDBETWEEN(0, 4294967295), 8), "-", DEC2HEX(RANDBETWEEN(0, 42949), 4), "-", DEC2HEX(RANDBETWEEN(0, 42949), 4), "-", DEC2HEX(RANDBETWEEN(0, 42949), 4), "-", DEC2HEX(RANDBETWEEN(0, 4294967295), 8), DEC2HEX(RANDBETWEEN(0, 42949), 4))

I have teased this apart and discovered the problem is the CONCATENATE function which gets a Run-time error '438': Object doesn't support this property or method.

I have both atpvbaen.xls and VBAProject Add-Ons installed. The add-ons show up checked under Tools References and they show up in the VBA Editor file explorer above my project folders.

Some of the add-on functions work such as Dec2Hex and RandBetween.

Calling from a SubRoutine

Works --> p = Application.WorksheetFunction.RandBetween(1, 999)

Works --> p = Application.WorksheetFunction.Dec2Hex(1234, 5)

NO Work --> p = Application.WorksheetFunction.CONCATENATE("-", "a")

As a Formula in a Cell

Works --> =CONCATENATE("-","a")

Works --> =CONCATENATE(8,"a")

Works --> =CONCATENATE((RANDBETWEEN(1, 999)),"XXX")

I have spent hours searching for help and testing and I would greatly appreciate some guidance.
Thanks - Gary

Body:
CONCATENATE might not be a VBA function but CONCAT is:

ConcatedCells = WorksheetFunction.Concat(range("A1:C1"))


问:
How to make Firebase database values only visible to their respective paired UIDs?
This is my database structure:

I want the values under the node of user 1 only readable and writable to user 1, and the values under the node of user 2 only readable and writable to user 2, and so on for other new users in the future. That means user 1 cannot read and write values under the nodes of other users and vise versa.For that I had to set up a rule for my database.

The rule below is what I tried. So far, User 1 can only write values under his own node and does not write under the nodes of other users, and vise versa, which is exactly what I want. Problem is user 1 can still read values under  the nodes of other users, which is undesirable. I read some documents explaining the database rules but this is very hard for me to understand. I tried multiple ways to rewrite my rule but still failed. I need help to fix this.

```<code>{
  "rules": {
    ".read": "auth.uid != null",
    ".write":"auth.uid != null",
    "Users' Input History": {
      "$user": {
      ".validate":"$user === auth.uid"
      }
    },

    "Users' Vocabulary List": {
      "$user": {
      ".validate":"$user === auth.uid"
      }
    }
  }
}
</code>```

For the record, I used the rule simulator, as in the following images. I toggeled on the "validated" option, selected "Google" as the provider, set simulated UID as "Kad06bqeNChhjaksxgP9cVtoFMh1" (which is user 1), and hit the execute button. The result was both "read" and "set" permitted at line 3 and 4 respectively.

Below is my code for user authentication and submitting values to the database:

GoogleSignInActivity:

```<code>public class GoogleSignInActivity extends BaseActivity implements
        View.OnClickListener {

    private static final String TAG = "GoogleActivity";
    private static final int RC_SIGN_IN = 9001;

    // [START declare_auth]
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    // [END declare_auth]

    private GoogleSignInClient mGoogleSignInClient;
    private TextView mStatusTextView; // For displaying user's email
    private TextView mDetailTextView; // For displaying user's UID
    private TextView mScreenNameTextView; // For displaying user's display name (user.getDisplayName())

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

        // Views
        mStatusTextView = findViewById(R.id.status);
        mDetailTextView = findViewById(R.id.detail);
        mScreenNameTextView = findViewById(R.id.screen_name_textView);

        setProgressBar(R.id.progressBar);

        // Button listeners
        findViewById(R.id.signInButton).setOnClickListener(this);

        // [START config_signin]
        // Configure Google Sign In
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        // [END config_signin]

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

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

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                    toastMessage("Successfully signed in with: " + user.getEmail());
                    mStatusTextView.setText(getString(R.string.Google_status_fmt, user.getEmail()));
                    mDetailTextView.setText(getString(R.string.Firebase_status_fmt, user.getUid()));

                            username = mDetailTextView.getText().toString();

                }
            }
        };

    }

    // [START on_start_check_user]
    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
        // Check if user is signed in (non-null).
        FirebaseUser currentUser = mAuth.getCurrentUser();
    }
    // [END on_start_check_user]

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    // [START onActivityResult]
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);
                firebaseAuthWithGoogle(account);

                Toast.makeText(getApplicationContext(), getResources().getString(R.string.Login_successful), Toast.LENGTH_LONG).show();

                        username = mDetailTextView.getText().toString();

            } catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
                Log.w(TAG, "Google sign in failed", e);
            }
        }
    }
    // [END onActivityResult]

    // [START auth_with_google]
    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
        // [START_EXCLUDE silent]
        showProgressBar();
        // [END_EXCLUDE]

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .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, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
                        }

                        // [START_EXCLUDE]
                        hideProgressBar();
                        // [END_EXCLUDE]
                    }
                });
    }
    // [END auth_with_google]

    // [START signin]
    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
    // [END signin]

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.signInButton) {
            signIn();
        }

    }

}
</code>```

My code for pushing values to the database:

```<code>EditText wordInputView;
String searchKeyword;
String username;

public static DatabaseReference mRootReference = FirebaseDatabase.getInstance().getReference();
    public static DatabaseReference mChildReferenceForInputHistory = mRootReference.child("Users' Input History");
    public static DatabaseReference mChildReferenceForVocabularyList = mRootReference.child("Users' Vocabulary List");

searchKeyword = wordInputView.getText().toString();

Query query = mChildReferenceForInputHistory.child(username).orderByValue().equalTo(searchKeyword);

                query.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                            //If a duplicate value (searchKeyword) is found, remove it.
                            snapshot.getRef().setValue(null);
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {
                        throw databaseError.toException();
                    }
                });

                mChildReferenceForInputHistory.child(username).push().setValue(searchKeyword);

//Initialize the adapter
        userInputArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, userInputArraylist);
        userInputListview.setAdapter(userInputArrayAdapter);
        mChildReferenceForInputHistory.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String previousChildKey) {

                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    String value = snapshot.getValue(String.class);

                    userInputArraylist.add(value);

                    HashSet<String> myVocabularyArraylistHashSet = new HashSet<>();
                    myVocabularyArraylistHashSet.addAll(userInputArraylist);
                    userInputArraylist.clear();
                    userInputArraylist.addAll(myVocabularyArraylistHashSet);

                    //Alphabetic sorting
                    Collections.sort(userInputArraylist);

                    userInputArrayAdapter.notifyDataSetChanged();

                }
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });
</code>```

答:
From the Firebase documentation:

If a rule grants read or write permissions at a particular path, then it also grants access to all child nodes under it.

In your case you are giving .read permissions to all users that are authenticated, because this part:

```<code>  "rules": {
".read": "auth.uid != null",
".write":"auth.uid != null",
</code>```

... gives read permissions to everyone that is authenticated and because this is your route directory they also give them permissions to read "Users' Input History" and "Users' Vocabulary List" because this are under your route.

The .validate rules are used only when you are writing data and they define what the data should be.
Back to your question, in your usecase you should reconsider restructuring your database and setting new rules.
One possible solution is setting these rules:

```<code>{
  "rules": {
    "Users' Input History": {
      "$user": {
            ".read": "auth.uid  === $user",
              ".write": "auth.uid  === $user"
      }
    },

    "Users' Vocabulary List": {
      "$user": {
            ".read": "auth.uid  === $user",
              ".write": "auth.uid  === $user"
      }
    }
  }
}
</code>```

In this case you give permissions to the user 111 to read and write only "/Users' Input History/111" and "/Users' Vocabulary List/111" so if you have more childs under root you must define rules for each one of them.

Body:
This is my database structure:

I want the values under the node of user 1 only readable and writable to user 1, and the values under the node of user 2 only readable and writable to user 2, and so on for other new users in the future. That means user 1 cannot read and write values under the nodes of other users and vise versa.For that I had to set up a rule for my database.

The rule below is what I tried. So far, User 1 can only write values under his own node and does not write under the nodes of other users, and vise versa, which is exactly what I want. Problem is user 1 can still read values under  the nodes of other users, which is undesirable. I read some documents explaining the database rules but this is very hard for me to understand. I tried multiple ways to rewrite my rule but still failed. I need help to fix this.

{
  "rules": {
    ".read": "auth.uid != null",
    ".write":"auth.uid != null",
    "Users' Input History": {
      "$user": {
      ".validate":"$user === auth.uid"
      }
    },

    "Users' Vocabulary List": {
      "$user": {
      ".validate":"$user === auth.uid"
      }
    }
  }
}

For the record, I used the rule simulator, as in the following images. I toggeled on the "validated" option, selected "Google" as the provider, set simulated UID as "Kad06bqeNChhjaksxgP9cVtoFMh1" (which is user 1), and hit the execute button. The result was both "read" and "set" permitted at line 3 and 4 respectively.

Below is my code for user authentication and submitting values to the database:

GoogleSignInActivity:

public class GoogleSignInActivity extends BaseActivity implements
        View.OnClickListener {

    private static final String TAG = "GoogleActivity";
    private static final int RC_SIGN_IN = 9001;

    // [START declare_auth]
    private FirebaseAuth mAuth;
    private FirebaseAuth.AuthStateListener mAuthListener;
    // [END declare_auth]

    private GoogleSignInClient mGoogleSignInClient;
    private TextView mStatusTextView; // For displaying user's email
    private TextView mDetailTextView; // For displaying user's UID
    private TextView mScreenNameTextView; // For displaying user's display name (user.getDisplayName())

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

        // Views
        mStatusTextView = findViewById(R.id.status);
        mDetailTextView = findViewById(R.id.detail);
        mScreenNameTextView = findViewById(R.id.screen_name_textView);

        setProgressBar(R.id.progressBar);

        // Button listeners
        findViewById(R.id.signInButton).setOnClickListener(this);

        // [START config_signin]
        // Configure Google Sign In
        GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestIdToken(getString(R.string.default_web_client_id))
                .requestEmail()
                .build();
        // [END config_signin]

        mGoogleSignInClient = GoogleSignIn.getClient(this, gso);

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

        mAuthListener = new FirebaseAuth.AuthStateListener() {
            @Override
            public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
                FirebaseUser user = firebaseAuth.getCurrentUser();
                if (user != null) {
                    // User is signed in
                    Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
                    toastMessage("Successfully signed in with: " + user.getEmail());
                    mStatusTextView.setText(getString(R.string.Google_status_fmt, user.getEmail()));
                    mDetailTextView.setText(getString(R.string.Firebase_status_fmt, user.getUid()));

                            username = mDetailTextView.getText().toString();

                }
            }
        };

    }

    // [START on_start_check_user]
    @Override
    public void onStart() {
        super.onStart();
        mAuth.addAuthStateListener(mAuthListener);
        // Check if user is signed in (non-null).
        FirebaseUser currentUser = mAuth.getCurrentUser();
    }
    // [END on_start_check_user]

    @Override
    public void onStop() {
        super.onStop();
        if (mAuthListener != null) {
            mAuth.removeAuthStateListener(mAuthListener);
        }
    }

    // [START onActivityResult]
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // Result returned from launching the Intent from GoogleSignInApi.getSignInIntent(...);
        if (requestCode == RC_SIGN_IN) {
            Task<GoogleSignInAccount> task = GoogleSignIn.getSignedInAccountFromIntent(data);
            try {
                // Google Sign In was successful, authenticate with Firebase
                GoogleSignInAccount account = task.getResult(ApiException.class);
                firebaseAuthWithGoogle(account);

                Toast.makeText(getApplicationContext(), getResources().getString(R.string.Login_successful), Toast.LENGTH_LONG).show();

                        username = mDetailTextView.getText().toString();

            } catch (ApiException e) {
                // Google Sign In failed, update UI appropriately
                Log.w(TAG, "Google sign in failed", e);
            }
        }
    }
    // [END onActivityResult]

    // [START auth_with_google]
    private void firebaseAuthWithGoogle(GoogleSignInAccount acct) {
        Log.d(TAG, "firebaseAuthWithGoogle:" + acct.getId());
        // [START_EXCLUDE silent]
        showProgressBar();
        // [END_EXCLUDE]

        AuthCredential credential = GoogleAuthProvider.getCredential(acct.getIdToken(), null);
        mAuth.signInWithCredential(credential)
                .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, "signInWithCredential:success");
                            FirebaseUser user = mAuth.getCurrentUser();
                        } else {
                            // If sign in fails, display a message to the user.
                            Log.w(TAG, "signInWithCredential:failure", task.getException());
                            Snackbar.make(findViewById(R.id.main_layout), "Authentication Failed.", Snackbar.LENGTH_SHORT).show();
                        }

                        // [START_EXCLUDE]
                        hideProgressBar();
                        // [END_EXCLUDE]
                    }
                });
    }
    // [END auth_with_google]

    // [START signin]
    private void signIn() {
        Intent signInIntent = mGoogleSignInClient.getSignInIntent();
        startActivityForResult(signInIntent, RC_SIGN_IN);
    }
    // [END signin]

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.signInButton) {
            signIn();
        }

    }

}

My code for pushing values to the database:

EditText wordInputView;
String searchKeyword;
String username;

public static DatabaseReference mRootReference = FirebaseDatabase.getInstance().getReference();
    public static DatabaseReference mChildReferenceForInputHistory = mRootReference.child("Users' Input History");
    public static DatabaseReference mChildReferenceForVocabularyList = mRootReference.child("Users' Vocabulary List");

searchKeyword = wordInputView.getText().toString();

Query query = mChildReferenceForInputHistory.child(username).orderByValue().equalTo(searchKeyword);

                query.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        for (DataSnapshot snapshot: dataSnapshot.getChildren()) {
                            //If a duplicate value (searchKeyword) is found, remove it.
                            snapshot.getRef().setValue(null);
                        }
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {
                        throw databaseError.toException();
                    }
                });

                mChildReferenceForInputHistory.child(username).push().setValue(searchKeyword);

//Initialize the adapter
        userInputArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, userInputArraylist);
        userInputListview.setAdapter(userInputArrayAdapter);
        mChildReferenceForInputHistory.addChildEventListener(new ChildEventListener() {
            @Override
            public void onChildAdded(@NonNull DataSnapshot dataSnapshot, @Nullable String previousChildKey) {

                for (DataSnapshot snapshot : dataSnapshot.getChildren()){
                    String value = snapshot.getValue(String.class);

                    userInputArraylist.add(value);

                    HashSet<String> myVocabularyArraylistHashSet = new HashSet<>();
                    myVocabularyArraylistHashSet.addAll(userInputArraylist);
                    userInputArraylist.clear();
                    userInputArraylist.addAll(myVocabularyArraylistHashSet);

                    //Alphabetic sorting
                    Collections.sort(userInputArraylist);

                    userInputArrayAdapter.notifyDataSetChanged();

                }
            }

            @Override
            public void onChildChanged(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            }

            @Override
            public void onChildRemoved(@NonNull DataSnapshot dataSnapshot) {
            }

            @Override
            public void onChildMoved(@NonNull DataSnapshot dataSnapshot, @Nullable String s) {
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
            }
        });

Body:
From the Firebase documentation:

If a rule grants read or write permissions at a particular path, then it also grants access to all child nodes under it.

In your case you are giving .read permissions to all users that are authenticated, because this part:

  "rules": {
".read": "auth.uid != null",
".write":"auth.uid != null",

... gives read permissions to everyone that is authenticated and because this is your route directory they also give them permissions to read "Users' Input History" and "Users' Vocabulary List" because this are under your route.

The .validate rules are used only when you are writing data and they define what the data should be.
Back to your question, in your usecase you should reconsider restructuring your database and setting new rules.
One possible solution is setting these rules:

{
  "rules": {
    "Users' Input History": {
      "$user": {
            ".read": "auth.uid  === $user",
              ".write": "auth.uid  === $user"
      }
    },

    "Users' Vocabulary List": {
      "$user": {
            ".read": "auth.uid  === $user",
              ".write": "auth.uid  === $user"
      }
    }
  }
}

In this case you give permissions to the user 111 to read and write only "/Users' Input History/111" and "/Users' Vocabulary List/111" so if you have more childs under root you must define rules for each one of them.


问:
declaring a variable blocks my code
is something wrong here?
declaring those variables stops the execution of my code :(

```<code>var color = $('fieldset input[type=checkbox]').data("color");
        if(color === orange){var bgy = '-1'}
        else{var bgy = '-37'};
</code>```

If you need more info please ask me :)

答: Define bgy outside the if block and just set the value inside.</p>

Title: declaring a variable blocks my code

Body:
is something wrong here?
declaring those variables stops the execution of my code :(

var color = $('fieldset input[type=checkbox]').data("color");
        if(color === orange){var bgy = '-1'}
        else{var bgy = '-37'};

If you need more info please ask me :)


问:
Regular delegate and ProxyDelegate RxSwift
I'm new to RxSwift and trying to implement this framework https://github.com/rubygarage/collection-view-layouts into my project.

So far I've got this:

```<code>extension BaseLayout: HasDelegate {
    public typealias Delegate = LayoutDelegate
}

class RxLayoutDelegateDelegateProxy: DelegateProxy<BaseLayout, LayoutDelegate>, DelegateProxyType, LayoutDelegate {
    public weak private(set) var baseLayout: BaseLayout?

    public init(baseLayout: ParentObject) {
        self.baseLayout = baseLayout
        super.init(parentObject: baseLayout,
                   delegateProxy: RxLayoutDelegateDelegateProxy.self)
    }

    static func registerKnownImplementations() {
        self.register { RxLayoutDelegateDelegateProxy(baseLayout: $0) }
    }
}

extension Reactive where Base: BaseLayout {

    public var delegate: DelegateProxy<BaseLayout, LayoutDelegate> {
        return RxLayoutDelegateDelegateProxy.proxy(for: base)
    }

    var cellSize: ControlEvent<CGSize> {

    }
}
</code>```

But still can't figure out how I can pass image size once I've got pics. Can anyone help, please?
Thanks!

答:
You were close. Because the delegate method returns a value, you have to implement it more like the items function in the UITableView reactive extension. Something like this:

```<code>extension BaseLayout: HasDelegate {
    public typealias Delegate = LayoutDelegate
}

class LayoutDelegateProxy
    : DelegateProxy<BaseLayout, LayoutDelegate>
    , DelegateProxyType
    , LayoutDelegate {

    init(parentObject: BaseLayout) {
        super.init(parentObject: parentObject, delegateProxy: LayoutDelegateProxy.self)
    }

    deinit {
        _cellSize.onCompleted()
    }

    public static func registerKnownImplementations() {
        self.register { LayoutDelegateProxy(parentObject: $0) }
    }

    func cellSize(indexPath: IndexPath) -> CGSize {
        return (try? _cellSize.value())?[indexPath] ?? CGSize.zero
    }

    fileprivate let _cellSize = BehaviorSubject<[IndexPath: CGSize]>(value: [:])
}

extension Reactive where Base: BaseLayout {
    var delegate: LayoutDelegateProxy {
        return LayoutDelegateProxy.proxy(for: base)
    }

    func items<Source: ObservableType>(_ source: Source) -> Disposable where Source.Element == [IndexPath: CGSize] {
        return source
            .bind(to: delegate._cellSize)
    }
}
</code>```

An example of use:

```<code>let sizes = Observable<[IndexPath: CGSize]>.just([
    IndexPath(item: 0, section: 0): CGSize(width:  50, height:  50),
    IndexPath(item: 1, section: 0): CGSize(width: 100, height:  50),
    IndexPath(item: 2, section: 0): CGSize(width:  50, height: 100)
])

sizes
    .bind(to: baseLayout.rx.items)
    .disposed(by: disposeBag)
</code>```

Body:
I'm new to RxSwift and trying to implement this framework https://github.com/rubygarage/collection-view-layouts into my project.

So far I've got this:

extension BaseLayout: HasDelegate {
    public typealias Delegate = LayoutDelegate
}

class RxLayoutDelegateDelegateProxy: DelegateProxy<BaseLayout, LayoutDelegate>, DelegateProxyType, LayoutDelegate {
    public weak private(set) var baseLayout: BaseLayout?

    public init(baseLayout: ParentObject) {
        self.baseLayout = baseLayout
        super.init(parentObject: baseLayout,
                   delegateProxy: RxLayoutDelegateDelegateProxy.self)
    }

    static func registerKnownImplementations() {
        self.register { RxLayoutDelegateDelegateProxy(baseLayout: $0) }
    }
}

extension Reactive where Base: BaseLayout {

    public var delegate: DelegateProxy<BaseLayout, LayoutDelegate> {
        return RxLayoutDelegateDelegateProxy.proxy(for: base)
    }

    var cellSize: ControlEvent<CGSize> {

    }
}

But still can't figure out how I can pass image size once I've got pics. Can anyone help, please?
Thanks!

Body:
You were close. Because the delegate method returns a value, you have to implement it more like the items function in the UITableView reactive extension. Something like this:

extension BaseLayout: HasDelegate {
    public typealias Delegate = LayoutDelegate
}

class LayoutDelegateProxy
    : DelegateProxy<BaseLayout, LayoutDelegate>
    , DelegateProxyType
    , LayoutDelegate {

    init(parentObject: BaseLayout) {
        super.init(parentObject: parentObject, delegateProxy: LayoutDelegateProxy.self)
    }

    deinit {
        _cellSize.onCompleted()
    }

    public static func registerKnownImplementations() {
        self.register { LayoutDelegateProxy(parentObject: $0) }
    }

    func cellSize(indexPath: IndexPath) -> CGSize {
        return (try? _cellSize.value())?[indexPath] ?? CGSize.zero
    }

    fileprivate let _cellSize = BehaviorSubject<[IndexPath: CGSize]>(value: [:])
}

extension Reactive where Base: BaseLayout {
    var delegate: LayoutDelegateProxy {
        return LayoutDelegateProxy.proxy(for: base)
    }

    func items<Source: ObservableType>(_ source: Source) -> Disposable where Source.Element == [IndexPath: CGSize] {
        return source
            .bind(to: delegate._cellSize)
    }
}

An example of use:

let sizes = Observable<[IndexPath: CGSize]>.just([
    IndexPath(item: 0, section: 0): CGSize(width:  50, height:  50),
    IndexPath(item: 1, section: 0): CGSize(width: 100, height:  50),
    IndexPath(item: 2, section: 0): CGSize(width:  50, height: 100)
])

sizes
    .bind(to: baseLayout.rx.items)
    .disposed(by: disposeBag)


问:
Get AVR with gcc running on fedora
im trying to solve this issue for a few days now and i cant find any solution.
I got myself an Atmega88A and i want to program it on fedora.
I tried to program C with gcc and that went well. But as i tried to include the avr/io.h, i always get the failure that it didnt found anything. I tried to get the new version of gcc, but that gives me an error too. Would it be enough to just download the avr/io.h library and implement it somewhere in my files? or is there any way to download this all together, including also all the other libraries that i need (e.g. util/delay.h)</p>

答:
What fixed this problem for me was this missing package: avr-gcc-c++. Running the command:

```<code>dnf install avr-gcc-c++
</code>```

fixed it.

Title: Get AVR with gcc running on fedora

Body:
What fixed this problem for me was this missing package: avr-gcc-c++. Running the command:

dnf install avr-gcc-c++

fixed it.


问:
Text goes out of screen in recycler view item
I have an item.xml being used in a recycler view, but the text goes out of the screen. I tried to rely on this answer,

You can avoid all of this by giving each textview a width of match_parent and an appropriate layout_weight.

but I find it confusing as I'm not sure where the

```<code>width="0"
</code>```

should be implemented.

My item.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/productLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginBottom="@dimen/product_recycler_view_margin">

    <ImageView
        android:id="@+id/photoIV"
        android:layout_width="@dimen/product_image_size"
        android:layout_height="@dimen/product_image_size"
        android:scaleType="centerCrop"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="@dimen/product_image_size"
        android:orientation="vertical"
        android:gravity="top"
        android:layout_marginStart="@dimen/product_details_margin_left"
        app:layout_constraintStart_toEndOf="@+id/photoIV"
        app:layout_constraintTop_toTopOf="@id/photoIV">

        <TextView
            android:id="@+id/titleTV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Top"

            android:textStyle="bold"
            android:textSize="@dimen/product_details_title" />

        <TextView
            android:id="@+id/descriptionTV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/product_details_margin_middle"
            android:text="Bottom"
            android:textSize="@dimen/product_details_description_text_size" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>
</code>```

There is an image and on its right, a title and description. Both the title and description go out of the screen:

My recycler view in my fragment where it's being displayed (if it matters):

```<code><androidx.recyclerview.widget.RecyclerView
    android:id="@+id/productsRV"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"
    android:layout_marginTop="16dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>
</code>```

答:
Problem is, you only defined the left constraints of your LinearLayout, but not the right constraints.

So you need to add the right constraint. Also you need to replace your width here with 0dp, as 0 means "match constraints" in this context.

```<code><LinearLayout
    android:layout_width="0dp"
    android:layout_height="@dimen/product_image_size"
    android:orientation="vertical"
    android:gravity="top"
    android:layout_marginStart="@dimen/product_details_margin_left"
    app:layout_constraintStart_toEndOf="@+id/photoIV"
    app:layout_constraintTop_toTopOf="@id/photoIV"
    app:layout_constraintEnd_toEndOf="parent">
</code>```

// EDIT: match_parent as width and height identifiers are not supported by ConstraintsLayouts at all.

Body:
I have an item.xml being used in a recycler view, but the text goes out of the screen. I tried to rely on this answer,

You can avoid all of this by giving each textview a width of match_parent and an appropriate layout_weight.

but I find it confusing as I'm not sure where the

width="0"

should be implemented.

My item.xml:

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/productLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginBottom="@dimen/product_recycler_view_margin">

    <ImageView
        android:id="@+id/photoIV"
        android:layout_width="@dimen/product_image_size"
        android:layout_height="@dimen/product_image_size"
        android:scaleType="centerCrop"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="@dimen/product_image_size"
        android:orientation="vertical"
        android:gravity="top"
        android:layout_marginStart="@dimen/product_details_margin_left"
        app:layout_constraintStart_toEndOf="@+id/photoIV"
        app:layout_constraintTop_toTopOf="@id/photoIV">

        <TextView
            android:id="@+id/titleTV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Top"

            android:textStyle="bold"
            android:textSize="@dimen/product_details_title" />

        <TextView
            android:id="@+id/descriptionTV"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="@dimen/product_details_margin_middle"
            android:text="Bottom"
            android:textSize="@dimen/product_details_description_text_size" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

There is an image and on its right, a title and description. Both the title and description go out of the screen:

My recycler view in my fragment where it's being displayed (if it matters):

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/productsRV"
    android:layout_marginStart="16dp"
    android:layout_marginEnd="16dp"
    android:layout_marginTop="16dp"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

Body:
Problem is, you only defined the left constraints of your LinearLayout, but not the right constraints.

So you need to add the right constraint. Also you need to replace your width here with 0dp, as 0 means "match constraints" in this context.

<LinearLayout
    android:layout_width="0dp"
    android:layout_height="@dimen/product_image_size"
    android:orientation="vertical"
    android:gravity="top"
    android:layout_marginStart="@dimen/product_details_margin_left"
    app:layout_constraintStart_toEndOf="@+id/photoIV"
    app:layout_constraintTop_toTopOf="@id/photoIV"
    app:layout_constraintEnd_toEndOf="parent">

// EDIT: match_parent as width and height identifiers are not supported by ConstraintsLayouts at all.


问:
useState hook not initialising with correct value: Array
I am passing an array 'defaults' into my panel component and then trying to set state hook 'selected option' to be equal to it. For some reason, the hook is setting an empty array instead.

component:

```<code>const Panel = ({ title, inputs, datepicker, identifiers, apiBase, isins, defaults = [], notes = "" }) => {
    const [expand, setExpand] = useState(false);
    const [date, setDate] = useState(new Date());
    const [selectedOption, setSelectedOption] = useState([...defaults]);
    const [dataError, setDataError] = useState(false);
    const [errorMsg, setErrorMsg] = useState('');
    const [errorCheckLoading, setErrorCheckLoading] = useState(false);

    const toggleExpand = () => {
        setExpand(!expand);
        console.log(defaults);
        console.log(selectedOption);
    };
</code>```

Just for testing, I have a couple of console logs in my toggle expand function so I can test the data passed in against the data set.

Output from console logs:

```<code>>(48) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
>[]
</code>```

So I know the data comes in ok, just that it doesn't set in the hook.

I have also tried giving the hook initial values of defaults, and  [defaults].

Now drawing a blank - any ideas?

Edit: this is the parent component supplying the defaults:

```<code>const Parent = () => {

    const [all, setAll] = useState([]);
    const [allLoadFailed, setAllLoadFailed] = useState(false);

    const [defaults, setDefaults] = useState([]);
    const [defaultsLoadFailed, setDefaultsLoadFailed] = useState(false);

    useEffect(() => { loadData()}, []);
    useEffect(() => { loadDefaultData()}, []);

    const loadDefaultData = async () => {
        try {
            let defaultData = await GetDefaults();
            setDefaults(defaultData.map(item => item = {value: item, label: item}));
        } catch (_) {
            setDefaultsLoadFailed(true);
        }
    };

    const loadData = async () => {
        try {
            let iData = await GetAll();
            let filteredIData = iData.filter(item => item);
            setAll(filteredIData.map(item => item = {value: item, label: item}));
        } catch (_) {
            setAllLoadFailed(true);
        }
    };

    return (

            <Panel
                title="Test"
                isins={all}
                defaults={defaults}
                inputs
                datepicker
                identifiers
                apiBase=""
                notes="not yet complete"
                key="2"
            />
    );
</code>```

答:
I'm guessing here that defaults is a value from api call?

This happens because in the initial render defaults = [] and useState's first parameter only get the initial value, so when default change to the correct data in the second render, the useState already have the [] value.

What you should do is use useEffect hook when defaults change and set selectedOption.

```<code>useEffect(() => {
    setSelectedOption([...defaults])
}, [defaults, setSelectedOption])
</code>```

Body:
I am passing an array 'defaults' into my panel component and then trying to set state hook 'selected option' to be equal to it. For some reason, the hook is setting an empty array instead.

component:

const Panel = ({ title, inputs, datepicker, identifiers, apiBase, isins, defaults = [], notes = "" }) => {
    const [expand, setExpand] = useState(false);
    const [date, setDate] = useState(new Date());
    const [selectedOption, setSelectedOption] = useState([...defaults]);
    const [dataError, setDataError] = useState(false);
    const [errorMsg, setErrorMsg] = useState('');
    const [errorCheckLoading, setErrorCheckLoading] = useState(false);

    const toggleExpand = () => {
        setExpand(!expand);
        console.log(defaults);
        console.log(selectedOption);
    };

Just for testing, I have a couple of console logs in my toggle expand function so I can test the data passed in against the data set.

Output from console logs:

>(48) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…},
 {…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]
>[]

So I know the data comes in ok, just that it doesn't set in the hook.

I have also tried giving the hook initial values of defaults, and  [defaults].

Now drawing a blank - any ideas?

Edit: this is the parent component supplying the defaults:

const Parent = () => {

    const [all, setAll] = useState([]);
    const [allLoadFailed, setAllLoadFailed] = useState(false);

    const [defaults, setDefaults] = useState([]);
    const [defaultsLoadFailed, setDefaultsLoadFailed] = useState(false);

    useEffect(() => { loadData()}, []);
    useEffect(() => { loadDefaultData()}, []);

    const loadDefaultData = async () => {
        try {
            let defaultData = await GetDefaults();
            setDefaults(defaultData.map(item => item = {value: item, label: item}));
        } catch (_) {
            setDefaultsLoadFailed(true);
        }
    };

    const loadData = async () => {
        try {
            let iData = await GetAll();
            let filteredIData = iData.filter(item => item);
            setAll(filteredIData.map(item => item = {value: item, label: item}));
        } catch (_) {
            setAllLoadFailed(true);
        }
    };

    return (

            <Panel
                title="Test"
                isins={all}
                defaults={defaults}
                inputs
                datepicker
                identifiers
                apiBase=""
                notes="not yet complete"
                key="2"
            />
    );

Body:
I'm guessing here that defaults is a value from api call?

This happens because in the initial render defaults = [] and useState's first parameter only get the initial value, so when default change to the correct data in the second render, the useState already have the [] value.

What you should do is use useEffect hook when defaults change and set selectedOption.

useEffect(() => {
    setSelectedOption([...defaults])
}, [defaults, setSelectedOption])


问:
Template or abstract base class?
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

```<code>class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};
</code>```

Version 2a: Template

```<code>template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};
</code>```

Version 2b: Template and private inheritance

```<code>template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};
</code>```

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

答: Templates are a way to let a class use a variable of which you don't really care about the type.  Inheritance is a way to define what a class is based on its attributes.  Its the "is-a" versus "has-a" question.  </p>

ContentLicense: CC BY-SA 2.5

Title: Template or abstract base class?

Body:
If I want to make a class adaptable, and make it possible to select different algorithms from the outside -- what is the best implementation in C++?

I see mainly two possibilities:

Use an abstract base class and pass concrete object in

Use a template

Here is a little example, implemented in the various versions:

Version 1: Abstract base class

class Brake {
public: virtual void stopCar() = 0;
};

class BrakeWithABS : public Brake {
public: void stopCar() { ... }
};

class Car {
  Brake* _brake;
public:
  Car(Brake* brake) : _brake(brake) { brake->stopCar(); }
};

Version 2a: Template

template<class Brake>
class Car {
  Brake brake;
public:
  Car(){ brake.stopCar(); }
};

Version 2b: Template and private inheritance

template<class Brake>
class Car : private Brake {
  using Brake::stopCar;
public:
  Car(){ stopCar(); }
};

Coming from Java, I am naturally inclined to always use version 1, but the templates versions seem to be preferred often, e.g. in STL code? If that's true, is it just because of memory efficiency etc (no inheritance, no virtual function calls)?

I realize there is not a big difference between version 2a and 2b, see C++ FAQ.

Can you comment on these possibilities?

OwnerDisplayName: John Ellinwood


问:
Convert mm/dd/yyyy to yyyy-mm-dd
I need to convert a date like this, 03/07/2016 to a date format like, 2016-03-07.

How can I do this using javascript or jquery?

答:
Please follow the below method. The trick is to use the unshift property. </p>

```<code>function formatDate(__d){
    if(__d.indexOf('/')){
      var a = __d.split('/')
      var b = a.pop()
      a.unshift(b)
   }
  return a.join('-')
}
</code>```

Title: Convert mm/dd/yyyy to yyyy-mm-dd

Body:
Please follow the below method. The trick is to use the unshift property.

function formatDate(__d){
    if(__d.indexOf('/')){
      var a = __d.split('/')
      var b = a.pop()
      a.unshift(b)
   }
  return a.join('-')
}


问:
How to display a derivative
Not sure this is the correct section of this site,but I have a question.

So,i`m using MathNet.Numerics to calculate a derivatives. I want to display them in console.

Code example

```<code>using System;
using MathNet.Numerics;

namespace math
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Func<double,double> f = x => 3 * Math.Pow(x, 3) + 2 * x - 6;
            var test = Differentiate.DerivativeFunc(f, 1);
            Console.WriteLine(test.ToString());
            Console.ReadKey();
        }
    }
}
</code>```

答:
Question

Let me reword your problem to make sure I understand and answer you correctly: Given the function 3x³ + 2x - 6 you would like to print in the console the equation of the derivative 9x² + 2

The library Math.NET Numerics can't do that

This library does calculation. It does not try to construct the equation of the derivative.

Look: Differentiate.DerivativeFunc method returns a C# method Func<double, double> that takes a double as parameter, and returns a double as the result. This signature makes it impossible to retrieve the equation of f'. Go deeper in the code and see that the library is all about computing results with an approximation.

However Math.NET Symbolics can

https://symbolics.mathdotnet.com/ is what you are looking for. I wrote the following code:

```<code>// using System;
// using MathNet.Symbolics;
// using Expr = MathNet.Symbolics.SymbolicExpression;

var x = Expr.Variable("x");
var func = 3 * (x * x * x) + 2 * x - 6;
Console.WriteLine("f(x) = " + func.ToString());

var derivative = func.Differentiate(x);
Console.WriteLine("f'(x) = " + derivative.ToString());
</code>```

which prints in the console:

f(x) = -6 + 2*x + 3*x^3

f'(x) = 2 + 9*x^2

Title: How to display a derivative

Body:
Not sure this is the correct section of this site,but I have a question.

So,i`m using MathNet.Numerics to calculate a derivatives. I want to display them in console.

Code example

using System;
using MathNet.Numerics;

namespace math
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            Func<double,double> f = x => 3 * Math.Pow(x, 3) + 2 * x - 6;
            var test = Differentiate.DerivativeFunc(f, 1);
            Console.WriteLine(test.ToString());
            Console.ReadKey();
        }
    }
}

Body:
Question

Let me reword your problem to make sure I understand and answer you correctly: Given the function 3x³ + 2x - 6 you would like to print in the console the equation of the derivative 9x² + 2

The library Math.NET Numerics can't do that

This library does calculation. It does not try to construct the equation of the derivative.

Look: Differentiate.DerivativeFunc method returns a C# method Func<double, double> that takes a double as parameter, and returns a double as the result. This signature makes it impossible to retrieve the equation of f'. Go deeper in the code and see that the library is all about computing results with an approximation.

However Math.NET Symbolics can

https://symbolics.mathdotnet.com/ is what you are looking for. I wrote the following code:

// using System;
// using MathNet.Symbolics;
// using Expr = MathNet.Symbolics.SymbolicExpression;

var x = Expr.Variable("x");
var func = 3 * (x * x * x) + 2 * x - 6;
Console.WriteLine("f(x) = " + func.ToString());

var derivative = func.Differentiate(x);
Console.WriteLine("f'(x) = " + derivative.ToString());

which prints in the console:

f(x) = -6 + 2*x + 3*x^3

f'(x) = 2 + 9*x^2


答:
Did you mean color=='orange'?

If it didn't help please alert the value of color.

Title: declaring a variable blocks my code


问:
Jmeter tool create request..cannot handle array parameters and dynamically created parameters
I'm having 2 issues when trying to do the create api requests using the jmeter tool

1). How to handle an array parameter. "Versions": "$[Versions]"

getting the following error message

{"timestamp":"2020-02-14T07:18:33.720+0000","status":400,"error":"Bad
  Request","message":"JSON parse error: Cannot deserialize instance of
  java.util.ArrayList<java.lang.Object> out of VALUE_STRING token;
  nested exception is
  com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
  deserialize instance of java.util.ArrayList<java.lang.Object> out of
  VALUE_STRING token\n at [Source: (PushbackInputStream); line: 15,
  column: 22]

2). how to handle dynamically created time stamp parameter createtime: "${createtime}"

getting the following error message

{"timestamp":"2020-02-14T07:17:58.942+0000","status":400,"error":"Bad
  Request","message":"JSON parse error: Cannot deserialize value of type
  java.time.OffsetDateTime from String \"${factoryCompleteTime}\":
  Failed to deserialize java.time.OffsetDateTime:
  (java.time.format.DateTimeParseException) Text
  '${factoryCompleteTime}' could not be parsed at index 0; nested
  exception is
  com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot
  deserialize value of type java.time.OffsetDateTime from String
  \"${factoryCompleteTime}\": Failed to deserialize
  java.time.OffsetDateTime: (java.time.format.DateTimeParseException)
  Text '${factoryCompleteTime}' could not be parsed at index 0\n at
  [Source: (PushbackInputStream); line: 15, column: 24]

My json body looks like this.

```<code>"Versions": "$[Versions]",
"createtime": "${createtime}"
</code>```

答:
I think you should pass this Versions a little bit differently, for example if it should be a JSON Array it should look like:

```<code>"Versions": [${Versions}],
</code>```

or

```<code>"Versions": ${Versions},
</code>```

It appears that your ${factoryCompleteTime} variable doesn't have a value so it has been replaced by the default placeholder. Use Debug Sampler and View Results Tree listener combination in order to check the variable value, it should be in format of the OffsetDateTime to wit something like: 2007-12-03T10:15:30+01:00

Body:
I'm having 2 issues when trying to do the create api requests using the jmeter tool

1). How to handle an array parameter. "Versions": "$[Versions]"

getting the following error message

{"timestamp":"2020-02-14T07:18:33.720+0000","status":400,"error":"Bad
  Request","message":"JSON parse error: Cannot deserialize instance of
  java.util.ArrayList<java.lang.Object> out of VALUE_STRING token;
  nested exception is
  com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot
  deserialize instance of java.util.ArrayList<java.lang.Object> out of
  VALUE_STRING token\n at [Source: (PushbackInputStream); line: 15,
  column: 22]

2). how to handle dynamically created time stamp parameter createtime: "${createtime}"

getting the following error message

{"timestamp":"2020-02-14T07:17:58.942+0000","status":400,"error":"Bad
  Request","message":"JSON parse error: Cannot deserialize value of type
  java.time.OffsetDateTime from String \"${factoryCompleteTime}\":
  Failed to deserialize java.time.OffsetDateTime:
  (java.time.format.DateTimeParseException) Text
  '${factoryCompleteTime}' could not be parsed at index 0; nested
  exception is
  com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot
  deserialize value of type java.time.OffsetDateTime from String
  \"${factoryCompleteTime}\": Failed to deserialize
  java.time.OffsetDateTime: (java.time.format.DateTimeParseException)
  Text '${factoryCompleteTime}' could not be parsed at index 0\n at
  [Source: (PushbackInputStream); line: 15, column: 24]

My json body looks like this.

"Versions": "$[Versions]",
"createtime": "${createtime}"

Body:
I think you should pass this Versions a little bit differently, for example if it should be a JSON Array it should look like:

"Versions": [${Versions}],

or

"Versions": ${Versions},

It appears that your ${factoryCompleteTime} variable doesn't have a value so it has been replaced by the default placeholder. Use Debug Sampler and View Results Tree listener combination in order to check the variable value, it should be in format of the OffsetDateTime to wit something like: 2007-12-03T10:15:30+01:00


问:
How to prevent a base class from inheritance in C++?
I don't want to make the base class from being derived to a new class. Is there any way to achieve this?
I want to tell the compiler that you can't inherit the base class just like a final keyword in java</p>

答:
You can mark the class as final to prevent derivation from it. E.g:

```<code>class A final { ... };
</code>```

Body:
You can mark the class as final to prevent derivation from it. E.g:

class A final { ... };


问:
Vue Source Code Q1: confused about the "this._init"

instance/index.js I wonder _init function not defined how can it be used

```<code>function Vue (options) {
  if (process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword')
  }
  this._init(options) // this line
}
initMixin(Vue)
</code>```

instance/init.js _init defined here but I still don't understand

```<code>export function initMixin (Vue: Class<Component>) {
  Vue.prototype._init = function (options?: Object) {
  }
}
</code>```

So I test by myself

```<code>function VueTest(str){
   this._init(str) // this equals to window right?
}

function initMixin(VueTest){
   Vue.prototype._init = function (str) {
      console.log(str)
   }
}

initMixin(new VueTest('vue'));

// console shows the error

VM63:2 Uncaught TypeError: this._init is not a function
    at new VueTest (<anonymous>:2:9)
    at <anonymous>:11:11

</code>```

Maybe it looks stupid but I'm truly confused.

答:
if you invoke "this._init" in "function VueTest", you should define
"VueTest.prototype._init = ... " in your "initMixin", not "Vue.prototype._init".</p>

Body:
instance/index.js I wonder _init function not defined how can it be used

function Vue (options) {
  if (process.env.NODE_ENV !== 'production' &&
    !(this instanceof Vue)
  ) {
    warn('Vue is a constructor and should be called with the `new` keyword')
  }
  this._init(options) // this line
}
initMixin(Vue)

instance/init.js _init defined here but I still don't understand

export function initMixin (Vue: Class<Component>) {
  Vue.prototype._init = function (options?: Object) {
  }
}

So I test by myself

function VueTest(str){
   this._init(str) // this equals to window right?
}

function initMixin(VueTest){
   Vue.prototype._init = function (str) {
      console.log(str)
   }
}

initMixin(new VueTest('vue'));

// console shows the error

VM63:2 Uncaught TypeError: this._init is not a function
    at new VueTest (<anonymous>:2:9)
    at <anonymous>:11:11

Maybe it looks stupid but I'm truly confused.


问:
The Id cannot be computed, since the navigation source 'values' cannot be resolved to a known entity set from model
I am accessing my OData service with following metadata (simplified and obfuscated to the relevant part), this is generated by using Microsoft.AspNet.OData :

```<code><Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
    <DataServices>
        <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="MyProject.Api.Models">
            <EntityType Name="ValuesContainer">
                <Key>
                    <PropertyRef Name="id" />
                </Key>
                <Property Name="id" Type="Edm.Guid" Nullable="false" />
                <NavigationProperty Name="values" Type="Collection(MyProject.Api.Models.Value)"/>
            </EntityType>
            <EntityType Name="Value">
                <Key>
                    <PropertyRef Name="id"/>
                </Key>
                <Property Name="value" Type="Edm.String" />
                <Property Name="id" Type="Edm.Guid" Nullable="false" />
                <Property Name="valuesContainerId" Type="Edm.Guid"/>
                <NavigationProperty Name="valuesContainer" Type="MyProject.Api.Models.ValuesContainer">
                    <ReferentialConstraint Property="valuesContainerId" ReferencedProperty="id"/>
                </NavigationProperty>
            </EntityType>
        </Schema>
        </DataServices>
</Edmx>
</code>```

Some example the output it generates:

```<code>{
    "@odata.context": "https://localhost:5002/v1/odata/$metadata#ValuesContainer(values())",
    "value": [
        {
            "id": "2996e6ea-3e72-4b4c-8b3b-b076e34f6dac",
            "values": [
                {
                    "value": "Hello world",
                    "valuesContainerId": "2996e6ea-3e72-4b4c-8b3b-b076e34f6dac",
                    "id": "3d10fcfa-27a2-4c21-7e01-08d783bf6c40"
                }
            ]
        }
    ]
}
</code>```

When I try to get a ValuesContainer via using the Simple.Odata.Client I receive the following error:

Microsoft.OData.ODataException: 'The Id cannot be computed, since the navigation source 'values' cannot be resolved to a known entity set from model.'

Part where the exception is thrown:

```<code>namespace Simple.OData.Client.V4.Adapter
{
    public class ResponseReader : ResponseReaderBase
...
private ODataEntryAnnotations CreateAnnotations(ODataResource odataEntry)
        {
            string id = null;
            Uri readLink = null;
            Uri editLink = null;
            if (_session.Adapter.GetMetadata().IsTypeWithId(odataEntry.TypeName))
            {
                try
                {
// Over here my exception occurs, calculating the odataEntry.Id.AbsoluteUri
                    id = odataEntry.Id.AbsoluteUri;
                    readLink = odataEntry.ReadLink;
                    editLink = odataEntry.EditLink;
                }
                catch (ODataException)
                {
/// Yep, the library contains this typo
                    // Ingored
                }
            }

            return new ODataEntryAnnotations
            {
                Id = id,
                TypeName = odataEntry.TypeName,
                ReadLink = readLink,
                EditLink = editLink,
                ETag = odataEntry.ETag,
                MediaResource = CreateAnnotations(odataEntry.MediaResource),
                InstanceAnnotations = odataEntry.InstanceAnnotations,
            };
        }
...
}
</code>```

Is my metadata wrong and/or is there a workaround for this? It's not really required to solve it, but having that many exceptions thrown during runtime causes too much overhead as these are expensive operations.

答: Found the solution, had to add the Contained attribute to my Value.

Body:
I am accessing my OData service with following metadata (simplified and obfuscated to the relevant part), this is generated by using Microsoft.AspNet.OData :

<Edmx xmlns:edmx="http://docs.oasis-open.org/odata/ns/edmx" Version="4.0">
    <DataServices>
        <Schema xmlns="http://docs.oasis-open.org/odata/ns/edm" Namespace="MyProject.Api.Models">
            <EntityType Name="ValuesContainer">
                <Key>
                    <PropertyRef Name="id" />
                </Key>
                <Property Name="id" Type="Edm.Guid" Nullable="false" />
                <NavigationProperty Name="values" Type="Collection(MyProject.Api.Models.Value)"/>
            </EntityType>
            <EntityType Name="Value">
                <Key>
                    <PropertyRef Name="id"/>
                </Key>
                <Property Name="value" Type="Edm.String" />
                <Property Name="id" Type="Edm.Guid" Nullable="false" />
                <Property Name="valuesContainerId" Type="Edm.Guid"/>
                <NavigationProperty Name="valuesContainer" Type="MyProject.Api.Models.ValuesContainer">
                    <ReferentialConstraint Property="valuesContainerId" ReferencedProperty="id"/>
                </NavigationProperty>
            </EntityType>
        </Schema>
        </DataServices>
</Edmx>

Some example the output it generates:

{
    "@odata.context": "https://localhost:5002/v1/odata/$metadata#ValuesContainer(values())",
    "value": [
        {
            "id": "2996e6ea-3e72-4b4c-8b3b-b076e34f6dac",
            "values": [
                {
                    "value": "Hello world",
                    "valuesContainerId": "2996e6ea-3e72-4b4c-8b3b-b076e34f6dac",
                    "id": "3d10fcfa-27a2-4c21-7e01-08d783bf6c40"
                }
            ]
        }
    ]
}

When I try to get a ValuesContainer via using the Simple.Odata.Client I receive the following error:

Microsoft.OData.ODataException: 'The Id cannot be computed, since the navigation source 'values' cannot be resolved to a known entity set from model.'

Part where the exception is thrown:

namespace Simple.OData.Client.V4.Adapter
{
    public class ResponseReader : ResponseReaderBase
...
private ODataEntryAnnotations CreateAnnotations(ODataResource odataEntry)
        {
            string id = null;
            Uri readLink = null;
            Uri editLink = null;
            if (_session.Adapter.GetMetadata().IsTypeWithId(odataEntry.TypeName))
            {
                try
                {
// Over here my exception occurs, calculating the odataEntry.Id.AbsoluteUri
                    id = odataEntry.Id.AbsoluteUri;
                    readLink = odataEntry.ReadLink;
                    editLink = odataEntry.EditLink;
                }
                catch (ODataException)
                {
/// Yep, the library contains this typo
                    // Ingored
                }
            }

            return new ODataEntryAnnotations
            {
                Id = id,
                TypeName = odataEntry.TypeName,
                ReadLink = readLink,
                EditLink = editLink,
                ETag = odataEntry.ETag,
                MediaResource = CreateAnnotations(odataEntry.MediaResource),
                InstanceAnnotations = odataEntry.InstanceAnnotations,
            };
        }
...
}

Is my metadata wrong and/or is there a workaround for this? It's not really required to solve it, but having that many exceptions thrown during runtime causes too much overhead as these are expensive operations.


问:
What is the more correct position for the error argument in a javascript callback?
I am writing a javascript function that takes a callback. The callback will be passed an error argument if something goes wrong.

What are the best / most standard calling conventions?

Should the callback's error argument be first or last?

Should I pass an 'errorMsg' string, or a new Error('errorMsg') object?

Ie, what is more correct - this code:

```<code>foo = function(bar, callback) {
  ...
  if (error) {
    callback('troz not found');
  } else {
    callback(null, result);
  }
}
</code>```

or this code:

```<code>foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, 'troz not found');
  } else {
    callback(result);
  }
}
</code>```

or this:

```<code>foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, new Error('troz not found'));
  } else {
    callback(result);
  }
}
</code>```

If its relevant, my code will be used as both as a NodeJS module and as a browser-based javascript library.

答:
You should choose a convention for your library and stick with it; otherwise, it is arbitrary. There are many different ways of handling errors in JavaScript:

Taking both a "success" and "error" callback.

Taking a single callback to handle both "success" and "error" cases.

Having a registration mechanism for a default "error" handler, making error handlers optional on all other calls, using the immediate or fallback error callbacks as appropriate.

Combined with:

Using no parameters to the error callback.

Using a boolean to indicate success / failure.

Using a string to encapsulate the nature of the error.

Using some more complex "Result" object to encapsulate success/failure and the result.

Using some complex object to encapsulate detailed failure information.

Really, it's entirely up to you. It also depends on what you are trying  to do. For example, if you don't really intend to do anything with the failure information, then it might not be worth the expense of constructing / passing around that extra information. But perhaps you have lots of detailed failure information you want to pass to the user or back to the API caller, in which case it makes lots of sense.

Choose a convention, and stick with it. Other than that, it's entirely up to you.

Body:
I am writing a javascript function that takes a callback. The callback will be passed an error argument if something goes wrong.

What are the best / most standard calling conventions?

Should the callback's error argument be first or last?

Should I pass an 'errorMsg' string, or a new Error('errorMsg') object?

Ie, what is more correct - this code:

foo = function(bar, callback) {
  ...
  if (error) {
    callback('troz not found');
  } else {
    callback(null, result);
  }
}

or this code:

foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, 'troz not found');
  } else {
    callback(result);
  }
}

or this:

foo = function(bar, callback) {
  ...
  if (error) {
    callback(null, new Error('troz not found'));
  } else {
    callback(result);
  }
}

If its relevant, my code will be used as both as a NodeJS module and as a browser-based javascript library.


问:
How to display error on PHP Plates templating engine
I am trying to set up platesphp for one of my projects.

One of the methods in the model checks for the email address supplied by a new user and tells if the email they trying to use exists or not.

Something like

```<code>class UserModel extends BaseModel
{
    public $errors = [];

    public function validate()
    {
        if (filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL) === false) {
            $this->errors[] = 'Invalid email';
        }
        if ($this->emailExists($this->request->post['email'])) {
            $this->errors[] = 'Email already exist';
        }
    }

    protected function emailExists($email)
    {
        $sql = 'SELECT * FROM user_account WHERE email = :email';
        -----
        -----
        $stmt->execute();
        return $stmt->fetch() !== false;
    }
}
</code>```

and in the controller

```<code>public function register()
{
    $this->load->getModel('UserModel');

    if ($this->model_UserModel->registerUser($this->request->post)) {
        echo "Success ... load (redirect) second page";
    } else {
        $data ['error'] = $this->model_UserModel->errors;
        echo $this->template->render('home/home', $data);
    }
}
</code>```

If the email exists and I var dump $data ['error'] it says "Email already Exist" as defined in the validate method in the UserModel.

Now, I am trying to get the error message on my home template by adding these lines on the tpl file

```<code><?php if (!empty($this->e($errors))): ?>
    <?php foreach($errors as $error): ?>
        <li><?=$this->e($error)?></li>
    <?php endforeach ?>
<?php endif;?>
</code>```

But now if I click on the register page the template says

Notice: Undefined variable: errors in C:\xampp\htdocs\vem\App\Views\template\register\registeruser.tpl on line 14

How do I move forward?

I even tried setting the $this->e($error) = '' but naa, shows another error.

答:
On your controller, you're setting variable error, but in template, you're accessing variable errors (with s).
Try with

```<code><?php if (@$error)): ?>
    <?php foreach($error as $e): ?>
        <li><?=$this->e($e)?></li>
    <?php endforeach ?>
<?php endif;?>
</code>```

Body:
I am trying to set up platesphp for one of my projects.

One of the methods in the model checks for the email address supplied by a new user and tells if the email they trying to use exists or not.

Something like

class UserModel extends BaseModel
{
    public $errors = [];

    public function validate()
    {
        if (filter_var($this->request->post['email'], FILTER_VALIDATE_EMAIL) === false) {
            $this->errors[] = 'Invalid email';
        }
        if ($this->emailExists($this->request->post['email'])) {
            $this->errors[] = 'Email already exist';
        }
    }

    protected function emailExists($email)
    {
        $sql = 'SELECT * FROM user_account WHERE email = :email';
        -----
        -----
        $stmt->execute();
        return $stmt->fetch() !== false;
    }
}

and in the controller

public function register()
{
    $this->load->getModel('UserModel');

    if ($this->model_UserModel->registerUser($this->request->post)) {
        echo "Success ... load (redirect) second page";
    } else {
        $data ['error'] = $this->model_UserModel->errors;
        echo $this->template->render('home/home', $data);
    }
}

If the email exists and I var dump $data ['error'] it says "Email already Exist" as defined in the validate method in the UserModel.

Now, I am trying to get the error message on my home template by adding these lines on the tpl file

<?php if (!empty($this->e($errors))): ?>
    <?php foreach($errors as $error): ?>

<?=$this->e($error)?>

    <?php endforeach ?>
<?php endif;?>

But now if I click on the register page the template says

Notice: Undefined variable: errors in C:\xampp\htdocs\vem\App\Views\template\register\registeruser.tpl on line 14

How do I move forward?

I even tried setting the $this->e($error) = '' but naa, shows another error.

Body:
On your controller, you're setting variable error, but in template, you're accessing variable errors (with s).
Try with

<?php if (@$error)): ?>
    <?php foreach($error as $e): ?>
        <li><?=$this->e($e)?></li>
    <?php endforeach ?>
<?php endif;?>


问:
Application run on Azure AKS Kubernates can not be accessed from App Service
I have configured two different applications ( SEQ and MockServer ) on Azure AKS service. They are both working correctly from internet but can not access them from Azure Web Service. It also can not be accessed from Azure CLI.
Below my </p>

```<code>apiVersion: apps/v1
kind: Deployment
metadata:
  name: mockserver-deployment
  labels:
    app: mockserver
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mockserver
  template:
    metadata:
      labels:
        app: mockserver
    spec:
      containers:
      - name: mockserver
        image: jamesdbloom/mockserver
        env:
        - name: LOG_LEVEL
          value: "INFO"
        ports:
        - containerPort: 1080
      imagePullSecrets:
      - name: my-secret
---
kind: Service
apiVersion: v1
metadata:
  name: mockserver-service
spec:
  selector:
    app: mockserver
  loadBalancerIP: 51.136.53.26
  type: LoadBalancer
  loadBalancerSourceRanges:
  # from Poland
  - 62.87.152.154/32
  - 83.30.150.205/32
  - 80.193.73.114/32
  - 195.191.163.0/24
  # from AppCenter test
  - 195.249.159.0/24
  - 195.0.0.0/8
  # from Marcin K home
  - 95.160.157.0/24
  - 93.105.0.0/16
  ports:
  - port: 1080
    targetPort: 1080
    name: mockserver
</code>```

答: The best approach is to use VNET integration for your AppService (https://learn.microsoft.com/en-us/azure/app-service/web-sites-integrate-with-vnet) combined with an internal LoadBalancer-type Service (https://learn.microsoft.com/en-us/azure/aks/internal-lb). This way the communication between the app service and AKS will flow only via the internal VNET. Note that you can have also an external LB service like the one you already have; you can have multiple services serving traffic to the same set of pods.

Body:
I have configured two different applications ( SEQ and MockServer ) on Azure AKS service. They are both working correctly from internet but can not access them from Azure Web Service. It also can not be accessed from Azure CLI.
Below my

apiVersion: apps/v1
kind: Deployment
metadata:
  name: mockserver-deployment
  labels:
    app: mockserver
spec:
  replicas: 1
  selector:
    matchLabels:
      app: mockserver
  template:
    metadata:
      labels:
        app: mockserver
    spec:
      containers:
      - name: mockserver
        image: jamesdbloom/mockserver
        env:
        - name: LOG_LEVEL
          value: "INFO"
        ports:
        - containerPort: 1080
      imagePullSecrets:
      - name: my-secret
---
kind: Service
apiVersion: v1
metadata:
  name: mockserver-service
spec:
  selector:
    app: mockserver
  loadBalancerIP: 51.136.53.26
  type: LoadBalancer
  loadBalancerSourceRanges:
  # from Poland
  - 62.87.152.154/32
  - 83.30.150.205/32
  - 80.193.73.114/32
  - 195.191.163.0/24
  # from AppCenter test
  - 195.249.159.0/24
  - 195.0.0.0/8
  # from Marcin K home
  - 95.160.157.0/24
  - 93.105.0.0/16
  ports:
  - port: 1080
    targetPort: 1080
    name: mockserver


问:
Removing duplicates while adding their values in an array
Lets say we have an array also with empty strings

```<code>const arr = [
  { value: 1, name: "king" },
  { value: 2, name: "master" },
  { value: 10, name: "lisa" },
  { value: 4, name: "lisa" },
  { value: 5, name: "jim" },
  { value: 6, name: "master" },
  { value: 1, name: "jim" },
  { value: 3, name: "" },
  { value: 2, name: "" },
]
</code>```

I want to remove the duplicate names and add their values into same array or another array.
Desired output:

```<code>[
  { value: 1, name: "king" },
  { value: 8, name: "master" },
  { value: 14, name: "lisa" },
  { value: 6, name: "jim" },
  { value: 5, name: "" },
]
</code>```

答:
By simply looping checking for repetition, you can reduce array.

arr = [
  { value: 1, name: "king" },
  { value: 2, name: "master" },
  { value: 10, name: "lisa" },
  { value: 4, name: "lisa" },
  { value: 5, name: "jim" },
  { value: 6, name: "master" },
  { value: 1, name: "jim" },
   { value: 3, name: "" },
  { value: 2, name: "" },
];
var a = new Set();

var array2 = [];
for (i = 0; i < arr.length; i++) {
 if(!a.has(arr[i].name)){
   array2.push(arr[i]);
   a.add(arr[i].name);
 }
 else{
   var name = arr[i].name;
   for (j = 0; j < array2.length; j++) {
      if(array2[j].name == name ){
        array2[j].value += arr[i].value;
      }
  }

}
}
console.log(array2);```

Body:
Lets say we have an array also with empty strings

const arr = [
  { value: 1, name: "king" },
  { value: 2, name: "master" },
  { value: 10, name: "lisa" },
  { value: 4, name: "lisa" },
  { value: 5, name: "jim" },
  { value: 6, name: "master" },
  { value: 1, name: "jim" },
  { value: 3, name: "" },
  { value: 2, name: "" },
]

I want to remove the duplicate names and add their values into same array or another array.
Desired output:

[
  { value: 1, name: "king" },
  { value: 8, name: "master" },
  { value: 14, name: "lisa" },
  { value: 6, name: "jim" },
  { value: 5, name: "" },
]