问:
Web framework and entity-relationship model (ERM)
I am currently designing a big website a priori based on a PostgreSQL database.

I have nearly ended the Entity Relationship Model and I am thinking about the way to develop (or have it develop) the whole thing (Java, PHP, other).

First I thought about a CMS to do the job. But this is a very specific (and big) project, and it would be better if I developed it entirely instead of trying to bow any CMS into my need.

Can I develop a website with any framework using my own ERM ?

Are there preconfigured ERMs with those frameworks (eventually for future projects) ?

I am thinking of CakePHP or Ruby on Rails. Would you encourage me into these directions ?

The website I am currently designing is supposed to be consulted by more than 1 000 000 times a day. As a consequence, I need scalability and strongness.

Thanks a lot by advance.

EDIT : I am thinking of taking Symfony. Can I do the same thing with this very framework ?

答:
You can easily implement any ERM in eZ Publish + Zeta Components + eZ Find (Solr) search engine.  And you get the rest of the functionality you'll need for 'free'.  Highly scalable architecture.
OSS license.  http://share.ez.no/download-develop/downloads</p>


来源: stackexchange

问:
Get all matching records where IDs are joined to a comma separated list
I have two database table like below:

Form

Id

Name

Fields(varchar-255)

FormFields

Id

Name

InputType

Sample data for Form

Id    Name     Fields
1     Form1    1,2,3
2     Form2    1,2
```

<p>Sample data for <strong>FormFields</strong></p>

<pre class="lang-none prettyprint-override"><code>Id    Name     InputType
1     FName    TEXT
2     Lname    TEXT
3     Email    TEXT
</code>```

Now I write query as below:

SELECT * FROM FormFields
WHERE Id IN (SELECT Fields FROM Form WHERE Id = 2)
```

<p>And I get only one record as below:</p>

<pre class="lang-none prettyprint-override"><code>Id    Name     InputType
1     FName    TEXT
</code>```

But I want all the records of FormFields table whose Id is present in the Fields columns of Form table. I want result like this:

Id    Name     InputType
1     FName    TEXT
2     Lname    TEXT
```

答:
If I understand you correctly this is what is happening in short:

You have let say two table:
Table Employee
id, locationid, name, status

1, 1, test,1
2, 1, test1,0
3, 2, test2,1
3, 3, test3,1
3, 4, test4,1

Table Users
id,allowedlocationids, username etc

1,[1,2,3],testuser

Now you want to get all records from employee table that are working with location 1 and 2 for logged in user testuser

SELECT * FROM employee WHERE `status`=1 AND `locationid` IN (SELECT locationid FROM employee WHERE FIND_IN_SET(locationid,'1,2,3') )

take note 1,2,3 are location the user has permission to see
Then this will be your output:

```<code>1, 1, test,1
3, 2, test2,1
3, 3, test3,1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have two database table like below:

Form

Id

Name

Fields(varchar-255)

FormFields

Id

Name

InputType

Sample data for Form

Id    Name     Fields
1     Form1    1,2,3
2     Form2    1,2

Sample data for FormFields

Id    Name     InputType
1     FName    TEXT
2     Lname    TEXT
3     Email    TEXT

Now I write query as below:

SELECT * FROM FormFields
WHERE Id IN (SELECT Fields FROM Form WHERE Id = 2)

And I get only one record as below:

Id    Name     InputType
1     FName    TEXT

But I want all the records of FormFields table whose Id is present in the Fields columns of Form table. I want result like this:

Id    Name     InputType
1     FName    TEXT
2     Lname    TEXT

Body:
If I understand you correctly this is what is happening in short:

You have let say two table:
Table Employee
id, locationid, name, status

1, 1, test,1
2, 1, test1,0
3, 2, test2,1
3, 3, test3,1
3, 4, test4,1

Table Users
id,allowedlocationids, username etc

1,[1,2,3],testuser

Now you want to get all records from employee table that are working with location 1 and 2 for logged in user testuser

SELECT * FROM employee WHERE `status`=1 AND `locationid` IN (SELECT locationid FROM employee WHERE FIND_IN_SET(locationid,'1,2,3') )

take note 1,2,3 are location the user has permission to see
Then this will be your output:

1, 1, test,1
3, 2, test2,1
3, 3, test3,1

ContentLicense: CC BY-SA 4.0


问:
Convert a list to expected list of tuples without any iteration in Python?
I am having a list like

```<code>['val1', 'val2', 'val3']
</code>```

I want this list as list of tuples like

```<code>[('val1', False), ('val2', False), ('val3', False)]
</code>```

This list may contains large number of data. So, I want optimized way to get expected result.

答:
Use a list comprehension. In most cases this is the most efficient solution for constructing lists:</p>

```<code>vals = ['val1', 'val2', 'val3']

result = [(v, False) for v in vals]
# [('val1', False), ('val2', False), ('val3', False)]
</code>```

Body:
I am having a list like

['val1', 'val2', 'val3']

I want this list as list of tuples like

[('val1', False), ('val2', False), ('val3', False)]

This list may contains large number of data. So, I want optimized way to get expected result.

Body:
Use a list comprehension. In most cases this is the most efficient solution for constructing lists:

vals = ['val1', 'val2', 'val3']

result = [(v, False) for v in vals]
# [('val1', False), ('val2', False), ('val3', False)]


问:
DynamoDB free tier read/write capacity charges
I am new to DynamoDB and NoSQL. I have 2 x tables setup and they are very small. < 80 items each. one currently 60KB the other 1.5KB. Writes are made on a timed basis twice delay based on an external feed. Reads are made via lambda for API gateway.

I can see already i have made mistakes in my DynamoDB setup and usage of these: I am using scans where i believe i could be using using queries and I have a GSI which could possibly be handled better through better primary key and local secondary index setup, although this is still a mystery to me.

I am getting charged $0.89 extra per day pretty consistently, above the free tier for "per hour for units of read capacity beyond the free tier" $0.15 and "per hour for units of write capacity beyond the free tier" $0.74.

Before making changes to my setup i want to understand why I am incurring the additional cost and where - I am looking at the costs explorer and I can't see the tipping point where the costs are incurred.

Grateful for any pointers

答:
DynamoDB free tier includes:

25 GB of Storage

25 provisioned Write Capacity Units (WCU)

25 provisioned Read Capacity Units (RCU)

A single write capacity unit is used for writing a single item of below 1kb. If the item is above 1kb (like in your example 1.5kb) then it will use additional capacity units. Your 60kb item would use 60 write capacity units to make this write.

A single read capacity unit is used for reading a single item of below 4kb. The same rules as write capacity applies.

With a scan, the read capacity units usage will always be the total for the entire DynamoDB table. Based on your example 1 60KB item is 15 read capacity units, if another 79 at 1.5kb, thats another 79 capacity units for each item. So 94 in total for a single scan.

The reason for scans using all these capacity units is that the filter is actually applied after he data is retrieved from each partition.

This is where a query is more efficient, the retrieval of items is performed on the partition. Items will be filtered and then consume the total capacity of the items that are returned.

If you want to try and reduce costs, ensure that DynamoDB read and write capacity units are either set at 25 during creation, or that autoscaling cannot surpass 25.

More information here: https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/HowItWorks.ReadWriteCapacityMode.html


问:
Uploading network image to firestore
How can I download an image file from network using a given url and upload it to fire store?
I am having hard time downloading image from url and uploading it to fire store. </p>

答:
you could do it for example like this:

```<code>upload() async {
   //pick image   use ImageSource.camera for accessing camera.
   File image = await ImagePicker.pickImage(source: ImageSource.gallery);

   //alternative with ressource in your app:
   var src = // your image src
   File image = await Image.network(src);

   //basename() function will give you the filename
   String fileName = basename(image.path);

   //passing your path with the filename to Firebase Storage Reference
   StorageReference reference =
        FirebaseHelper.firebaseStorage().child("your_path/$fileName");

   //upload the file to Firebase Storage
   StorageUploadTask uploadTask = reference.putFile(image);

   //Snapshot of the uploading task
   StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
}
</code>```

To get a better understanding of firebase storage and the upload process, and features like showing progress and more I recommend you checking this useful article too: https://medium.com/flutterpub/firebase-cloud-storage-and-flutter-fa2e91663b95

Title: Uploading network image to firestore

Body:
you could do it for example like this:

upload() async {
   //pick image   use ImageSource.camera for accessing camera.
   File image = await ImagePicker.pickImage(source: ImageSource.gallery);

   //alternative with ressource in your app:
   var src = // your image src
   File image = await Image.network(src);

   //basename() function will give you the filename
   String fileName = basename(image.path);

   //passing your path with the filename to Firebase Storage Reference
   StorageReference reference =
        FirebaseHelper.firebaseStorage().child("your_path/$fileName");

   //upload the file to Firebase Storage
   StorageUploadTask uploadTask = reference.putFile(image);

   //Snapshot of the uploading task
   StorageTaskSnapshot taskSnapshot = await uploadTask.onComplete;
}

To get a better understanding of firebase storage and the upload process, and features like showing progress and more I recommend you checking this useful article too: https://medium.com/flutterpub/firebase-cloud-storage-and-flutter-fa2e91663b95


问:
OpenMP 5.0 Memory allocation
I am trying to use an example from the OpenMP specification on page 64:

```<code>#include <stdio.h>
#include <omp.h>

int basic_default2(int n)
{
  const int success=1, failure=0;
  int retval;
  omp_memspace_t *my_mspace;
  omp_allocator_t *my_allocator;
  double *buffer;

  my_mspace = omp_init_memspace(&omp_default_memtraits);
  my_allocator = omp_init_allocator(my_mspace, &omp_default_alloctraits);
  buffer = omp_alloc(n * sizeof(*buffer), my_allocator);

  if ( buffer == NULL ){
    fprintf("Could not allocate space using default traits\n");
    retval = failure;
  }else{
    do_work(buffer, n);
    omp_free(buffer, my_allocator);
    retval = success;
  }

  omp_destroy_allocator(my_allocator);
  omp_destroy_mspace(my_mspace);
}
</code>```

According to the OpenMp 5.0 requirements this should work.
I am using GNU 9.1.0 compiler and the -fopenmp flag.

Unfortunately, the type omp_allocator_t is unknown by the compiler.

答:
You are using a 2017 Technical Report, not the OpenMP 5.0 standard, and the interface has evolved since the TR (which does say "Expires January 4th, 2018" on the cover!)

In the standard, the return type from omp_init_allocator is omp_allocator_handle_t.

Note, too, that many of the other names have also changed, so your code needs other changes as well (for instance there is no omp_init_memspace call any longer).

The allocation section of the standard is here.

Title: OpenMP 5.0 Memory allocation

Body:
I am trying to use an example from the OpenMP specification on page 64:

#include <stdio.h>
#include <omp.h>

int basic_default2(int n)
{
  const int success=1, failure=0;
  int retval;
  omp_memspace_t *my_mspace;
  omp_allocator_t *my_allocator;
  double *buffer;

  my_mspace = omp_init_memspace(&omp_default_memtraits);
  my_allocator = omp_init_allocator(my_mspace, &omp_default_alloctraits);
  buffer = omp_alloc(n * sizeof(*buffer), my_allocator);

  if ( buffer == NULL ){
    fprintf("Could not allocate space using default traits\n");
    retval = failure;
  }else{
    do_work(buffer, n);
    omp_free(buffer, my_allocator);
    retval = success;
  }

  omp_destroy_allocator(my_allocator);
  omp_destroy_mspace(my_mspace);
}

According to the OpenMp 5.0 requirements this should work.
I am using GNU 9.1.0 compiler and the -fopenmp flag.

Unfortunately, the type omp_allocator_t is unknown by the compiler.


问:
Understanding "randomness"
I can't get my head around this, which is more random?

```<code>rand()
</code>```

OR:

```<code>rand() * rand()
</code>```

I´m finding it a real brain teaser, could you help me out?

EDIT:

Intuitively I know that the mathematical answer will be that they are equally random, but I can't help but think that if you "run the random number algorithm" twice when you multiply the two together you'll create something more random than just doing it once.

答:
Use a linear feedback shift register (LFSR) that implements a primitive polynomial.

The result will be a sequence of 2^n pseudo-random numbers, ie none repeating in the sequence where n is the number of bits in the LFSR .... resulting in a uniform distribution.

http://en.wikipedia.org/wiki/Linear_feedback_shift_register
http://www.xilinx.com/support/documentation/application_notes/xapp052.pdf

Use a "random" seed based on microsecs of your computer clock or maybe a subset of the md5 result on some continuously changing data in your file system.

For example, a 32-bit LFSR will generate 2^32 unique numbers in sequence (no 2 alike) starting with a given seed.
The sequence will always be in the same order, but the starting point will be different (obviously) for a different seeds.
So, if a possibly repeating sequence between seedings is not a problem, this might be a good choice.

I've used 128-bit LFSR's to generate random tests in hardware simulators using a seed which is the md5 results on continuously changing system data.

Title: Understanding "randomness"

Body:
I can't get my head around this, which is more random?

rand()

OR:

rand() * rand()

I´m finding it a real brain teaser, could you help me out?

EDIT:

Intuitively I know that the mathematical answer will be that they are equally random, but I can't help but think that if you "run the random number algorithm" twice when you multiply the two together you'll create something more random than just doing it once.


问:
Updating Html content through loop not reflecting the final value
html

```<code><div class="content"></div>
</code>```

array of objects:

```<code>var obj = [
  {
    title : "burger",
    price : 5
  },
  {
    title : "salad",
    price : 10
  }
]
</code>```

functions:

```<code>function addItems() {
  $(".content").html('<div id="title"></div><div id="price"></div>');
};

function addContent() {
  $("#title").text(obj[i].title);
  $("#price").text(obj[i].price);
};
</code>```

Then I am looping through to change the html and the content:

```<code>for(i = 0; i < obj.length; i++){
  addItems();
  addContent();
}
</code>```

The actual result is the text string from obj[2].title

salad

My expected result :

burger 5 salad 10

Thanks for the help

答:
There are several problems in your code.

Firtsly, you are mixing the scope of your functions addContent, addItems with the scope of your for -loop. If you need to use variables inside of your functions, that are only known within another scope, you should pass them to your function. That makes your code much more readable and undestandable. Noone will ever know by you function declarations, that you actually need the item's data within that function

That means, you have to declare your function so that it can work with the paramters:

```<code>function addItem( item ) {
  // use the item data inside this function
  // also note that i changed the functions name,
  // since you are only adding one item
}
</code>```

Secondly, you are trying to add multiple elements with the same ID to your HTML. That would be invalid HTML, since IDs need to be unique. You are un/lucky since the function .html() replaces the whole HTML within the given object so you end up only having one #title and #price ID. Instead you can use the append() function which appends a given element to your html, so your addItem Function gets:

```<code>function addItem( item ) {
  let html = "<div class='title'>"+item.title+"</div><div class='price'>"+item.price+"</div>";
  $('.content').append( html );
}
</code>```

You addContent function is now redundant and would actualy overcomplicate your code.

var obj = [
   {
     title : "burger",
     price : 5
   },
   {
    title : "salad",
    price : 10
   }
];

function addItem( item ) {
  let html = "
"+item.title+"

"+item.price+"
";
  $('.content').append( html );
};

for(i = 0; i < obj.length; i++){
   addItem( obj[i]);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content"></div></code>```

Body:
html

array of objects:

var obj = [
  {
    title : "burger",
    price : 5
  },
  {
    title : "salad",
    price : 10
  }
]

functions:

function addItems() {
  $(".content").html('

');
};

function addContent() {
  $("#title").text(obj[i].title);
  $("#price").text(obj[i].price);
};

Then I am looping through to change the html and the content:

for(i = 0; i < obj.length; i++){
  addItems();
  addContent();
}

The actual result is the text string from obj[2].title

salad

My expected result :

burger 5 salad 10

Thanks for the help

Body:
There are several problems in your code.

Firtsly, you are mixing the scope of your functions addContent, addItems with the scope of your for -loop. If you need to use variables inside of your functions, that are only known within another scope, you should pass them to your function. That makes your code much more readable and undestandable. Noone will ever know by you function declarations, that you actually need the item's data within that function

That means, you have to declare your function so that it can work with the paramters:

function addItem( item ) {
  // use the item data inside this function
  // also note that i changed the functions name,
  // since you are only adding one item
}

Secondly, you are trying to add multiple elements with the same ID to your HTML. That would be invalid HTML, since IDs need to be unique. You are un/lucky since the function .html() replaces the whole HTML within the given object so you end up only having one #title and #price ID. Instead you can use the append() function which appends a given element to your html, so your addItem Function gets:

function addItem( item ) {
  let html = "<div class='title'>"+item.title+"</div><div class='price'>"+item.price+"</div>";
  $('.content').append( html );
}

You addContent function is now redundant and would actualy overcomplicate your code.

var obj = [
   {
     title : "burger",
     price : 5
   },
   {
    title : "salad",
    price : 10
   }
];

function addItem( item ) {
  let html = "<div class='title'>"+item.title+"</div><div class='price'>"+item.price+"</div>";
  $('.content').append( html );
};

for(i = 0; i < obj.length; i++){
   addItem( obj[i]);
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content"></div>


问:
usprivacy=1 cookie causes a 404 in Apache
I have two curl commands below. You'll notice I'm passing in a Cookie of "usprivacy=1---". This is a cookie that seems to be added by some web browsers automatically. The issue I'm seeing -- if this cookie is present, some of my assets return HTTP error codes. As soon as the cookie is removed, it returns HTTP CODE 200. It doesn't happen with any other cookies. I suspect there's some Apache configuration variable, but I'm baffled.

This one results in the Apache webserver returning 404 not found:

curl 'https://salvagedinspirations.com/wp-content/plugins/woocommerce/packages/woocommerce-blocks/build/style.css?ver=2.4.5' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0' -H 'Accept: text/css,*/*;q=0.1' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Connection: keep-alive' -H 'Referer: https://salvagedinspirations.com/' -H 'Cookie: usprivacy=1---;' -H 'Cache-Control: max-age=0' -D -

This one results in a "403 Forbidden" header, although HTML is still returned:

curl 'https://salvagedinspirations.com/' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.14; rv:71.0) Gecko/20100101 Firefox/71.0' -H 'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' -H 'Accept-Language: en-US,en;q=0.5' --compressed -H 'Connection: keep-alive' -H 'Cookie: usprivacy=1---;' -H 'Upgrade-Insecure-Requests: 1' -H 'Cache-Control: max-age=0' -D -

Thank you

答: The issue was with an apache module that was loaded in. I forgot which one. Sorry</p>


问:
Clustering images using unsupervised Machine Learning
I have a database of images that contains identity cards, bills and passports.

I want to classify these images into different groups (i.e identity cards, bills and passports).

As I read about that, one of the ways to do this task is clustering (since it is going to be unsupervised).

The idea for me is like this: the clustering will be based on the similarity between images (i.e images that have similar features will be grouped together).

I know also that this process can be done by using k-means.

So the problem for me is about features and using images with K-means.

If anyone has done this before, or has a clue about it, please would you recommend some links to start with or suggest any features that can be helpful.

答:
I have implemented Unsupervised Clustering based on Image Similarity using Agglomerative Hierarchical Clustering.

My use case had images of People, so I had extracted the Face Embedding (aka Feature) Vector from each image. I have used dlib for face embedding and so each feature vector was 128d.

In general, the feature vector of each image can be extracted. A pre-trained VGG or CNN network, with its final classification layer removed; can be used for feature extraction.

A dictionary with KEY as the IMAGE_FILENAME and VALUE as the FEATURE_VECTOR can be created for all the images in the folder. This will make the co-relation between the filename and it’s feature vector easier.

Then create a single feature vector say X, which comprises of individual feature vectors of each image in the folder/group which needs to be clustered.

In my use case, X had the dimension as : NUMBER OF IMAGE IN THE FOLDER, 128 (i.e SIZE OF EACH FEATURE VECTOR). For instance, Shape of X : 50,128

This feature vector can then be used to fit an Agglomerative Hierarchical Cluster. One needs to fine tune the distance threshold parameter empirically.

Finally, we can write a code to identify which IMAGE_FILENAME belongs to which cluster.

In my case, there were about 50 images per folder so this was a manageable solution. This approach was able to group image of a single person into a single clusters. For example, 15 images of PERSON1 belongs to CLUSTER 0, 10 images of PERSON2 belongs to CLUSTER 2 and so on…


问:
How to get all form input values using blur event in `addEventListener`?
I am trying to get form values dynamically using addEventListener but I am just getting first input, not getting other inputs.

This is my current code:

$(document).ready(
  function() {
    const user_input = document.querySelector('input[type="text"], input[type="password"]');

    user_input.addEventListener(
      'blur',
      function(event) {
        var target = event.target;

        if (target.name == "first_name") {
          console.log('first name : ' + target.value);
        }

        if (target.name == "mid_name") {
          console.log('mid name : ' + target.value);
        }

        if (target.name == "last_name") {
          console.log('last name : ' + target.value);
        }

        if (target.name == "password") {
          console.log('password : ' + target.value);
        }
      }
    );
  }
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
  first_name : <input type="text" name="first_name" value=""> <br>
  mid_name : <input type="text" name="mid_name" value=""> <br>
  last_name : <input type="text" name="last_name" value=""> <br>
  password : <input type="password" name="password" value=""> <br>
</form></code>```

Demo on JSFiddle

I can just get the fist name value; for the other inputs I am not getting anything. Any idea what I am doing wrong?

答:
Like this?

function updateResult() {
  $('#result').text(JSON.stringify($('#inputs').serializeArray().map(x=>x.name + ': '+x.value)))
}

$(document).ready(function() {
  $('input').on('change', function() {
    updateResult()
  })
})```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="inputs">
  first_name : <input type="text" name="first_name" value=""> <br>
  mid_name  :  <input type="text" name="mid_name" value=""> <br>
  last_name  :  <input type="text" name="last_name" value=""> <br>
  password :  <input type="password" name="password" value=""> <br>
</form>
<div id="result">

</div></code>```

Body:
I am trying to get form values dynamically using addEventListener but I am just getting first input, not getting other inputs.

This is my current code:

$(document).ready(
  function() {
    const user_input = document.querySelector('input[type="text"], input[type="password"]');

    user_input.addEventListener(
      'blur',
      function(event) {
        var target = event.target;

        if (target.name == "first_name") {
          console.log('first name : ' + target.value);
        }

        if (target.name == "mid_name") {
          console.log('mid name : ' + target.value);
        }

        if (target.name == "last_name") {
          console.log('last name : ' + target.value);
        }

        if (target.name == "password") {
          console.log('password : ' + target.value);
        }
      }
    );
  }
);

<form>
  first_name : <input type="text" name="first_name" value="">

  mid_name : <input type="text" name="mid_name" value="">

  last_name : <input type="text" name="last_name" value="">

  password : <input type="password" name="password" value="">

</form>

Demo on JSFiddle

I can just get the fist name value; for the other inputs I am not getting anything. Any idea what I am doing wrong?

Body:
Like this?

function updateResult() {
  $('#result').text(JSON.stringify($('#inputs').serializeArray().map(x=>x.name + ': '+x.value)))
}

$(document).ready(function() {
  $('input').on('change', function() {
    updateResult()
  })
})

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="inputs">
  first_name : <input type="text" name="first_name" value=""> <br>
  mid_name  :  <input type="text" name="mid_name" value=""> <br>
  last_name  :  <input type="text" name="last_name" value=""> <br>
  password :  <input type="password" name="password" value=""> <br>
</form>
<div id="result">

</div>


问:
copying C-style arrays and structure
C++ does not allow copying of C-style arrays using =. But allows copying of structures using =, as in this link -> Copying array in C v/s copying structure in C.It does not have any credible answers yet.
 But consider following code

```<code>#include <iostream>
using namespace std;

struct user {
    int a[4];
    char c;
};

int main() {
    user a{{1,2,3,4}, 'a'}, b{{4,5,6,7}, 'b'};
    a = b;             //should have given any error or warning but nothing
    return 0;
}
</code>```

Above code segment didn't gave any kind of errors and warnings, and just works fine. WHY?
Consider explaining both questions(this one and the one linked above).

答:
Yes, the code should work fine. arrays can't be assigned directly as a whole; but they can be assigned as data member by the implicity-defined copy assignment operator, for non-union class type it performs member-wise copy assignment of the non-static data member, including the array member and its elements.

Objects of array type cannot be modified as a whole: even though they
  are lvalues (e.g. an address of array can be taken), they cannot
  appear on the left hand side of an assignment operator:

```<code>int a[3] = {1, 2, 3}, b[3] = {4, 5, 6};
int (*p)[3] = &a; // okay: address of a can be taken
a = b;            // error: a is an array
struct { int c[3]; } s1, s2 = {3, 4, 5};
s1 = s2; // okay: implicity-defined copy assignment operator
         // can assign data members of array type
</code>```

Title: copying C-style arrays and structure

Body:
C++ does not allow copying of C-style arrays using =. But allows copying of structures using =, as in this link -> Copying array in C v/s copying structure in C.It does not have any credible answers yet.
 But consider following code

#include <iostream>
using namespace std;

struct user {
    int a[4];
    char c;
};

int main() {
    user a{{1,2,3,4}, 'a'}, b{{4,5,6,7}, 'b'};
    a = b;             //should have given any error or warning but nothing
    return 0;
}

Above code segment didn't gave any kind of errors and warnings, and just works fine. WHY?
Consider explaining both questions(this one and the one linked above).

Body:
Yes, the code should work fine. arrays can't be assigned directly as a whole; but they can be assigned as data member by the implicity-defined copy assignment operator, for non-union class type it performs member-wise copy assignment of the non-static data member, including the array member and its elements.

Objects of array type cannot be modified as a whole: even though they
  are lvalues (e.g. an address of array can be taken), they cannot
  appear on the left hand side of an assignment operator:

int a[3] = {1, 2, 3}, b[3] = {4, 5, 6};
int (*p)[3] = &a; // okay: address of a can be taken
a = b;            // error: a is an array
struct { int c[3]; } s1, s2 = {3, 4, 5};
s1 = s2; // okay: implicity-defined copy assignment operator
         // can assign data members of array type


问:
NSWindow problem
Please help me. I set frame to the window like this:

```<code>- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
[window makeKeyWindow];
[window setFrame:NSMakeRect(0, 0, 1024, 768) display:YES];
[window setBackgroundColor:[NSColor clearColor]];
[window center];
}
</code>```

But real window size: width = 1024, height = 620. I think because my screen size (1280x720).

So, when [window setContentView:myView], myView is disable a part.

I can't solve this problem. Please help me solve this.

Thanks.

答: If you want to show your window at the maximum size, have a look at NSWindow's -zoom: method

Title: NSWindow problem

Body:
Please help me. I set frame to the window like this:

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
// Insert code here to initialize your application
[window makeKeyWindow];
[window setFrame:NSMakeRect(0, 0, 1024, 768) display:YES];
[window setBackgroundColor:[NSColor clearColor]];
[window center];
}

But real window size: width = 1024, height = 620. I think because my screen size (1280x720).

So, when [window setContentView:myView], myView is disable a part.

I can't solve this problem. Please help me solve this.

Thanks.


问:
Regarding HHTPTrigger to retrieve a document from CosmosDB
I am trying to execute the HTTP Trigger azure function to retrieve a document from CosmosDB. I am trying to pass the id value in the URL, but not able to retrieve the document. I have got this sample code from learn.microsoft.com.

Function code:

```<code>import logging
import azure.functions as func
def main(req: func.HttpRequest, todoitems: func.DocumentList) -> str:
    if not todoitems:
        logging.warning("ToDo item not found")
    else:
        logging.info("Found ToDo item, Description=%s",
                     todoitems[0]['description'])

    return 'OK'
</code>```

function.json

```<code>{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "cosmosDB",
      "name": "todoitems",
      "databaseName": "ckdb",
      "collectionName": "cosmocontainer",
      "connectionStringSetting": "ckdb_DOCUMENTDB",
      "direction": "in",
      "id": "{id}",
      "PartitionKey": "{id}"
    }
  ],
  "disabled": true,
  "scriptFile": "__init__.py"
}
</code>```

URL:

```<code>http://localhost:7071/api/HttpTrigger1?id="3"
</code>```

Even though I have the document with id value as "3" in cosmosdb database, function is not able to retrieve the document. Please guide me to fix the error.

答:
I think the problems comes from the item in your cosmosdb.

It is not possible to get the specified item by simply providing the id. Multiple items can exist in the same id in a container.

Please have a look of my cosmosdb:

And this is my azure function:

init.py :

```<code>import logging

import azure.functions as func

def main(req: func.HttpRequest, documents: func.DocumentList) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    if not documents:
        logging.warning("ToDo item not found")
    else:
        logging.info("Found ToDo item")
    return 'OK'
</code>```

function.json :

```<code>{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    },
    {
      "name": "documents",
      "type": "cosmosDB",
      "databaseName": "testbowman",
      "collectionName": "testbowman",
      "id" : "1",
      "partitionKey": "1",
      "connectionStringSetting": "MyAccount_COSMOSDB",
      "direction": "in"
  }
  ]
}
</code>```

local.settings.json :

```<code>{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "MyAccount_COSMOSDB":"AccountEndpoint=https://testbowman.documents.azure.com:443/;AccountKey=xxxxxx;"
  }
}
</code>```

After i start my function, only item like this can be catch:

```<code>{
    "id": "1",
    "testbowman": "1"
}
</code>```

(This is because I have to provide the value of the partition key while providing the id. In my case, the partition key name is testbowman.)

When you actually use it, you do not need to fix the value to 1, you can specify the value of the corresponding parameter through {}.

You can see that I can successfully get here:

Body:
I am trying to execute the HTTP Trigger azure function to retrieve a document from CosmosDB. I am trying to pass the id value in the URL, but not able to retrieve the document. I have got this sample code from learn.microsoft.com.

Function code:

import logging
import azure.functions as func
def main(req: func.HttpRequest, todoitems: func.DocumentList) -> str:
    if not todoitems:
        logging.warning("ToDo item not found")
    else:
        logging.info("Found ToDo item, Description=%s",
                     todoitems[0]['description'])

    return 'OK'

function.json

{
  "bindings": [
    {
      "authLevel": "anonymous",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "cosmosDB",
      "name": "todoitems",
      "databaseName": "ckdb",
      "collectionName": "cosmocontainer",
      "connectionStringSetting": "ckdb_DOCUMENTDB",
      "direction": "in",
      "id": "{id}",
      "PartitionKey": "{id}"
    }
  ],
  "disabled": true,
  "scriptFile": "__init__.py"
}

URL:

http://localhost:7071/api/HttpTrigger1?id="3"

Even though I have the document with id value as "3" in cosmosdb database, function is not able to retrieve the document. Please guide me to fix the error.

Body:
I think the problems comes from the item in your cosmosdb.

It is not possible to get the specified item by simply providing the id. Multiple items can exist in the same id in a container.

Please have a look of my cosmosdb:

And this is my azure function:

init.py :

import logging

import azure.functions as func

def main(req: func.HttpRequest, documents: func.DocumentList) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')

    if not documents:
        logging.warning("ToDo item not found")
    else:
        logging.info("Found ToDo item")
    return 'OK'

function.json :

{
  "scriptFile": "__init__.py",
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "get",
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "$return"
    },
    {
      "name": "documents",
      "type": "cosmosDB",
      "databaseName": "testbowman",
      "collectionName": "testbowman",
      "id" : "1",
      "partitionKey": "1",
      "connectionStringSetting": "MyAccount_COSMOSDB",
      "direction": "in"
  }
  ]
}

local.settings.json :

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "",
    "FUNCTIONS_WORKER_RUNTIME": "python",
    "MyAccount_COSMOSDB":"AccountEndpoint=https://testbowman.documents.azure.com:443/;AccountKey=xxxxxx;"
  }
}

After i start my function, only item like this can be catch:

{
    "id": "1",
    "testbowman": "1"
}

(This is because I have to provide the value of the partition key while providing the id. In my case, the partition key name is testbowman.)

When you actually use it, you do not need to fix the value to 1, you can specify the value of the corresponding parameter through {}.

You can see that I can successfully get here:


问:
How to send system notifications for windows in golang
I want to send a system notifications to windows using golang.

How can this be done?
if you awnser contains a cross platform solution it would be even better.

答:
Finding system notification with Golang in 2020 and found this: https://github.com/gen2brain/beeep . It looks like currently still actively maintained.

Example from repo:

```<code>err := beeep.Notify("Title", "Message body", "assets/information.png")
if err != nil {
    panic(err)
}
</code>```

Even it works great, actually I feel that this app was made mainly for producing "beep" sound on the computer speaker. Based on the app name which is "beeep" :). You can check on example page if interest in makes those "beep" sound too.

Body:
Finding system notification with Golang in 2020 and found this: https://github.com/gen2brain/beeep . It looks like currently still actively maintained.

Example from repo:

err := beeep.Notify("Title", "Message body", "assets/information.png")
if err != nil {
    panic(err)
}

Even it works great, actually I feel that this app was made mainly for producing "beep" sound on the computer speaker. Based on the app name which is "beeep" :). You can check on example page if interest in makes those "beep" sound too.


问:
Cache Http requests using only RxJS operators
I'm trying to achieve what is described here: https://www.prestonlamb.com/blog/rxjs-cache-and-refresh-in-angular

In other words, I want to cache an observable, during a given time (let's say 1minute). When a subscription is made after that given time, data should be retrieved again and cache again for 1 minute.

Example of the expected result:

```<code>T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => RETRIEVE data
T 01:15: Request (6) => data from cache
T 01:30: Request (7) => data from cache
T 02:30: Request (8) => RETRIEVE data
</code>```

The shareReplay operator is working fine to cache data for a given time, but I'm not able to re-launch it when that given time is elapsed.

Example using shareRelay(1, 1000) operator:

```<code>T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => no response
T 01:15: Request (6) => no response
T 01:30: Request (7) => no response
T 02:30: Request (8) => no response
</code>```

The link above try to change that behavior using first operator catching null results. Unfortunately, it's not working fine as data is not cached after the first time.

Here's what I've got using the article of the above link (following picture is describing the code used)

Result I've got:

```<code>T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => RETRIEVE data
T 01:15: Request (6) => RETRIEVE data
T 01:30: Request (7) => RETRIEVE data
T 02:30: Request (8) => RETRIEVE data
</code>```

I've also seen some example with the timer operator, but in that cases, data is retrieved every minute, even if there is no subscribtion on it. I do not want to refresh data every minute, I want to expire cache every minute. Unfortunately, I've lost the code with the timer operator, but the result was something like that:

Result with timer operator:

```<code>T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:00: NO REQUEST => RETRIEVE data
T 01:10: Request (5) => data from cache
T 01:15: Request (6) => data from cache
T 01:30: Request (7) => data from cache
T 02:00: NO REQUEST => RETRIEVE data
T 02:30: Request (8) => data from cache
</code>```

Anyone with a "pure" RxJS solution to do what I want?

答:
I think that solution you provided a link for has a small bug, as I tried to highlight in this StackBlitz. (or I might have misunderstood the idea)

You could try this:

const refetchSbj = new Subject();
const refetchData$ = refetchSbj.pipe(
    switchMap(() => service.fetchData())
  ).pipe(share());

merge(
  src$,
  refetchData$
).pipe(
  shareReplay(1, 1000),
  buffer(concat(timer(0), refetchData$)),
  tap(values => !values.length && refetchSbj.next()),
  filter(values => values.length !== 0),
  // In case there is only one value,
  map(([v]) => v),
  // Might want to add this, because each subscriber will receive the value emitted by the `shareReplay`
  take(1)
)
```

<p><code>shareReplay</code> internally uses a <code>ReplaySubject</code>, which emits all the cached values <strong>synchronously</strong> to a new subscriber. <code>timer(0)</code> is similar to <code>setTimeout(fn, 0)</code>, but the important aspect here is that it's <strong>asynchronous</strong>, which allows <code>buffer</code> to collect the values emitted by the <code>ReplaySubject</code>. </p>

<p><code>buffer(concat(timer(0), refetchData$)),</code> - we want to make sure that the inner observable provided to <code>buffer</code> does not complete, otherwise the entire stream would complete. <code>refetchData$</code> will emit the newly fetched data when it's the case(we'll see when a bit later).</p>

<p><code>tap(values => !values.length && refetchSbj.next())</code> - if no values were emitted, it means that the <code>ReplaySubject</code> in use does not have any values, which means that time has passed. If that's the case, with the help of <code>refetchSbj</code>, we can repopulate the cache.</p>

<hr>

<p>So this is how we could visualize the flow:</p>

```T 00:00: Request (1) => RETRIEVE data
1) `refetchSbj.next()`
2) shareReplay will send the value resulted from `service.fetchData()` to the subscriber
3) the newly fetched value will be added to the `buffer`, and then the `refetchData$` from `concat(timer(0), refetchData$)` will emit(this is why we've used `share()`), meaning that `values` will not be an empty array
4) take(1) is reached, the value will be sent to the subscriber and then it will complete, so the `ReplaySubject` from `shareReplay()` will have no subscribers.

T 00:10: Request (2) => data from cache
`values` will not be empty, so `refetchSbj` won't emit and `take(1)` will be reached

T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => RETRIEVE data
Same as `Request (1)`
T 01:15: Request (6) => data from cache
T 01:30: Request (7) => data from cache
T 02:30: Request (8) => RETRIEVE data
```

Body:
I'm trying to achieve what is described here: https://www.prestonlamb.com/blog/rxjs-cache-and-refresh-in-angular

In other words, I want to cache an observable, during a given time (let's say 1minute). When a subscription is made after that given time, data should be retrieved again and cache again for 1 minute.

Example of the expected result:

T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => RETRIEVE data
T 01:15: Request (6) => data from cache
T 01:30: Request (7) => data from cache
T 02:30: Request (8) => RETRIEVE data

The shareReplay operator is working fine to cache data for a given time, but I'm not able to re-launch it when that given time is elapsed.

Example using shareRelay(1, 1000) operator:

T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => no response
T 01:15: Request (6) => no response
T 01:30: Request (7) => no response
T 02:30: Request (8) => no response

The link above try to change that behavior using first operator catching null results. Unfortunately, it's not working fine as data is not cached after the first time.

Here's what I've got using the article of the above link (following picture is describing the code used)

Result I've got:

T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => RETRIEVE data
T 01:15: Request (6) => RETRIEVE data
T 01:30: Request (7) => RETRIEVE data
T 02:30: Request (8) => RETRIEVE data

I've also seen some example with the timer operator, but in that cases, data is retrieved every minute, even if there is no subscribtion on it. I do not want to refresh data every minute, I want to expire cache every minute. Unfortunately, I've lost the code with the timer operator, but the result was something like that:

Result with timer operator:

T 00:00: Request (1) => RETRIEVE data
T 00:10: Request (2) => data from cache
T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:00: NO REQUEST => RETRIEVE data
T 01:10: Request (5) => data from cache
T 01:15: Request (6) => data from cache
T 01:30: Request (7) => data from cache
T 02:00: NO REQUEST => RETRIEVE data
T 02:30: Request (8) => data from cache

Anyone with a "pure" RxJS solution to do what I want?

Body:
I think that solution you provided a link for has a small bug, as I tried to highlight in this StackBlitz. (or I might have misunderstood the idea)

You could try this:

const refetchSbj = new Subject();
const refetchData$ = refetchSbj.pipe(
    switchMap(() => service.fetchData())
  ).pipe(share());

merge(
  src$,
  refetchData$
).pipe(
  shareReplay(1, 1000),
  buffer(concat(timer(0), refetchData$)),
  tap(values => !values.length && refetchSbj.next()),
  filter(values => values.length !== 0),
  // In case there is only one value,
  map(([v]) => v),
  // Might want to add this, because each subscriber will receive the value emitted by the `shareReplay`
  take(1)
)

shareReplay internally uses a ReplaySubject, which emits all the cached values synchronously to a new subscriber. timer(0) is similar to setTimeout(fn, 0), but the important aspect here is that it's asynchronous, which allows buffer to collect the values emitted by the ReplaySubject.

buffer(concat(timer(0), refetchData$)), - we want to make sure that the inner observable provided to buffer does not complete, otherwise the entire stream would complete. refetchData$ will emit the newly fetched data when it's the case(we'll see when a bit later).

tap(values => !values.length && refetchSbj.next()) - if no values were emitted, it means that the ReplaySubject in use does not have any values, which means that time has passed. If that's the case, with the help of refetchSbj, we can repopulate the cache.

So this is how we could visualize the flow:

T 00:00: Request (1) => RETRIEVE data
1) `refetchSbj.next()`
2) shareReplay will send the value resulted from `service.fetchData()` to the subscriber
3) the newly fetched value will be added to the `buffer`, and then the `refetchData$` from `concat(timer(0), refetchData$)` will emit(this is why we've used `share()`), meaning that `values` will not be an empty array
4) take(1) is reached, the value will be sent to the subscriber and then it will complete, so the `ReplaySubject` from `shareReplay()` will have no subscribers.

T 00:10: Request (2) => data from cache
`values` will not be empty, so `refetchSbj` won't emit and `take(1)` will be reached

T 00:35: Request (3) => data from cache
T 00:50: Request (4) => data from cache
T 01:10: Request (5) => RETRIEVE data
Same as `Request (1)`
T 01:15: Request (6) => data from cache
T 01:30: Request (7) => data from cache
T 02:30: Request (8) => RETRIEVE data


问:
DotNetNuke: How to add paging to the core announcements module
Situation looks like this:

I need to add paging to the core announcement module in DotNetNuke. My client is adding more and more announcements and now the page is too long. I am using the announcements module for news.

The problem:

The announcements module does not have a paging system. Is there any way to add a paging system to it?

答:
The Announcements module is missing lots of key features. I'd recommend switching from it to one of the many Articles modules available.

Ventrian News Articles -
probably the most popular

DNN Simple
Article - New, free, and open
source, built by a core team member

Efficion's Articles Module - My
favorite, but then I built it

There are lots of other options out there as well.


问:
Deselecting the selected row in Xamarin forms list view
I have a list view. On Tapping the selected row, how do I deselect? If I select a different row which is not selected, it must select it. How do I do this? Thanks</p>

```<code>  <ListView x:Name="DimensionListView" HasUnevenRows="True"  ItemTapped="OnItemSelected"  SeparatorVisibility="Default" VerticalOptions="FillAndExpand"  >
</code>```

答:
```<code><ListView x:Name="DimensionListView" HasUnevenRows="True"  ItemTapped="OnItemSelected"  SeparatorVisibility="Default" VerticalOptions="FillAndExpand"  >
</code>```

Your on ItemSelected handler:

```<code>private void OnItemSelected(object sender, ItemTappedEventArgs e)
    {

        if (DimensionListView.SelectedItem == null)
        {
            return;
        }

        DimensionListView.SelectedItem = null;
    }
</code>```

Body:
I have a list view. On Tapping the selected row, how do I deselect? If I select a different row which is not selected, it must select it. How do I do this? Thanks

  <ListView x:Name="DimensionListView" HasUnevenRows="True"  ItemTapped="OnItemSelected"  SeparatorVisibility="Default" VerticalOptions="FillAndExpand"  >

Body:
<ListView x:Name="DimensionListView" HasUnevenRows="True"  ItemTapped="OnItemSelected"  SeparatorVisibility="Default" VerticalOptions="FillAndExpand"  >

Your on ItemSelected handler:

private void OnItemSelected(object sender, ItemTappedEventArgs e)
    {

        if (DimensionListView.SelectedItem == null)
        {
            return;
        }

        DimensionListView.SelectedItem = null;
    }


问:
Cannot Update Composer in Command Line
I am updating the composer and it shows up some error like below.

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

```<code>Problem 1
    - pusher/pusher-php-server v3.4.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - pusher/pusher-php-server v3.4.0 requires php >=5.4 <7.3 -> your PHP version (7.3.6) does not satisfy that requirement.
    - pusher/pusher-php-server v3.3.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - pusher/pusher-php-server v3.3.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - pusher/pusher-php-server 3.4.x-dev requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - Installation request for pusher/pusher-php-server ^3.3 -> satisfiable by pusher/pusher-php-server[3.4.x-dev, v3.3.0, v3.3.1, v3.4.0, v3.4.1].

  To enable extensions, verify that they are enabled in your .ini files:
    - C:\PHP7\php.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.
</code>```

答:
the pusher v3 doesn't support php version that higher than 7.3

there are some options :

first is downgrade the php to the requirement (not recomended), the second one is  use this command to upgrade the pusher to version 4

```<code>composer require pusher/pusher-php-server
</code>```

Title: Cannot Update Composer in Command Line

Body:
I am updating the composer and it shows up some error like below.

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of packages.

Problem 1
    - pusher/pusher-php-server v3.4.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - pusher/pusher-php-server v3.4.0 requires php >=5.4 <7.3 -> your PHP version (7.3.6) does not satisfy that requirement.
    - pusher/pusher-php-server v3.3.1 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - pusher/pusher-php-server v3.3.0 requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - pusher/pusher-php-server 3.4.x-dev requires ext-curl * -> the requested PHP extension curl is missing from your system.
    - Installation request for pusher/pusher-php-server ^3.3 -> satisfiable by pusher/pusher-php-server[3.4.x-dev, v3.3.0, v3.3.1, v3.4.0, v3.4.1].

  To enable extensions, verify that they are enabled in your .ini files:
    - C:\PHP7\php.ini
  You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

Body:
the pusher v3 doesn't support php version that higher than 7.3

there are some options :

first is downgrade the php to the requirement (not recomended), the second one is  use this command to upgrade the pusher to version 4

composer require pusher/pusher-php-server


问:
What is the right way to code this Observable to fetch location?
I'm writing an observable to help me fetch the user's country code (which is then later passed to a different Observable. This is what I've coded:

```<code>val tm: TelephonyManager = requireContext().getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
var countryCodeValue: String = tm.networkCountryIso.toUpperCase(Locale.ROOT)

disposables.add(Observable.just(countryCodeValue)
      .flatMap {
        if(it.isEmpty()) {
          rxLocation.location()
            .lastLocation()
            .flatMap {
              rxLocation.geocoding().fromLocation(it).map { item -> item.countryCode }
            }
        } else {
          Observable.just(it)
        }
      }
      .subscribe ({
        Timber.i("Got country code: %s", it)
      }, { error -> Timber.i("Got error $error")}))
</code>```

What am I doing here? Taking the country code from the Context.TELEPHONY_SERVICE. If it returns empty string, then call RxLocation operators to get the geocoded country code value based on user location.

The it.isEmpty() block completely fails and gives an error saying "Type Mismatch". This is surprising since the flatMap should be emitting a string as expected however it doesn't. How to fix this?

答:
Solved it after reading comment by Mark Keen that I should be using a flapMapMaybe.

The working code is now:

```<code>disposables.add(Observable.just(countryCodeValue)
    .flatMapMaybe {
        if(it.isEmpty()) {
            rxLocation.location()
                .lastLocation()
                .flatMap {
                    rxLocation.geocoding().fromLocation(it).map { item -> item.countryCode }
                }
        } else {
            Maybe.just(it)
        }
    }
    .subscribe ({
        Timber.i("Got %s", it)
    }, { error -> Timber.i("Got error $error")}))
</code>```

Body:
I'm writing an observable to help me fetch the user's country code (which is then later passed to a different Observable. This is what I've coded:

val tm: TelephonyManager = requireContext().getSystemService(Context.TELEPHONY_SERVICE) as TelephonyManager
var countryCodeValue: String = tm.networkCountryIso.toUpperCase(Locale.ROOT)

disposables.add(Observable.just(countryCodeValue)
      .flatMap {
        if(it.isEmpty()) {
          rxLocation.location()
            .lastLocation()
            .flatMap {
              rxLocation.geocoding().fromLocation(it).map { item -> item.countryCode }
            }
        } else {
          Observable.just(it)
        }
      }
      .subscribe ({
        Timber.i("Got country code: %s", it)
      }, { error -> Timber.i("Got error $error")}))

What am I doing here? Taking the country code from the Context.TELEPHONY_SERVICE. If it returns empty string, then call RxLocation operators to get the geocoded country code value based on user location.

The it.isEmpty() block completely fails and gives an error saying "Type Mismatch". This is surprising since the flatMap should be emitting a string as expected however it doesn't. How to fix this?

Body:
Solved it after reading comment by Mark Keen that I should be using a flapMapMaybe.

The working code is now:

disposables.add(Observable.just(countryCodeValue)
    .flatMapMaybe {
        if(it.isEmpty()) {
            rxLocation.location()
                .lastLocation()
                .flatMap {
                    rxLocation.geocoding().fromLocation(it).map { item -> item.countryCode }
                }
        } else {
            Maybe.just(it)
        }
    }
    .subscribe ({
        Timber.i("Got %s", it)
    }, { error -> Timber.i("Got error $error")}))


问:
How do I use class variables from class and instance methods which are mixed in via a Module
I want to be able to make an option passed to my class method (auditable) available to instance methods. I'm mixing in both the class and instance methods using a Module.

The obvious choice is to use a class variable, but I get an error when trying access it:

uninitialized class variable @@auditable_only_once in Auditable

```<code>class Document
  include Auditable
  auditable :only_once => true
end

# The mixin
module Auditable
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def auditable(options = {})

      options[:only_once] ||= false

      class_eval do
        # SET THE OPTION HERE!!
        @@auditable_only_once = options[:only_once]
      end
      end
    end

    private

    def audit(action)
      # AND READ IT BACK LATER HERE
      return if @@auditable_only_once && self.audit_item
      AuditItem.create(:auditable => self, :tag => "#{self.class.to_s}_#{action}".downcase, :user => self.student)
    end
  end
</code>```

I've stripped out some of the code to make this a bit easier to read, the full code is here: https://gist.github.com/1004399 (EDIT: Gist now includes the solution)

答:
Using @@ class instance variables is irregular and the number of of occasions when they're strictly required is exceedingly rare. Most of the time they just seem to cause trouble or confusion. Generally you can use regular instance variables in the class context without issue.

What you might want to do is use a different template for this sort of thing. If you have mattr_accessor, which is provided by ActiveSupport, you may want to use that instead of that variable, or you can always write your own equivalent in your ClassMethods component.

One approach I've used is to break up your extension into two modules, a hook and an implementation. The hook only adds the methods to the base class that can be used to add the rest of the methods if required, but otherwise doesn't pollute the namespace:

```<code>module ClassExtender
  def self.included(base)
    base.send(:extend, self)
  end

  def engage(options = { })
    extend ClassExtenderMethods::ClassMethods
    include ClassExtenderMethods::InstanceMethods

    self.class_extender_options.merge!(options)
  end
end
</code>```

This engage method can be called anything you like, as in your example it is auditable.

Next you create a container module for the class and instance methods that the extension adds when it is exercised:

```<code>module ClassExtenderMethods
  module ClassMethods
    def class_extender_options
      @class_extender_options ||= {
        :default_false => false
      }
    end
  end

  module InstanceMethods
    def instance_method_example
      :example
    end
  end
end
</code>```

In this case there is a simple method class_extender_options that can be used to query or modify the options for a particular class. This avoids having to use the instance variable directly. An example instance method is also added.

You can define a simple example:

```<code>class Foo
  include ClassExtender

  engage(:true => true)
end
</code>```

Then test that it is working properly:

```<code>Foo.class_extender_options
# => {:default_false=>false, :true=>true}

foo = Foo.new
foo.instance_method_example
# => :example
</code>```

Body:
I want to be able to make an option passed to my class method (auditable) available to instance methods. I'm mixing in both the class and instance methods using a Module.

The obvious choice is to use a class variable, but I get an error when trying access it:

uninitialized class variable @@auditable_only_once in Auditable

class Document
  include Auditable
  auditable :only_once => true
end

# The mixin
module Auditable
  def self.included(base)
    base.extend(ClassMethods)
  end

  module ClassMethods
    def auditable(options = {})

      options[:only_once] ||= false

      class_eval do
        # SET THE OPTION HERE!!
        @@auditable_only_once = options[:only_once]
      end
      end
    end

    private

    def audit(action)
      # AND READ IT BACK LATER HERE
      return if @@auditable_only_once && self.audit_item
      AuditItem.create(:auditable => self, :tag => "#{self.class.to_s}_#{action}".downcase, :user => self.student)
    end
  end

I've stripped out some of the code to make this a bit easier to read, the full code is here: https://gist.github.com/1004399 (EDIT: Gist now includes the solution)

Body:
Using @@ class instance variables is irregular and the number of of occasions when they're strictly required is exceedingly rare. Most of the time they just seem to cause trouble or confusion. Generally you can use regular instance variables in the class context without issue.

What you might want to do is use a different template for this sort of thing. If you have mattr_accessor, which is provided by ActiveSupport, you may want to use that instead of that variable, or you can always write your own equivalent in your ClassMethods component.

One approach I've used is to break up your extension into two modules, a hook and an implementation. The hook only adds the methods to the base class that can be used to add the rest of the methods if required, but otherwise doesn't pollute the namespace:

module ClassExtender
  def self.included(base)
    base.send(:extend, self)
  end

  def engage(options = { })
    extend ClassExtenderMethods::ClassMethods
    include ClassExtenderMethods::InstanceMethods

    self.class_extender_options.merge!(options)
  end
end

This engage method can be called anything you like, as in your example it is auditable.

Next you create a container module for the class and instance methods that the extension adds when it is exercised:

module ClassExtenderMethods
  module ClassMethods
    def class_extender_options
      @class_extender_options ||= {
        :default_false => false
      }
    end
  end

  module InstanceMethods
    def instance_method_example
      :example
    end
  end
end

In this case there is a simple method class_extender_options that can be used to query or modify the options for a particular class. This avoids having to use the instance variable directly. An example instance method is also added.

You can define a simple example:

class Foo
  include ClassExtender

  engage(:true => true)
end

Then test that it is working properly:

Foo.class_extender_options
# => {:default_false=>false, :true=>true}

foo = Foo.new
foo.instance_method_example
# => :example


问:
React Navigation Header Button (V5 / Version 5.x): Show Menu Item
I am using React-Native-Paper's Menu Component

I am trying to show Menu item from the header after tapping an icon.

So far I have managed to show list of item on the screen only.

However, I want to show the menu list from the header.

Due to React Navigation's update from version:4.x to version:5.x, I am a bit confused on how to work this out. I tried following the example here but still I need some time to fully understand hook and the way it works.

All kinds of help would be appreciated.

Workable/Testable code link, code snippets and screenshots provided below:

Snack Link

Register.js:

```<code>import { TextInput, Button, Menu, Divider, Provider } from 'react-native-paper';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';

class Register extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    }
  }

  //[ TEST DROP DOWN MENU ]
  _openMenu = () => this.setState({ visible: true });

  _closeMenu = () => this.setState({ visible: false });

  renderMenuExample() {
    return (
      <View
        style={{
          paddingTop: 50,
          flexDirection: 'row',
          justifyContent: 'center'
        }}>
        <Menu
          visible={this.state.visible}
          onDismiss={this._closeMenu}
          anchor={
            < TouchableOpacity
              onPress={this._openMenu}
              style={{ marginHorizontal: 20 }}
            >
              <MaterialCommunityIcons name="earth" size={30} style={{ color: 'black' }} />
            </TouchableOpacity>
          }
        >
          <Menu.Item onPress={() => { }} title="Item 1" />
          <Menu.Item onPress={() => { }} title="Item 2" />
          <Divider />
          <Menu.Item onPress={() => { }} title="Item 3" />
        </Menu>
      </View>
    );
  }
  //[ TEST DROP DOWN MENU ]

  render() {
    return (
      <Provider>
        {this.renderMenuExample()}
      </Provider>
    );
  }
}

export default Register;
</code>```

App.js:

```<code>import { TextInput, Button, Menu, Divider, Provider } from 'react-native-paper';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import AntDesign from 'react-native-vector-icons/AntDesign';

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Register"
          component={Register}
          options={{
            headerBackImage: () => (
              <AntDesign name="close" size={30} style={{ color: 'white' }} />
            ),
            headerTitle: () => (
              <View>
                <Text style={{ flex: 1, fontSize: 20, fontWeight: 'bold', alignSelf: 'center', color:                   'white' }}>
                  Register
                </Text>
              </View>
            ),
            headerRight: () => (
              <TouchableOpacity
                onPress={() => {/* I WANT TO SHOW THE MENU HERE */ }}
                style={{ marginHorizontal: 20 }}
              >
                <MaterialCommunityIcons name="earth" size={30} style={{ color: 'white' }} />
              </TouchableOpacity>
            ),
            headerStyle: {
              backgroundColor: '#2e46ff',
            },
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;
</code>```

Screenshot:

答:
One possible solution would be to wrap the navigation container with a provider and have a separate component for the menu.
Tried this with your snack and it works

The code would be as below.

```<code>const CustomMenu = () => {
  const [showMenu, setShowMenu] = React.useState(false);

  return (
    <View style={{}}>
      <Menu
        visible={showMenu}
        onDismiss={() => setShowMenu(false)}
        anchor={
          <TouchableOpacity onPress={() => setShowMenu(true)}>
            <MaterialCommunityIcons
              name="earth"
              size={30}
              style={{ color: 'black' }}
            />
          </TouchableOpacity>
        }>
        <Menu.Item onPress={() => {}} title="Item 1" />
        <Menu.Item onPress={() => {}} title="Item 2" />
        <Divider />
        <Menu.Item onPress={() => {}} title="Item 3" />
      </Menu>
    </View>
  );
};

function App() {
  return (
    <Provider>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen
            name="Register"
            component={Register}
            options={{
              headerBackImage: () => (
                <AntDesign name="close" size={30} style={{ color: 'white' }} />
              ),
              headerTitle: () => (
                <View>
                  <Text
                    style={{
                      flex: 1,
                      fontSize: 20,
                      fontWeight: 'bold',
                      alignSelf: 'center',
                      color: 'white',
                    }}>
                    Register
                  </Text>
                </View>
              ),
              headerRight: () => <CustomMenu />,
              headerStyle: {
                backgroundColor: '#2e46ff',
              },
            }}
          />
        </Stack.Navigator>
      </NavigationContainer>
    </Provider>
  );
}
</code>```

Body:
I am using React-Native-Paper's Menu Component

I am trying to show Menu item from the header after tapping an icon.

So far I have managed to show list of item on the screen only.

However, I want to show the menu list from the header.

Due to React Navigation's update from version:4.x to version:5.x, I am a bit confused on how to work this out. I tried following the example here but still I need some time to fully understand hook and the way it works.

All kinds of help would be appreciated.

Workable/Testable code link, code snippets and screenshots provided below:

Snack Link

Register.js:

import { TextInput, Button, Menu, Divider, Provider } from 'react-native-paper';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';

class Register extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    }
  }

  //[ TEST DROP DOWN MENU ]
  _openMenu = () => this.setState({ visible: true });

  _closeMenu = () => this.setState({ visible: false });

  renderMenuExample() {
    return (
      <View
        style={{
          paddingTop: 50,
          flexDirection: 'row',
          justifyContent: 'center'
        }}>
        <Menu
          visible={this.state.visible}
          onDismiss={this._closeMenu}
          anchor={
            < TouchableOpacity
              onPress={this._openMenu}
              style={{ marginHorizontal: 20 }}
            >
              <MaterialCommunityIcons name="earth" size={30} style={{ color: 'black' }} />
            </TouchableOpacity>
          }
        >
          <Menu.Item onPress={() => { }} title="Item 1" />
          <Menu.Item onPress={() => { }} title="Item 2" />
          <Divider />
          <Menu.Item onPress={() => { }} title="Item 3" />
        </Menu>
      </View>
    );
  }
  //[ TEST DROP DOWN MENU ]

  render() {
    return (
      <Provider>
        {this.renderMenuExample()}
      </Provider>
    );
  }
}

export default Register;

App.js:

import { TextInput, Button, Menu, Divider, Provider } from 'react-native-paper';
import MaterialCommunityIcons from 'react-native-vector-icons/MaterialCommunityIcons';
import AntDesign from 'react-native-vector-icons/AntDesign';

const Stack = createStackNavigator();

function App() {
  return (
    <NavigationContainer>
      <Stack.Navigator>
        <Stack.Screen
          name="Register"
          component={Register}
          options={{
            headerBackImage: () => (
              <AntDesign name="close" size={30} style={{ color: 'white' }} />
            ),
            headerTitle: () => (
              <View>
                <Text style={{ flex: 1, fontSize: 20, fontWeight: 'bold', alignSelf: 'center', color:                   'white' }}>
                  Register
                </Text>
              </View>
            ),
            headerRight: () => (
              <TouchableOpacity
                onPress={() => {/* I WANT TO SHOW THE MENU HERE */ }}
                style={{ marginHorizontal: 20 }}
              >
                <MaterialCommunityIcons name="earth" size={30} style={{ color: 'white' }} />
              </TouchableOpacity>
            ),
            headerStyle: {
              backgroundColor: '#2e46ff',
            },
          }}
        />
      </Stack.Navigator>
    </NavigationContainer>
  );
}

export default App;

Screenshot:

Body:
One possible solution would be to wrap the navigation container with a provider and have a separate component for the menu.
Tried this with your snack and it works

The code would be as below.

const CustomMenu = () => {
  const [showMenu, setShowMenu] = React.useState(false);

  return (
    <View style={{}}>
      <Menu
        visible={showMenu}
        onDismiss={() => setShowMenu(false)}
        anchor={
          <TouchableOpacity onPress={() => setShowMenu(true)}>
            <MaterialCommunityIcons
              name="earth"
              size={30}
              style={{ color: 'black' }}
            />
          </TouchableOpacity>
        }>
        <Menu.Item onPress={() => {}} title="Item 1" />
        <Menu.Item onPress={() => {}} title="Item 2" />
        <Divider />
        <Menu.Item onPress={() => {}} title="Item 3" />
      </Menu>
    </View>
  );
};

function App() {
  return (
    <Provider>
      <NavigationContainer>
        <Stack.Navigator>
          <Stack.Screen
            name="Register"
            component={Register}
            options={{
              headerBackImage: () => (
                <AntDesign name="close" size={30} style={{ color: 'white' }} />
              ),
              headerTitle: () => (
                <View>
                  <Text
                    style={{
                      flex: 1,
                      fontSize: 20,
                      fontWeight: 'bold',
                      alignSelf: 'center',
                      color: 'white',
                    }}>
                    Register
                  </Text>
                </View>
              ),
              headerRight: () => <CustomMenu />,
              headerStyle: {
                backgroundColor: '#2e46ff',
              },
            }}
          />
        </Stack.Navigator>
      </NavigationContainer>
    </Provider>
  );
}


问:
Total Row Count of an Interactive Grid as a Select List
I have an interactive grid, which contains more than 200000 rows of data. Instead of having page numbers listed below, is there any way I can have a drop down select list, which contains options such as 1-40 records, 40-80 records, and so on. So that the user can go directly to the end of the report.

Is there any way to implement this?

答:
so what you essentially need is a sequence in a SELECT that is big enough.
I think this should work for you

```<code>select LEVEL
  FROM DUAL
CONNECT BY LEVEL <= CEIL(:rowcount / 40);
</code>```

What this does is create a sequence up to the CEIL(:rowcount/40) number, so if that number is 3, the result is 1, 2, 3.

Then you can play around with this to display as 0-40, 40-80, 80-120,...
Hope this does what you need.

EDIT TO ANSWER COMMENT(Changing total row count at the bottom):

I dont think this is made possible in APEX, but it can be acomplished with js.

I would suggest you make a DA that runs on start and every time the Select list you are now using is changed. The DA will generate the current text you want down there, say for selection 40-80 you say "1 of 567" or whatever, then you will have to set this text with js.

If you are not already you will have to get used to the js console.

You will have to set a static ID to the grid, then run js that looks something like this:

```<code>var temp = $("span#dn_main_ig_grid_vc_pageRange")[0]
temp.children[1].innerText = "text"
</code>```

Where dn_main is the static ID of my grid, so substitute that with yours. You should open up the console and go step by step and see what you are selecting with each step. Then once you understand what this is doing, you can use it in your DA to change the "text" to whatever you need there.

And for getting the value of a page item in js, in case you are not familiar,
https://apex.oracle.com/pls/apex/germancommunities/apexcommunity/tipp/6341/index-en.html

I hope this helps

Body:
so what you essentially need is a sequence in a SELECT that is big enough.
I think this should work for you

select LEVEL
  FROM DUAL
CONNECT BY LEVEL <= CEIL(:rowcount / 40);

What this does is create a sequence up to the CEIL(:rowcount/40) number, so if that number is 3, the result is 1, 2, 3.

Then you can play around with this to display as 0-40, 40-80, 80-120,...
Hope this does what you need.

EDIT TO ANSWER COMMENT(Changing total row count at the bottom):

I dont think this is made possible in APEX, but it can be acomplished with js.

I would suggest you make a DA that runs on start and every time the Select list you are now using is changed. The DA will generate the current text you want down there, say for selection 40-80 you say "1 of 567" or whatever, then you will have to set this text with js.

If you are not already you will have to get used to the js console.

You will have to set a static ID to the grid, then run js that looks something like this:

var temp = $("span#dn_main_ig_grid_vc_pageRange")[0]
temp.children[1].innerText = "text"

Where dn_main is the static ID of my grid, so substitute that with yours. You should open up the console and go step by step and see what you are selecting with each step. Then once you understand what this is doing, you can use it in your DA to change the "text" to whatever you need there.

And for getting the value of a page item in js, in case you are not familiar,
https://apex.oracle.com/pls/apex/germancommunities/apexcommunity/tipp/6341/index-en.html

I hope this helps


问:
How to switch between light and dark theme dynamically in app using composables
How would you dynamically switch between theme's color palette with a press of a button inside the app

This is what I am doing so far, but only works when I switch the Android Theme to dark or light mode

AppTheme.Kt

```<code>@Model
object ThemeState {
    var isLight: Boolean = true
}

@Composable
fun MyAppTheme(
    children: @Composable() () -> Unit
) {
    MaterialTheme(colors = if (ThemeState.isLight) themeColorsLight else themColorDark) {
            children()
    }
}
</code>```

MainActivity.kt

```<code>class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyAppTheme(children = {
                Surface {
                    Greetings(name = "Android")
                }

            })

        }
    }
}

@Composable
fun Greetings(name: String) {

    Column(modifier = Modifier.fillMaxHeight()) {
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = "Hello $name", modifier = Modifier.padding(24.dp),
                style = MaterialTheme.typography.h1
            )
        }

        Button(onClick = { ThemeState.isLight = !ThemeState.isLight }) {
            Text(text = "Change Theme IsLight:${ThemeState.isLight}")
        }
    }
}

</code>```

答:
At the moment I don't have any Idea why your code not works, I'll update this answer when I find out.

but instead of using if else for colors parameter use it for the whole MaterialTheme like this and it will work:

```<code>@Composable
fun MyAppTheme(
    children: @Composable() () -> Unit
) {

    if (ThemeState.isLight) {
        MaterialTheme(colors = themeColorsLight) {
            children()
        }
    } else {
        MaterialTheme(colors = themColorDark) {
            children()
        }

    }
}
</code>```

Update:
seems that it's bug in Jetpack Compose dev11, I tried in dev12 and it works there.

NOTE 1:
@Model has been deprecated in dev 12
change your ThemeState to

object ThemeState {
    var isLight by mutableStateOf(true)
}
```
<p>more information: https://android-review.googlesource.com/c/platform/frameworks/support/+/1311293</p>
<p><strong>NOTE 2</strong>
There are some problems with auto Import in recent versions of AndroidStudio
If the Idea throws error: <code>Type 'MutableState<TypeVariable(T)>' has no method 'getValue(ThemeState, KProperty<*>)' and thus it cannot serve as a delegate</code></p>
<p>Import <code>getValue</code> and <code>SetValue</code> manually.</p>
<pre class="lang-kotlin prettyprint-override"><code>import androidx.compose.getValue
import androidx.compose.setValue
</code>```

Since 0.1.0-dev16 use these imports:

import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue

```

Body:
How would you dynamically switch between theme's color palette with a press of a button inside the app

This is what I am doing so far, but only works when I switch the Android Theme to dark or light mode

AppTheme.Kt

@Model
object ThemeState {
    var isLight: Boolean = true
}

@Composable
fun MyAppTheme(
    children: @Composable() () -> Unit
) {
    MaterialTheme(colors = if (ThemeState.isLight) themeColorsLight else themColorDark) {
            children()
    }
}

MainActivity.kt

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            MyAppTheme(children = {
                Surface {
                    Greetings(name = "Android")
                }

            })

        }
    }
}

@Composable
fun Greetings(name: String) {

    Column(modifier = Modifier.fillMaxHeight()) {
        Column(modifier = Modifier.weight(1f)) {
            Text(
                text = "Hello $name", modifier = Modifier.padding(24.dp),
                style = MaterialTheme.typography.h1
            )
        }

        Button(onClick = { ThemeState.isLight = !ThemeState.isLight }) {
            Text(text = "Change Theme IsLight:${ThemeState.isLight}")
        }
    }
}

Body:
At the moment I don't have any Idea why your code not works, I'll update this answer when I find out.

but instead of using if else for colors parameter use it for the whole MaterialTheme like this and it will work:

@Composable
fun MyAppTheme(
    children: @Composable() () -> Unit
) {

    if (ThemeState.isLight) {
        MaterialTheme(colors = themeColorsLight) {
            children()
        }
    } else {
        MaterialTheme(colors = themColorDark) {
            children()
        }

    }
}

Update:
seems that it's bug in Jetpack Compose dev11, I tried in dev12 and it works there.

NOTE 1:
@Model has been deprecated in dev 12
change your ThemeState to

object ThemeState {
    var isLight by mutableStateOf(true)
}

more information: https://android-review.googlesource.com/c/platform/frameworks/support/+/1311293

NOTE 2
There are some problems with auto Import in recent versions of AndroidStudio
If the Idea throws error: Type 'MutableState<TypeVariable(T)>' has no method 'getValue(ThemeState, KProperty<*>)' and thus it cannot serve as a delegate

Import getValue and SetValue manually.

import androidx.compose.getValue
import androidx.compose.setValue

Since 0.1.0-dev16 use these imports:

import androidx.compose.runtime.getValue
import androidx.compose.runtime.setValue


问:
Getting the string in the middle of two other strings in Python
I need to find the string in between two other strings. How could I do this?

```<code>string = "vHELLOv"
</code>```

Finding "HELLO" which is in between of two lowercase "v"'s

Another example could be:

```<code>string = "/World/"
</code>```

Finding "World" in the middle of the two "/"s

答:
If you are talking about two identical strings surrounding another, you can use the split method: </p>

```<code>string = "vHELLOv"
surrounder = "v"
x = string.split(surrounder)

print(x[1])
</code>```

Body:
I need to find the string in between two other strings. How could I do this?

string = "vHELLOv"

Finding "HELLO" which is in between of two lowercase "v"'s

Another example could be:

string = "/World/"

Finding "World" in the middle of the two "/"s

Body:
If you are talking about two identical strings surrounding another, you can use the split method:

string = "vHELLOv"
surrounder = "v"
x = string.split(surrounder)

print(x[1])


问:
Cloudera installation failed to detect root privileges on CentOS
I tried to adding new host into the cluster o CentOS. It fails on install & gives "Installation failed. Failed to detect root privileges" in status.
I know that Cloudera needs user to have passwordless privileges ("Root access to your hosts is required to install the Cloudera packages. This installer will connect to your hosts via SSH and log in either directly as root or as another user with password-less sudo/pbrun privileges to become root."). How can I achieve that? I tried to edit the /etc/sudoers file.
EDIT: in sudoers file, I added the line:

cdh  ALL=(ALL): ALL #cdh is my username

just under where permissions for 'root' is defined.

but with no more success at the install. In the Details window, it says:

```<code>Detecting root privileges...
effective UID is 502
BEGIN which pbrun
END (1)
BEGIN sudo -S id
[sudo] password for cdh:
Sorry, try again.
[sudo] password for cdh:
Sorry, try again.
[sudo] password for cdh:
Sorry, try again.
sudo: 3 incorrect password attempts
END (1)
need root privileges but sudo requires password, exiting
closing logging file descriptor.
</code>```

Any sort of help will be highly appreciated.

答:
In /etc/sudoers uncomment this line

```<code>## Same thing without a password
%wheel ALL=(ALL) NOPASSWD: ALL
</code>```

Body:
I tried to adding new host into the cluster o CentOS. It fails on install & gives "Installation failed. Failed to detect root privileges" in status.
I know that Cloudera needs user to have passwordless privileges ("Root access to your hosts is required to install the Cloudera packages. This installer will connect to your hosts via SSH and log in either directly as root or as another user with password-less sudo/pbrun privileges to become root."). How can I achieve that? I tried to edit the /etc/sudoers file.
EDIT: in sudoers file, I added the line:

cdh  ALL=(ALL): ALL #cdh is my username

just under where permissions for 'root' is defined.

but with no more success at the install. In the Details window, it says:

Detecting root privileges...
effective UID is 502
BEGIN which pbrun
END (1)
BEGIN sudo -S id
[sudo] password for cdh:
Sorry, try again.
[sudo] password for cdh:
Sorry, try again.
[sudo] password for cdh:
Sorry, try again.
sudo: 3 incorrect password attempts
END (1)
need root privileges but sudo requires password, exiting
closing logging file descriptor.

Any sort of help will be highly appreciated.

Body:
In /etc/sudoers uncomment this line

## Same thing without a password
%wheel ALL=(ALL) NOPASSWD: ALL


答:
Try this. Use regex (regular expression) library for pattern matching.

import re

# 1st pattern: vHELLOv
re.findall(r"v(.*?)v", "vHELLOv")

# 2nd pattern: /HELLO/
re.findall(r"/(.*?)/", "/HELLO/")

## NOTE: For regex in python you do not have to escape / with a \.
#        But, if you want to use a similar regex universally elsewhere,
#        consider escaping each / with a \.
#
#        Example: r"/(.*?)/" ==> r"\/(.*?)\/"

```

EDIT: Added lazy quantifier .*? instead of .* inside the () as suggested by Jan.

pattern: r"v(.*)v" Greedy --> Example on regex101.com

pattern: r"v(.*?)v" Lazy --> Example on regex101.com BETTER

Title: Getting the string in the middle of two other strings in Python

Body:
Try this. Use regex (regular expression) library for pattern matching.

import re

# 1st pattern: vHELLOv
re.findall(r"v(.*?)v", "vHELLOv")

# 2nd pattern: /HELLO/
re.findall(r"/(.*?)/", "/HELLO/")

## NOTE: For regex in python you do not have to escape / with a \.
#        But, if you want to use a similar regex universally elsewhere,
#        consider escaping each / with a \.
#
#        Example: r"/(.*?)/" ==> r"\/(.*?)\/"

EDIT: Added lazy quantifier .*? instead of .* inside the () as suggested by Jan.

pattern: r"v(.*)v" Greedy --> Example on regex101.com

pattern: r"v(.*?)v" Lazy --> Example on regex101.com BETTER


问:
Programmatically determine pip 'user install' location Scripts directory
As explained in pip's documentation a user can install packages in his personal account using pip install --user <pkg>.

How can I programmatically determine the user install location for scripts installed like this? I am talking about the directory that should be added to the PATH so that installed packages can be invoked from command line.

For example, in Windows when installing pip install -U pylint --user I get the following warning because I don't have 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' in my PATH:

```<code>...
Installing collected packages: wrapt, six, typed-ast, lazy-object-proxy, astroid, mccabe, isort, colorama, toml, pylint
  Running setup.py install for wrapt ... done
  WARNING: The script isort.exe is installed in 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts epylint.exe, pylint.exe, pyreverse.exe and symilar.exe are installed in 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' which is not on PATH.
</code>```

Is there some python code I can use to determine that location programmatically (that will work on Windows/Linux/Darwin/etc)? Something like:

```<code>def get_user_install_scripts_dir():
    ...
    # would return 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts'
    # on Windows with Python 3.7.x, '/home/myusername/.local/bin' in Linux, etc
    return platform_scripts_dir
</code>```

As a fallback, is there some command I can run to obtain this location? Something like (but for the script location not the site's base directory):

```<code>PS C:\Users\myusername\> python -m site --user-base
C:\Users\myusername\AppData\Roaming\Python

$ python -m site --user-base
/home/myusername/.local
</code>```

答:
I believe the following should give the expected result

```<code>import os
import sysconfig

user_scripts_path = sysconfig.get_path('scripts', f'{os.name}_user')
print(user_scripts_path)
</code>```

Command-line:

```<code>python -c 'import os,sysconfig;print(sysconfig.get_path("scripts",f"{os.name}_user"))'
</code>```

Since pip 21.3 released on 2021-10-11, pip itself uses sysconfig to compute paths.

References:

https://docs.python.org/3/library/sysconfig.html#installation-paths

https://docs.python.org/3/library/os.html#os.name

https://discuss.python.org/t/proper-way-to-determine-install-location-of-console-scripts/7188

pip 21.3 "Deprecations and removals"

github.com/pypa/pip/pull/10358 "Switch install scheme backend to sysconfig"

Body:
As explained in pip's documentation a user can install packages in his personal account using pip install --user <pkg>.

How can I programmatically determine the user install location for scripts installed like this? I am talking about the directory that should be added to the PATH so that installed packages can be invoked from command line.

For example, in Windows when installing pip install -U pylint --user I get the following warning because I don't have 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' in my PATH:

...
Installing collected packages: wrapt, six, typed-ast, lazy-object-proxy, astroid, mccabe, isort, colorama, toml, pylint
  Running setup.py install for wrapt ... done
  WARNING: The script isort.exe is installed in 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' which is not on PATH.
  Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.
  WARNING: The scripts epylint.exe, pylint.exe, pyreverse.exe and symilar.exe are installed in 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts' which is not on PATH.

Is there some python code I can use to determine that location programmatically (that will work on Windows/Linux/Darwin/etc)? Something like:

def get_user_install_scripts_dir():
    ...
    # would return 'C:\Users\myusername\AppData\Roaming\Python\Python37\Scripts'
    # on Windows with Python 3.7.x, '/home/myusername/.local/bin' in Linux, etc
    return platform_scripts_dir

As a fallback, is there some command I can run to obtain this location? Something like (but for the script location not the site's base directory):

PS C:\Users\myusername\> python -m site --user-base
C:\Users\myusername\AppData\Roaming\Python

$ python -m site --user-base
/home/myusername/.local

Body:
I believe the following should give the expected result

import os
import sysconfig

user_scripts_path = sysconfig.get_path('scripts', f'{os.name}_user')
print(user_scripts_path)

Command-line:

python -c 'import os,sysconfig;print(sysconfig.get_path("scripts",f"{os.name}_user"))'

Since pip 21.3 released on 2021-10-11, pip itself uses sysconfig to compute paths.

References:

https://docs.python.org/3/library/sysconfig.html#installation-paths

https://docs.python.org/3/library/os.html#os.name

https://discuss.python.org/t/proper-way-to-determine-install-location-of-console-scripts/7188

pip 21.3 "Deprecations and removals"

github.com/pypa/pip/pull/10358 "Switch install scheme backend to sysconfig"


问:
How many bits is a WORD and is that constant over different architectures?
Is a machine WORD always the same or does it depend on the machine architecture?
And is the meaning of the word WORD context sensitive or generally applicable?

答:
A "word" in small letters depends on the architecture.

A "WORD" in capital letters, as defined in Windows SDK, is 16 bits.

Similarly:
"DWORD" - (double word) 32 bits.
"QWORD" ...             64 bits.

OwnerDisplayName: mixedpickles

OwnerDisplayName: Jimmy J

ContentLicense: CC BY-SA 2.5