问:
How to wait until an element exists?
I'm working on an Extension in Chrome, and I'm wondering: what's the best way to find out when an element comes into existence? Using plain javascript, with an interval that checks until an element exists, or does jQuery have some easy way to do this?</p>

答:
Update

Below there is an updated version that works with promises. It also "stops" if a specific number of tries is reached.

```<code>function _waitForElement(selector, delay = 50, tries = 100) {
    const element = document.querySelector(selector);

    if (!window[`__${selector}`]) {
      window[`__${selector}`] = 0;
      window[`__${selector}__delay`] = delay;
      window[`__${selector}__tries`] = tries;
    }

    function _search() {
      return new Promise((resolve) => {
        window[`__${selector}`]++;
        setTimeout(resolve, window[`__${selector}__delay`]);
      });
    }

    if (element === null) {
      if (window[`__${selector}`] >= window[`__${selector}__tries`]) {
        window[`__${selector}`] = 0;
        return Promise.resolve(null);
      }

      return _search().then(() => _waitForElement(selector));
    } else {
      return Promise.resolve(element);
    }
  }
</code>```

Usage is very simple, to use it with await just make sure you're within an
async function:

```<code>const start = (async () => {
  const $el = await _waitForElement(`.my-selector`);
  console.log($el);
})();
</code>```

Outdated version

Simply add the selector you want. Once the element is found you can have access to in the callback function.

```<code>const waitUntilElementExists = (selector, callback) => {
const el = document.querySelector(selector);

if (el){
    return callback(el);
}

setTimeout(() => waitUntilElementExists(selector, callback), 500);
}

waitUntilElementExists('.wait-for-me', (el) => console.log(el));
</code>```

Title: How to wait until an element exists?

Body:
Update

Below there is an updated version that works with promises. It also "stops" if a specific number of tries is reached.

function _waitForElement(selector, delay = 50, tries = 100) {
    const element = document.querySelector(selector);

    if (!window[`__${selector}`]) {
      window[`__${selector}`] = 0;
      window[`__${selector}__delay`] = delay;
      window[`__${selector}__tries`] = tries;
    }

    function _search() {
      return new Promise((resolve) => {
        window[`__${selector}`]++;
        setTimeout(resolve, window[`__${selector}__delay`]);
      });
    }

    if (element === null) {
      if (window[`__${selector}`] >= window[`__${selector}__tries`]) {
        window[`__${selector}`] = 0;
        return Promise.resolve(null);
      }

      return _search().then(() => _waitForElement(selector));
    } else {
      return Promise.resolve(element);
    }
  }

Usage is very simple, to use it with await just make sure you're within an
async function:

const start = (async () => {
  const $el = await _waitForElement(`.my-selector`);
  console.log($el);
})();

Outdated version

Simply add the selector you want. Once the element is found you can have access to in the callback function.

const waitUntilElementExists = (selector, callback) => {
const el = document.querySelector(selector);

if (el){
    return callback(el);
}

setTimeout(() => waitUntilElementExists(selector, callback), 500);
}

waitUntilElementExists('.wait-for-me', (el) => console.log(el));


来源: stackexchange

问:
Virtual Assistents Development Comparison: Alexa vs Google Home vs Siri vs Cortana
I would love to hear some advice from someone who has programmed for Alexa and any other virtual assistant.
I'm the only one in my team with experience with Alexa and just recently we have sold our first Alexa product. The client wants to know how expensive it would be to make the app also work for Siri/Google Home/Cortana but I have no idea about other virtual assistants and we don't really have time to dive deep into every assistants documentation.

That's where you could help me. Do you have any experience in programming for Alexa and any other mentioned virtual assistant? Maybe you have even tried them all? Which ones are the most similar (from the development point of view of course)? Do other assistance have the same intent/utterance/slots-logic as Alexa? The most interesting thing I want to find out is how much Alexa code we could actually reuse and how much time I would need to spend if I wanted to learn another frameworks granted that I already know Alexa API. Can you share your experiences on this topic?

Thank you very much for any advises.

PS forgot to mention, for Alexa we have made our own webservice endpoint and used Java

答:
Yes, I've developed for Alexa, Actions, Cortana, and Bixby.

All have similar "dialog design" guidance and support.  Some names change.

Alexa and Actions are, in my opinion, similar in architecture.

Cortana is different from an architectural point of view, because you can bridge the gap between a state-full application and a cloud serverless design.  Doing pure SOA and stateless for complex problems can, in my humble opinion, add tons of complexity and "breaking points".

Bixby is just odd; but if you want Samsung mobile...

From a language stand point, Google is JS/webhooks.  Cortana also supports JS/node fully, which is nice.  Cortana supports C# (first).

Reusing code... will be a problem.  You can reuse design, and possibly patterns, and if you built a RESTful microservice of course you can use it from any platform.

It took me about two weeks to learn each platform to a point I published skills. The hardest part (going from Cortana to Actions) was redesigning to be serverless (event based, like cloud functions/aws lambda).

.02

ContentLicense: CC BY-SA 4.0


问:
Django- Field appears as Null
I want to show the name of a field and not the ID of it, so I tried a couple of different methods but with nothing worked for me. I couldn't figure out why or find a suitable solution for this, so here it goes:
Basically, my views returns a null field when in fact it is not null. Code bellow.

tags = TagListSerializer() # Returns null

tags = serializers.Field(source='tags.name') # Returns null

tags = TagListSerializer # Doesn't change anything

Comercial inherits from Project which is abstract:

```<code>class Comercial(Project):
    name = models.CharField()
</code>```

Project is abstract:

```<code>class Project(models.Model):
    tags = models.ManyToManyField(Tag, blank=True, editable=True)
</code>```

The Tag Model:

```<code>class Tag(models.Model):
    name = models.CharField(null=False)
</code>```

The Comercial View which searches by tag:

```<code>class ListComercialAPIView(ListAPIView):
    serializer_class = ComercialListSerializer
    pagination_class = StandardResultsSetPagination

    def get_queryset(self):
        tag = self.request.GET.get('tag')
        if(tag!=None):
            return Comercial.objects.filter(tags__name=tag)
        else:
            return Comercial.objects.all()
</code>```

The Tag Serializer:

```<code>class TagListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ('__all__')
</code>```

And finally the ComercialSerlialzier:

```<code>class ComercialListSerializer(serializers.ModelSerializer):
    tags = TagListSerializer()
    class Meta:
        model = Comercial
        fields = ('name', 'tags')
</code>```

At listing the Comercial object I expected something like this:

```<code>{
"name": "Example Comercial Name"
"tags": {
         "name":"Example Tag Name"}
}
</code>```

But all i get is:

```<code>{
"name": "Example Comercial Name"
"tags": {
        "name": null
}
</code>```

Thanks in advance!

答:
Well, adding many=True to the serializer solved my problem...dumb me

```<code>class ComercialListSerializer(serializers.ModelSerializer):
    tags = TagListSerializer(many=True)
</code>```

Title: Django- Field appears as Null

Body:
I want to show the name of a field and not the ID of it, so I tried a couple of different methods but with nothing worked for me. I couldn't figure out why or find a suitable solution for this, so here it goes:
Basically, my views returns a null field when in fact it is not null. Code bellow.

tags = TagListSerializer() # Returns null

tags = serializers.Field(source='tags.name') # Returns null

tags = TagListSerializer # Doesn't change anything

Comercial inherits from Project which is abstract:

class Comercial(Project):
    name = models.CharField()

Project is abstract:

class Project(models.Model):
    tags = models.ManyToManyField(Tag, blank=True, editable=True)

The Tag Model:

class Tag(models.Model):
    name = models.CharField(null=False)

The Comercial View which searches by tag:

class ListComercialAPIView(ListAPIView):
    serializer_class = ComercialListSerializer
    pagination_class = StandardResultsSetPagination

    def get_queryset(self):
        tag = self.request.GET.get('tag')
        if(tag!=None):
            return Comercial.objects.filter(tags__name=tag)
        else:
            return Comercial.objects.all()

The Tag Serializer:

class TagListSerializer(serializers.ModelSerializer):
    class Meta:
        model = Tag
        fields = ('__all__')

And finally the ComercialSerlialzier:

class ComercialListSerializer(serializers.ModelSerializer):
    tags = TagListSerializer()
    class Meta:
        model = Comercial
        fields = ('name', 'tags')

At listing the Comercial object I expected something like this:

{
"name": "Example Comercial Name"
"tags": {
         "name":"Example Tag Name"}
}

But all i get is:

{
"name": "Example Comercial Name"
"tags": {
        "name": null
}

Thanks in advance!

Body:
Well, adding many=True to the serializer solved my problem...dumb me

class ComercialListSerializer(serializers.ModelSerializer):
    tags = TagListSerializer(many=True)


问:
Vim and Ctags tips and tricks
I have just installed Ctags (to help with C++ development) with my Vim (or rather gVim), and would like to find out your favorite commands, macros, shortcuts, tips that go along with it...

Share your best arsenal. What other Vim add-ons you would recommend for C++ on Vim development?

EDIT What other add-on you would use in conjunction with Ctags?

EDIT2 What version of gVim you use with tags? Does it make a difference?

EDIT3 How do you enhance your programming experience for both big and small projects?

答:
Ctrl+] - go to definition

Ctrl+T - Jump back from the definition.

Ctrl+W Ctrl+] - Open the definition in a horizontal split

Add these lines in vimrc

    map <C-\> :tab split<CR>:exec("tag ".expand("<cword>"))<CR>

    map  :vsp <CR>:exec("tag ".expand("<cword>"))<CR>

Ctrl+\ - Open the definition in a new tab

Alt+] - Open the definition in a vertical split

After the tags are generated. You can use the following keys to tag into and tag out of functions:

Ctrl+Left MouseClick - Go to definition

Ctrl+Right MouseClick - Jump back from definition

OwnerDisplayName: Sasha

LastEditorDisplayName: Sasha

ContentLicense: CC BY-SA 2.5

Title: Vim and Ctags tips and tricks

Body:
Ctrl+] - go to definition

Ctrl+T - Jump back from the definition.

Ctrl+W Ctrl+] - Open the definition in a horizontal split

Add these lines in vimrc

    map <C-\> :tab split<CR>:exec("tag ".expand("<cword>"))<CR>

    map <A-]> :vsp <CR>:exec("tag ".expand("<cword>"))<CR>

Ctrl+\ - Open the definition in a new tab

Alt+] - Open the definition in a vertical split

After the tags are generated. You can use the following keys to tag into and tag out of functions:

Ctrl+Left MouseClick - Go to definition

Ctrl+Right MouseClick - Jump back from definition

ContentLicense: CC BY-SA 3.0


问:
Simple Java name based locks?
MySQL has a handy function:

```<code>SELECT GET_LOCK("SomeName")
</code>```

This can be used to create simple, but very specific, name-based locks for an application. However, it requires a database connection.

I have many situations like:

```<code>someMethod() {
    // do stuff to user A for their data for feature X
}
</code>```

It doesn't make sense to simply synchronize this method, because, for example, if this method is called for user B in the meantime, user B does not need to wait for user A to finish before it starts, only operations for the user A and feature X combination need to wait.

With the MySql lock I could do something like:

```<code>someMethod() {
    executeQuery("SELECT GET_LOCK('userA-featureX')")
    // only locked for user A for their data for feature X
    executeQuery("SELECT RELEASE_LOCK('userA-featureX')")
}
</code>```

Since Java locking is based on objects, it seems like I would need to create a new object to represent the situation for this lock and then put it in a static cache somewhere so all the threads can see it. Subsequent requests to lock for that situation would then locate the lock object in the cache and acquire its lock. I tried to create something like this, but then the lock cache itself needs synchronization. Also, it is difficult to detect when a lock object is no longer being used so that it can be removed from the cache.

I have looked at the Java concurrent packages, but nothing stands out as being able to handle something like this. Is there an easy way to implement this, or am I looking at this from the wrong perspective?

Edit:

To clarify, I am not looking to create a predefined pool of locks ahead of time, I would like to create them on demand. Some pseudo-code for what I am thinking of is:

```<code>LockManager.acquireLock(String name) {
    Lock lock;

    synchronized (map) {
        lock = map.get(name);

        // doesn't exist yet - create and store
        if(lock == null) {
            lock = new Lock();
            map.put(name, lock);
        }
    }

    lock.lock();
}

LockManager.releaseLock(String name) {
    // unlock
    // if this was the last hold on the lock, remove it from the cache
}
</code>```

答:
Can you have a Map<String, java.util.concurrent.Lock>? Each time you require a lock, you basically call map.get(lockName).lock().

Here's an example using Google Guava:

```<code>Map<String, Lock> lockMap = new MapMaker().makeComputingMap(new Function<String, Lock>() {
  @Override public Lock apply(String input) {
    return new ReentrantLock();
  }
});
</code>```

Then lockMap.get("anyOldString") will cause a new lock to be created if required and returned to you. You can then call lock() on that lock. makeComputingMap returns a Map that is thread-safe, so you can just share that with all your threads.

Title: Simple Java name based locks?

Body:
MySQL has a handy function:

SELECT GET_LOCK("SomeName")

This can be used to create simple, but very specific, name-based locks for an application. However, it requires a database connection.

I have many situations like:

someMethod() {
    // do stuff to user A for their data for feature X
}

It doesn't make sense to simply synchronize this method, because, for example, if this method is called for user B in the meantime, user B does not need to wait for user A to finish before it starts, only operations for the user A and feature X combination need to wait.

With the MySql lock I could do something like:

someMethod() {
    executeQuery("SELECT GET_LOCK('userA-featureX')")
    // only locked for user A for their data for feature X
    executeQuery("SELECT RELEASE_LOCK('userA-featureX')")
}

Since Java locking is based on objects, it seems like I would need to create a new object to represent the situation for this lock and then put it in a static cache somewhere so all the threads can see it. Subsequent requests to lock for that situation would then locate the lock object in the cache and acquire its lock. I tried to create something like this, but then the lock cache itself needs synchronization. Also, it is difficult to detect when a lock object is no longer being used so that it can be removed from the cache.

I have looked at the Java concurrent packages, but nothing stands out as being able to handle something like this. Is there an easy way to implement this, or am I looking at this from the wrong perspective?

Edit:

To clarify, I am not looking to create a predefined pool of locks ahead of time, I would like to create them on demand. Some pseudo-code for what I am thinking of is:

LockManager.acquireLock(String name) {
    Lock lock;

    synchronized (map) {
        lock = map.get(name);

        // doesn't exist yet - create and store
        if(lock == null) {
            lock = new Lock();
            map.put(name, lock);
        }
    }

    lock.lock();
}

LockManager.releaseLock(String name) {
    // unlock
    // if this was the last hold on the lock, remove it from the cache
}

Body:
Can you have a Map<String, java.util.concurrent.Lock>? Each time you require a lock, you basically call map.get(lockName).lock().

Here's an example using Google Guava:

Map<String, Lock> lockMap = new MapMaker().makeComputingMap(new Function<String, Lock>() {
  @Override public Lock apply(String input) {
    return new ReentrantLock();
  }
});

Then lockMap.get("anyOldString") will cause a new lock to be created if required and returned to you. You can then call lock() on that lock. makeComputingMap returns a Map that is thread-safe, so you can just share that with all your threads.


问:
Using regex to find substring inside another substring
Using regex, how would one check for ANY portion of a string (substring) within another string(substring)?
For example:

```<code>str1 = "li_xxxyyy"
str2 = "123xxxyyy"
</code>```

I need a true response for the xxxyyy variable portion of the string.

I'm looking for any portion of str1 found in any portion of str2

答:
I'm guessing that here we would just want to use a capturing group around our desired output and that'd likely solve our problem, with a simple expression such as:

const regex = /(xxxyyy)/gm;
const str = `li_xxxyyy
123xxxyyy
123xxxyyy123xxxyyy
123xxxyyy123`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}```

Demo

Body:
Using regex, how would one check for ANY portion of a string (substring) within another string(substring)?
For example:

str1 = "li_xxxyyy"
str2 = "123xxxyyy"

I need a true response for the xxxyyy variable portion of the string.

I'm looking for any portion of str1 found in any portion of str2

Body:
I'm guessing that here we would just want to use a capturing group around our desired output and that'd likely solve our problem, with a simple expression such as:

const regex = /(xxxyyy)/gm;
const str = `li_xxxyyy
123xxxyyy
123xxxyyy123xxxyyy
123xxxyyy123`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }

    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}

Demo


问:
404 error when query string contains com1 for WebApi hosted on IIS 10
I have a simple WebApi solution hosted on IIS10.

I have a ProductController class that inherits ApiController. This class has a method GetProduct

```<code> [HttpGet]
    [Route("api/product/{productName}")]
    public object GetProduct(string productName)
    {
        return "abc";
    }
</code>```

When I try to hit the following api through postman

http://localhost:10000/api/product/com1?query=test

I get a 404 error, Tried to create a folder by the same name (com1) but got an error as well. Then found out that I cannot have the following values in my api
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9.

I tried adding the following entries in IIS
under Request Filtering

Am I missing out on anything?

答:
make sure productNamed and productName matches, I ran into an error recently as well because the names didn't match.. crazy haha i was using Swagger and it gave me two fields to fill out when i only needed one.. </p>

```<code> [HttpGet]
 [Route("api/product/{productName}")]
 public object GetProduct(string productName)
 {
     return "abc";
 }
</code>```

Body:
I have a simple WebApi solution hosted on IIS10.

I have a ProductController class that inherits ApiController. This class has a method GetProduct

 [HttpGet]
    [Route("api/product/{productName}")]
    public object GetProduct(string productName)
    {
        return "abc";
    }

When I try to hit the following api through postman

http://localhost:10000/api/product/com1?query=test

I get a 404 error, Tried to create a folder by the same name (com1) but got an error as well. Then found out that I cannot have the following values in my api
CON, PRN, AUX, NUL, COM1, COM2, COM3, COM4, COM5, COM6, COM7, COM8, COM9, LPT1, LPT2, LPT3, LPT4, LPT5, LPT6, LPT7, LPT8, and LPT9.

I tried adding the following entries in IIS
under Request Filtering

Am I missing out on anything?

Body:
make sure productNamed and productName matches, I ran into an error recently as well because the names didn't match.. crazy haha i was using Swagger and it gave me two fields to fill out when i only needed one..

 [HttpGet]
 [Route("api/product/{productName}")]
 public object GetProduct(string productName)
 {
     return "abc";
 }


问:
Pandas - group by one column, sort by another, get value from the third column
I would like to take pandas dataframe, group it by one column, sort it by another column and take first element from third column and populate original dataframe.

Here is my original df. I would to group by col_1, sort by col_2 (ascending) and take first element from col_3 and populate col_4 with results.

```<code>df_in = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f']})
</code>```

[

Here is how output df should look like:

```<code>df_out = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f'], 'col_4': ['k','k','k','f','f','f'], })
</code>```

I can accomplish grouping and sorting with group and transform, but how to extract first element is not clear.

Sorry SO does not display images correctly ;-(

答:
Try some thing diff idxmin

```<code>s=df_in.groupby(['col_1']).col_2.transform('idxmin')
df_in['New']=df_in.col_3.reindex(s).values
df_in
Out[469]:
  col_1  col_2 col_3 New
0     A      5     c   k
1     A      9     d   k
2     A      2     k   k
3     B      3     n   f
4     B      7     l   f
5     B      1     f   f
</code>```

Body:
I would like to take pandas dataframe, group it by one column, sort it by another column and take first element from third column and populate original dataframe.

Here is my original df. I would to group by col_1, sort by col_2 (ascending) and take first element from col_3 and populate col_4 with results.

df_in = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f']})

[

Here is how output df should look like:

df_out = pd.DataFrame({'col_1':['A', 'A', 'A', 'B', 'B', 'B'], 'col_2': [5,9,2, 3,7,1],
                   'col_3': ['c','d','k','n','l','f'], 'col_4': ['k','k','k','f','f','f'], })

I can accomplish grouping and sorting with group and transform, but how to extract first element is not clear.

Sorry SO does not display images correctly ;-(

Body:
Try some thing diff idxmin

s=df_in.groupby(['col_1']).col_2.transform('idxmin')
df_in['New']=df_in.col_3.reindex(s).values
df_in
Out[469]:
  col_1  col_2 col_3 New
0     A      5     c   k
1     A      9     d   k
2     A      2     k   k
3     B      3     n   f
4     B      7     l   f
5     B      1     f   f


问:
Replacing all tables with a text
I would like to replace all tables in a document with the following text:

"Table 1" (to replace the first table)
"Table 2" (to replace the second table)
...

Could someone please help me?

Thanks in advance!

答:
I am providing here a solution that I have developed by own:</p>

```<code>Sub MyMacro()

Dim i As Integer

For i = 1 To ActiveDocument.Tables.Count
    ActiveDocument.Tables(1).Select
    ActiveDocument.Tables(1).Delete
    Selection.TypeText Text:="Table" & i
    Selection.InsertParagraphAfter
Next i

End Sub
</code>```

Title: Replacing all tables with a text

Body:
I am providing here a solution that I have developed by own:

Sub MyMacro()

Dim i As Integer

For i = 1 To ActiveDocument.Tables.Count
    ActiveDocument.Tables(1).Select
    ActiveDocument.Tables(1).Delete
    Selection.TypeText Text:="Table" & i
    Selection.InsertParagraphAfter
Next i

End Sub


问:
Why is Javascript's Splice function not working?

My question is quick. Here is the problem:

```<code>//Gets string from database in "User1|User2|User3" format
var frArray = res[0].friendRequests.split('|');

//frArray should now equal ['User1', 'User2', etc]

//data.friend is a string for the friend we are removing from requests
//let's assume it's User1

console.log(frArray.indexOf(data.friend)); //This prints 0

console.log(frArray); //This prints User1 which is correct

frArray = frArray.splice(frArray.indexOf(data.friend), 1);

console.log(frArray);
//This prints User1 STILL which is not correct it should've removed it
</code>```

I would appreciate any help, I can't figure it out. I've been stuck on this for a while. Thanks

答:
splice returns an array of the elements you removed. Just remove the assignment so your variable continues to refer to the original array, which is modified in place:

```<code>frArray.splice(frArray.indexOf(data.friend), 1);
</code>```

Example:

const frArray = ["Jane", "Mohammed", "An"];
const removed = frArray.splice(0, 1);
console.log(`removed: ${JSON.stringify(removed)}`);
console.log(`frArray: ${JSON.stringify(frArray)}`);```

Body:
My question is quick. Here is the problem:

//Gets string from database in "User1|User2|User3" format
var frArray = res[0].friendRequests.split('|');

//frArray should now equal ['User1', 'User2', etc]

//data.friend is a string for the friend we are removing from requests
//let's assume it's User1

console.log(frArray.indexOf(data.friend)); //This prints 0

console.log(frArray); //This prints User1 which is correct

frArray = frArray.splice(frArray.indexOf(data.friend), 1);

console.log(frArray);
//This prints User1 STILL which is not correct it should've removed it

I would appreciate any help, I can't figure it out. I've been stuck on this for a while. Thanks

Body:
splice returns an array of the elements you removed. Just remove the assignment so your variable continues to refer to the original array, which is modified in place:

frArray.splice(frArray.indexOf(data.friend), 1);

Example:

const frArray = ["Jane", "Mohammed", "An"];
const removed = frArray.splice(0, 1);
console.log(`removed: ${JSON.stringify(removed)}`);
console.log(`frArray: ${JSON.stringify(frArray)}`);


问:
Why was the warning to add content description to image views and image button removed in AppCompat
When building layouts in android, if you use an ImageView or an ImageButton without adding a content description, then you would get a warning telling you to add a content description to the views with AppCompatImageView and AppCompatImageButton that warning is no longer available. I thought this is because the implementation for AppCompatImageView  has a default content description based on the content of the view but talk back still reads it as an "un labelled button", why was the warning removed?

答:
This lint rule is designed to work on specific widget types. Currently, this rule is checking only ImageView and ImageButton widgets. The lack of warning for AppCompat widgets is because they have never added them to the element list.

The source code of the current implementation shows that it is applied only to ImageView and ImageButton.

public Collection<String> getApplicableElements() {
    return Arrays.asList(
            IMAGE_BUTTON,
            IMAGE_VIEW
    );
}
```

I have filled a bug on the Android issue tracker to request them to add AppCompatImageView and AppCompatImageButton to this lint rule. You may star the issue to convey your support.

Body:
This lint rule is designed to work on specific widget types. Currently, this rule is checking only ImageView and ImageButton widgets. The lack of warning for AppCompat widgets is because they have never added them to the element list.

The source code of the current implementation shows that it is applied only to ImageView and ImageButton.

public Collection<String> getApplicableElements() {
    return Arrays.asList(
            IMAGE_BUTTON,
            IMAGE_VIEW
    );
}

I have filled a bug on the Android issue tracker to request them to add AppCompatImageView and AppCompatImageButton to this lint rule. You may star the issue to convey your support.


问:
Aggregate hourly count based on "HOUR" in datetime field in Django
I am using Django 2.2 along with MySQL. I have the following query:
Here's the model for the reference :

```<code>class TrackCount(models.Model):
    people_count_obj_id = models.CharField(primary_key=True, default=uuid.uuid4,
                                           editable=False, max_length=255)
    recorded_at = models.DateTimeField()
    camera = models.ForeignKey(Camera, on_delete=models.PROTECT)
    store = models.ForeignKey(Store, on_delete=models.PROTECT)
    people_count_in = models.IntegerField()
    people_count_out = models.IntegerField()
    created_at = models.DateTimeField(auto_now=True)
    is_unique = models.BooleanField(default=False)

    def __str__(self):
        return "{}.{}.{}".format(self.people_count_in,
                                 self.people_count_out, str(self.store))

    class Meta:
        verbose_name = 'Track Count'
        verbose_name_plural = 'Track Counts'
</code>```

========================================================
My Query goes like this.

```<code>track_events = TrackCount.objects.filter(
            recorded_at__date=start_date.date(),
            recorded_at__hour__range=(8, 23),
            store__store_owner__id=self.kwargs['account_id']).order_by(
            'recorded_at'
        ).extra(
            select={
                'hour': 'hour(recorded_at)'
            }
        ).values(
            'hour'
        ).annotate(
            TotalPeople=Sum('people_count_in')
        )
</code>```

But when I check my records I get the output as following :

```<code>[
    {
        "hour": 17,
        "TotalPeople": 22
    },
    {
        "hour": 17,
        "TotalPeople": 19
    },
    {
        "hour": 17,
        "TotalPeople": 30
    },
    {
        "hour": 18,
        "TotalPeople": 33
    },
    {
        "hour": 18,
        "TotalPeople": 31
    },
    {
        "hour": 18,
        "TotalPeople": 32
    },
    {
        "hour": 19,
        "TotalPeople": 32
    },
    {
        "hour": 19,
        "TotalPeople": 21
}]
</code>```

But I would like the output something like this :

[{ "hour": 18, "TotalPeople": 96}....] that is the record for same hour should be SUM-ed up together.

Hope my point is clear. TIA

答:
Okay, so practically it took me couple of hour to decode this. Since I wanted a SUM-med up answer for same value of hour the final query was something like this.

```<code>track_events = TrackCount.objects.filter(
            recorded_at__date=start_date.date(),
            recorded_at__hour__range=(8, 23),
            store__store_owner__id=self.kwargs['account_id']).order_by(
            'recorded_at'
        ).extra(
            select={
                'hour': 'hour(recorded_at)'
            }
        ).values(
            'hour'
        ).annotate(
            TotalPeople=Sum('people_count_in')
        ).order_by('hour')
</code>```

Body:
I am using Django 2.2 along with MySQL. I have the following query:
Here's the model for the reference :

class TrackCount(models.Model):
    people_count_obj_id = models.CharField(primary_key=True, default=uuid.uuid4,
                                           editable=False, max_length=255)
    recorded_at = models.DateTimeField()
    camera = models.ForeignKey(Camera, on_delete=models.PROTECT)
    store = models.ForeignKey(Store, on_delete=models.PROTECT)
    people_count_in = models.IntegerField()
    people_count_out = models.IntegerField()
    created_at = models.DateTimeField(auto_now=True)
    is_unique = models.BooleanField(default=False)

    def __str__(self):
        return "{}.{}.{}".format(self.people_count_in,
                                 self.people_count_out, str(self.store))

    class Meta:
        verbose_name = 'Track Count'
        verbose_name_plural = 'Track Counts'

========================================================
My Query goes like this.

track_events = TrackCount.objects.filter(
            recorded_at__date=start_date.date(),
            recorded_at__hour__range=(8, 23),
            store__store_owner__id=self.kwargs['account_id']).order_by(
            'recorded_at'
        ).extra(
            select={
                'hour': 'hour(recorded_at)'
            }
        ).values(
            'hour'
        ).annotate(
            TotalPeople=Sum('people_count_in')
        )

But when I check my records I get the output as following :

[
    {
        "hour": 17,
        "TotalPeople": 22
    },
    {
        "hour": 17,
        "TotalPeople": 19
    },
    {
        "hour": 17,
        "TotalPeople": 30
    },
    {
        "hour": 18,
        "TotalPeople": 33
    },
    {
        "hour": 18,
        "TotalPeople": 31
    },
    {
        "hour": 18,
        "TotalPeople": 32
    },
    {
        "hour": 19,
        "TotalPeople": 32
    },
    {
        "hour": 19,
        "TotalPeople": 21
}]

But I would like the output something like this :

[{ "hour": 18, "TotalPeople": 96}....] that is the record for same hour should be SUM-ed up together.

Hope my point is clear. TIA

Body:
Okay, so practically it took me couple of hour to decode this. Since I wanted a SUM-med up answer for same value of hour the final query was something like this.

track_events = TrackCount.objects.filter(
            recorded_at__date=start_date.date(),
            recorded_at__hour__range=(8, 23),
            store__store_owner__id=self.kwargs['account_id']).order_by(
            'recorded_at'
        ).extra(
            select={
                'hour': 'hour(recorded_at)'
            }
        ).values(
            'hour'
        ).annotate(
            TotalPeople=Sum('people_count_in')
        ).order_by('hour')


问:
Enumerating all walks in a graph
Given a term representation of an edge of a graph, i.e.:

```<code>edge(a, b).
edge(b, c).
</code>```

I would like to construct a predicate path/1 which succeeds iff its sole argument is a valid path in this graph (that is, for every two adjacent terms X, Y, edge(X, Y) holds). Given a variable, it should enumerate all walks (which could have repeated nodes). My first try:

```<code>path([X, Y]) :- edge(X, Y).
path([X, Y, Z | T]) :-
  path([Y, Z | T]),
  edge(X, Y).
</code>```

It works as intended except for the case where it is supplied an acyclic graph - path finds all solutions and then halts, unable to construct any other path. On the other hand, swapping first and second term will result in many walks being skipped, due to the DFS nature of Prolog resolution.

My second attempt:

```<code>path(P) :- length(P, L), L >= 2, (path(P, L) *-> true ; (!, fail)).

path([X, Y], 2) :- edge(X, Y).
path([X, Y, Z | T], L) :-
  L >= 3,
  L1 is L - 1,
  edge(X, Y),
  path([Y, Z | T], L1).
</code>```

It works as intended, but using a soft cut feels a bit forced. I was wondering if there was an easier way to accomplish this, perhaps a simpler simulation of a soft cut is possible in this particular scenario?

答: Testing your first solution, after finding three paths ([a,b],[a,c],[a,b,c]), it loops. One super quick way to avoid this is to use tabling wich is available in XSB, SWI and YAP. In case of SWI just add :- table path/1. as first directive to avoid loops. Otherwise you need to remember all path and there are plenty of answers you can look at (like this).

Title: Enumerating all walks in a graph

Body:
Given a term representation of an edge of a graph, i.e.:

edge(a, b).
edge(b, c).

I would like to construct a predicate path/1 which succeeds iff its sole argument is a valid path in this graph (that is, for every two adjacent terms X, Y, edge(X, Y) holds). Given a variable, it should enumerate all walks (which could have repeated nodes). My first try:

path([X, Y]) :- edge(X, Y).
path([X, Y, Z | T]) :-
  path([Y, Z | T]),
  edge(X, Y).

It works as intended except for the case where it is supplied an acyclic graph - path finds all solutions and then halts, unable to construct any other path. On the other hand, swapping first and second term will result in many walks being skipped, due to the DFS nature of Prolog resolution.

My second attempt:

path(P) :- length(P, L), L >= 2, (path(P, L) *-> true ; (!, fail)).

path([X, Y], 2) :- edge(X, Y).
path([X, Y, Z | T], L) :-
  L >= 3,
  L1 is L - 1,
  edge(X, Y),
  path([Y, Z | T], L1).

It works as intended, but using a soft cut feels a bit forced. I was wondering if there was an easier way to accomplish this, perhaps a simpler simulation of a soft cut is possible in this particular scenario?


问:
Can i format txt files from within python
now pleased don't get me wrong on this, but im just curious whether I can get a text file and then find out how many lines within that text file have been written on, and thus use that number to print selective data from every few lines. Also could I use python to find specific words within the text file that are evenly apart for example within the text file if everything was written like this

name:> Ben

Score:> 2

name:> Ethan

Score:> 8

name:> James

Score:> 0

would it be possible for me to search the text file, for the string 'name:>' (and then save whatever comes infront of it, if possible to a variable) or seeing as they're all equally spaced could I save the specific score of one person to a variable with their name (as everything in front would be equally spaced), without having to open the txt file at all.

If all of this sounds completely impossible or if any of you have received any vague ideas as to what im talking about (in which case im in awe of your abilities of comprehension from this badly worded example), please give me any thoughts or ideas on how to format text files to create variables.

if all the above seems too complex could someone please just tell me wether its possible to analyse how many lines within a text file have been written on, from there ive got a vague idea on how to create my program.

答:
To do what you are asking, I would personally use the built-in re module, as follows:

```<code>import re
with open("foo.txt", "r") as foo:
    contents = foo.read()

results = re.search("foo-bar", contents).group()
print(results)
</code>```

That should do what you are looking for.

Body:
To do what you are asking, I would personally use the built-in re module, as follows:

import re
with open("foo.txt", "r") as foo:
    contents = foo.read()

results = re.search("foo-bar", contents).group()
print(results)

That should do what you are looking for.


问:
what's the difference for preparing time series data than regular data for machine learning
I am not sure how to ask or search for this, any key words or concepts are appreciated. If the difference of nature of these two data forms can be elaborated would be great. </p>

答:
Usually, you would consider either normalizing or standardizing your data. Normalization is to rescale your data between 0-1, while standardizing your data is to reshape it into normal distribution. While the latter one is more robust for new data, it requires the prior knowledge that your data follows normal distribution which is not true in many cases. Normalization requires you know the min and max of your data, but generally more applicable to most cases.

For time series data, the above two methods still apply, but you would want to first make sure you are dealing with stationary data. Otherwise the "scale" your model learned from the training set may not apply well for inference.

There are another two methods for time series data: power transformation and difference transformation.

Power transform is used to remove a changing variance. Log transform, Box-Cox transform and Yeo-Johnson transform are some variants.

Difference transform is used to remove trend or seasonality.


问:
Programmatically running commands on remote Linux server using R
I was able to use the shell()command on R to write out the instructions to gaining access to the AWS EC2 Linux server.

```<code>shell("chmod 400 rstudio.pem")

shell("ssh -i \"rstudio.pem\" ec2-user@[address number here].us-east-2.compute.amazonaws.com")
</code>```

But once I gained access to the Linux server from R. And I tried running

```<code>shell("sudo yum -y update")
</code>```

It would not run and just stayed in thinking mode for a while and then I recieved an error saying "The Child Process is not running. Click ok to terminate it".

How do I run commands on the Linux server once I gain access from R running on my computer?

答:
The issue you're running into is that each call to shell is being executed in its own process.  So the ssh command that is opened in the first process isn't what is receiving the commands being issued in the subsequent shell calls.

Assuming the underlying shell is bash, you can demonstrate this using:

```<code># echo PID of shell
system('echo $$') # 20859
system('echo $$') # 20860
</code>```

If you're intent on using R as your entry point into invoking ssh, you can pass commands to execute remotely as part of your call to ssh.  This uses ssh to connect and run the command all in a single call.

E.g. get disk usage from remote host

```<code>command <- 'ssh -i "rstudio.pem" ec2-user@[address number here].us-east-2.compute.amazonaws.com df -H'
system(command)
</code>```

I expect your command will look like the following:

```<code>command <- 'ssh -i "rstudio.pem" ec2-user@[address number here].us-east-2.compute.amazonaws.com sudo yum -y update'
system(command)
</code>```

If you wanted to run a series of commands, you could try listed them as the inputs.  This will in turn pass them to ssh via stdin.  That has a little bit of a peculiar behavior, but might suffice for your purposes.

```<code>inputs <- c('echo "Starting Command"', 'df -h', 'echo "All done."')
command <- 'ssh -i "rstudio.pem" ec2-user@your.aws.ec2.address'
system(command, input=inputs)
</code>```

Body:
I was able to use the shell()command on R to write out the instructions to gaining access to the AWS EC2 Linux server.

shell("chmod 400 rstudio.pem")

shell("ssh -i \"rstudio.pem\" ec2-user@[address number here].us-east-2.compute.amazonaws.com")

But once I gained access to the Linux server from R. And I tried running

shell("sudo yum -y update")

It would not run and just stayed in thinking mode for a while and then I recieved an error saying "The Child Process is not running. Click ok to terminate it".

How do I run commands on the Linux server once I gain access from R running on my computer?

Body:
The issue you're running into is that each call to shell is being executed in its own process.  So the ssh command that is opened in the first process isn't what is receiving the commands being issued in the subsequent shell calls.

Assuming the underlying shell is bash, you can demonstrate this using:

# echo PID of shell
system('echo $$') # 20859
system('echo $$') # 20860

If you're intent on using R as your entry point into invoking ssh, you can pass commands to execute remotely as part of your call to ssh.  This uses ssh to connect and run the command all in a single call.

E.g. get disk usage from remote host

command <- 'ssh -i "rstudio.pem" ec2-user@[address number here].us-east-2.compute.amazonaws.com df -H'
system(command)

I expect your command will look like the following:

command <- 'ssh -i "rstudio.pem" ec2-user@[address number here].us-east-2.compute.amazonaws.com sudo yum -y update'
system(command)

If you wanted to run a series of commands, you could try listed them as the inputs.  This will in turn pass them to ssh via stdin.  That has a little bit of a peculiar behavior, but might suffice for your purposes.

inputs <- c('echo "Starting Command"', 'df -h', 'echo "All done."')
command <- 'ssh -i "rstudio.pem" ec2-user@your.aws.ec2.address'
system(command, input=inputs)


问:
Redraw widget with Delay in Flutter
I want to remove a content from a Widget based on a conditional logic.

Below is my Widget tree,

```<code>return MaterialApp(
    home: Scaffold(
    body: Container(
    margin: EdgeInsets.all(120.0),
    child: Align(
      alignment: Alignment.center,
      child: Column(
        children: <Widget>[
          Text("Loading...");
        ],
      ),
    ),
  ),
));
</code>```

Lets say I have a variable which fetches value from SharePreferences and if the value is "Hide" then Text widget encapsulated inside must be hidden. Otherwise it should display the text fetched from the SP.

The catch here is that the Text will initially display "Loading..." for a specific duration and then after that it must behave dynamically based on the condition.

I have tried with Timer and setState() but couldn't really make it work. Kindly assist if anyone has a solution for this.

答:
I have figured out the solution finally which combines @olexa.le's Future.Delayed method along with a few modifications.

```<code> main() {
    runApp(MyPrimaryWidgetBuilder());

    Future.delayed(const Duration(seconds: 5), () async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String appRunStatus = sharedPreferences.getString("appStartStatus");

    if( appRunStatus == null || appRunStatus == "" ){
        //Redraw new Widget
    }
}
</code>```

Now my initial Widget will be drawn to the viewport and then the main() method will wait for 5 seconds due to the delay set in the Future. Then the conditional block will check the value returned by sharedPreferences.getString()

If the value is NULL then my goal is to draw a new widget replacing the existing one. Inside the conditional module, I just invoke the runApp() method again with a new widget.

```<code>if( appRunStatus == null || appRunStatus == "" ){
      runApp(
         new MaterialApp(
             home: Scaffold(
                 body: Container(
                    child: Text("You Are running the app for the first time..."),
                 ),
             ),
      );
}
</code>```

Assume that, initially the layout displayed will hold the text "Loading..." and this will stay as such for 5 seconds. After 5 seconds based on the value returned by
SharePreferences, the whole app's view will be redrawn with a new widget.

I have redrawn around 6 new widgets and also included a few animations based to suit my use case. The Text widget is just a sample and you can replace it with whatever you want and this will work. It will be suitable for redrawing widgets with new children without navigating to a new page.

This worked for me and if there is a better solution to achieve the same with more efficiency, then please do share that.

Title: Redraw widget with Delay in Flutter

Body:
I want to remove a content from a Widget based on a conditional logic.

Below is my Widget tree,

return MaterialApp(
    home: Scaffold(
    body: Container(
    margin: EdgeInsets.all(120.0),
    child: Align(
      alignment: Alignment.center,
      child: Column(
        children: <Widget>[
          Text("Loading...");
        ],
      ),
    ),
  ),
));

Lets say I have a variable which fetches value from SharePreferences and if the value is "Hide" then Text widget encapsulated inside must be hidden. Otherwise it should display the text fetched from the SP.

The catch here is that the Text will initially display "Loading..." for a specific duration and then after that it must behave dynamically based on the condition.

I have tried with Timer and setState() but couldn't really make it work. Kindly assist if anyone has a solution for this.

Body:
I have figured out the solution finally which combines @olexa.le's Future.Delayed method along with a few modifications.

 main() {
    runApp(MyPrimaryWidgetBuilder());

    Future.delayed(const Duration(seconds: 5), () async {
    SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
    String appRunStatus = sharedPreferences.getString("appStartStatus");

    if( appRunStatus == null || appRunStatus == "" ){
        //Redraw new Widget
    }
}

Now my initial Widget will be drawn to the viewport and then the main() method will wait for 5 seconds due to the delay set in the Future. Then the conditional block will check the value returned by sharedPreferences.getString()

If the value is NULL then my goal is to draw a new widget replacing the existing one. Inside the conditional module, I just invoke the runApp() method again with a new widget.

if( appRunStatus == null || appRunStatus == "" ){
      runApp(
         new MaterialApp(
             home: Scaffold(
                 body: Container(
                    child: Text("You Are running the app for the first time..."),
                 ),
             ),
      );
}

Assume that, initially the layout displayed will hold the text "Loading..." and this will stay as such for 5 seconds. After 5 seconds based on the value returned by
SharePreferences, the whole app's view will be redrawn with a new widget.

I have redrawn around 6 new widgets and also included a few animations based to suit my use case. The Text widget is just a sample and you can replace it with whatever you want and this will work. It will be suitable for redrawing widgets with new children without navigating to a new page.

This worked for me and if there is a better solution to achieve the same with more efficiency, then please do share that.


问:
Reduce array by adding elements
I came across this question in a test.

Given an array, reduce the array to a single element with minimum cost. For reducing, remove two elements from the array, add those two numbers and keep the sum back in the array. The cost of each operation is the sum of the elements removed in that step.

Example, let the array A = [1,2,3]

Then, we can remove 1 and 2, add both of them and keep the sum back in array. Cost of this step would be (1+2) = 3.

So A = [3,3], Cost = 3

In second step, we can remove both elements from the array and keep the sum back in array again. Cost of this step would be 3 + 3 = 6.

So, A = [6], Cost = 6

So total cost turns out to be 9 (6+3).

I tried sorting the array, and adding the elements from decreasing to increasing, but it fails if there are duplicate elements.

Pseudo code of my algorithm

```<code>sort(Array)
cost = 0
for(i=0; i<Array.length - 1; i++) {
   Array[i+1] = Array[i] + Array[i+1]
   cost = cost + Array[i+1]
}
</code>```

The algorithm mentioned above was not working. I came up with a possible case where it may fail.
If the Array = [5, 5, 5, 5], then Cost = 45, according to the above algorithm.

However if we sum the first two elements and last two elements, and then sum the remaining two elements, then the total cost turns out to be 40. (In first step, cost = 10*2, and in next step another 20)

What could be a efficient algorithm for this?

答:
Here's my solution in java: </p>

```<code>int cost = 0;
for (int i=1; i<Array.length; i++) {
    Array[i] += Array[i-1];
    cost += Array[i];
}
return cost;
</code>```

Title: Reduce array by adding elements

Body:
I came across this question in a test.

Given an array, reduce the array to a single element with minimum cost. For reducing, remove two elements from the array, add those two numbers and keep the sum back in the array. The cost of each operation is the sum of the elements removed in that step.

Example, let the array A = [1,2,3]

Then, we can remove 1 and 2, add both of them and keep the sum back in array. Cost of this step would be (1+2) = 3.

So A = [3,3], Cost = 3

In second step, we can remove both elements from the array and keep the sum back in array again. Cost of this step would be 3 + 3 = 6.

So, A = [6], Cost = 6

So total cost turns out to be 9 (6+3).

I tried sorting the array, and adding the elements from decreasing to increasing, but it fails if there are duplicate elements.

Pseudo code of my algorithm

sort(Array)
cost = 0
for(i=0; i<Array.length - 1; i++) {
   Array[i+1] = Array[i] + Array[i+1]
   cost = cost + Array[i+1]
}

The algorithm mentioned above was not working. I came up with a possible case where it may fail.
If the Array = [5, 5, 5, 5], then Cost = 45, according to the above algorithm.

However if we sum the first two elements and last two elements, and then sum the remaining two elements, then the total cost turns out to be 40. (In first step, cost = 10*2, and in next step another 20)

What could be a efficient algorithm for this?

Body:
Here's my solution in java:

int cost = 0;
for (int i=1; i<Array.length; i++) {
    Array[i] += Array[i-1];
    cost += Array[i];
}
return cost;


问:
Locating a single value in a dynamically created array
I'm trying to create a dynamic array.  The reason I need to use a dynamic array is because I don't know how many variables will need to be in the array at the start.

After the array exists, I want to parse through the ranges in the array, and at times isolate only a single cell value for one of the ranges.  Unfortunately, i'm getting an Object Required error.

I've checked already on this site and others, and I can't find an explanation.  Perhaps people are calling the actions something differently.

```<code>Sub get_val()

'get the number of rows
Dim id As Worksheet
Set id = ThisWorkbook.Sheets("ID Sheet")
rc = id.Range("B:B").Find(What:="*", After:=id.Range("B1"), LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row

'Find which ones have "yes" in column Q and create an array
Dim memcache As Variant
Dim x As Integer
x = 1
ReDim memcache(x)
For i = 3 To rc
    If id.Cells(i, 17).Value = "Yes" Then
        ReDim Preserve memcache(x)
        memcache(x) = id.Range("A" & i & ":M" & i)
        x = x + 1
    End If
Next i
</code>```

' Here's where i'm running into issues.
'If I want to copy one of the ranges to a another range on the sheet, that works fine

```<code>id.Range("A50:M50").Value = memcache(2) 'this works
</code>```

'However, if i want to just locate one cell's value in the range it won't 'work.  This produces an "Object Required" error.

```<code>Debug.Print memcache(2).Cells(1, 2).Value
</code>```

'For comparison, creating a single range will work

```<code>Dim cellrange As Variant

Set cellrange = id.Range("A9:M19")

Debug.Print cellrange.Cells(1, 2).Value ' this will work

End Sub
</code>```

I would like to be able to get the value of cells (1,2) in each range saved in the array, and if they match a certain condition, I will then be updating another range on the sheet with the full range in that saved array.

答:
Arrays and ranges are different things in VBA. An array is simply an array of values, whereas a range is a reference to a group of cells on a worksheet. In this case, Memcache is an array, but you're trying to treat it like a range. Memcache does not have any cells, it just has values.

What you want is to replace Debug.Print memcache(2).Cells(1, 2).Value with Debug.Print memcache(2).

The difference is more clear if you explicitly set your variable types, for example:

```<code>Dim memcache() As String '(or integer, or whatever type of data you're putting into it)
Dim cellrange As Range
</code>```

Body:
I'm trying to create a dynamic array.  The reason I need to use a dynamic array is because I don't know how many variables will need to be in the array at the start.

After the array exists, I want to parse through the ranges in the array, and at times isolate only a single cell value for one of the ranges.  Unfortunately, i'm getting an Object Required error.

I've checked already on this site and others, and I can't find an explanation.  Perhaps people are calling the actions something differently.

Sub get_val()

'get the number of rows
Dim id As Worksheet
Set id = ThisWorkbook.Sheets("ID Sheet")
rc = id.Range("B:B").Find(What:="*", After:=id.Range("B1"), LookIn:=xlValues, SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row

'Find which ones have "yes" in column Q and create an array
Dim memcache As Variant
Dim x As Integer
x = 1
ReDim memcache(x)
For i = 3 To rc
    If id.Cells(i, 17).Value = "Yes" Then
        ReDim Preserve memcache(x)
        memcache(x) = id.Range("A" & i & ":M" & i)
        x = x + 1
    End If
Next i

' Here's where i'm running into issues.
'If I want to copy one of the ranges to a another range on the sheet, that works fine

id.Range("A50:M50").Value = memcache(2) 'this works

'However, if i want to just locate one cell's value in the range it won't 'work.  This produces an "Object Required" error.

Debug.Print memcache(2).Cells(1, 2).Value

'For comparison, creating a single range will work

Dim cellrange As Variant

Set cellrange = id.Range("A9:M19")

Debug.Print cellrange.Cells(1, 2).Value ' this will work

End Sub

I would like to be able to get the value of cells (1,2) in each range saved in the array, and if they match a certain condition, I will then be updating another range on the sheet with the full range in that saved array.

Body:
Arrays and ranges are different things in VBA. An array is simply an array of values, whereas a range is a reference to a group of cells on a worksheet. In this case, Memcache is an array, but you're trying to treat it like a range. Memcache does not have any cells, it just has values.

What you want is to replace Debug.Print memcache(2).Cells(1, 2).Value with Debug.Print memcache(2).

The difference is more clear if you explicitly set your variable types, for example:

Dim memcache() As String '(or integer, or whatever type of data you're putting into it)
Dim cellrange As Range


问:
Read a large file, line by line, while also writing to a different large file, in Python
I am trying to read a large file line by line while also writing to a large file and I want to know the "best" way of doing so.

I found this Stack Overflow post for reading a large file line by line and want to know the proper way to also incorporate writing to a file. Is there anything better than nesting a 2nd with open

What I currently have:

```<code> #args is parsed from the command line
 #file is an exogenous variable
 with open(args.inPath + file, "r") as fpIn:
   with open(args.outPath + file, "w") as fpOut:
     for line in fpIn:
       if re.match(some match): canWrite = True
       if re.match(some match 2): break
       if canWrite: fpOut.write(line)
</code>```

答:
You need not nest the with statements. A single with statement can use multiple context managers.

```<code>with open(args.inPath + file, "r") as fpIn, open(args.outPath + file, "w") as fpOut:
    for line in fpIn:
       if re.match(some match): canWrite = True
       if re.match(some match 2): break
       if canWrite: fpOut.write(line)
</code>```

It's a bit cleaner.

Body:
I am trying to read a large file line by line while also writing to a large file and I want to know the "best" way of doing so.

I found this Stack Overflow post for reading a large file line by line and want to know the proper way to also incorporate writing to a file. Is there anything better than nesting a 2nd with open

What I currently have:

 #args is parsed from the command line
 #file is an exogenous variable
 with open(args.inPath + file, "r") as fpIn:
   with open(args.outPath + file, "w") as fpOut:
     for line in fpIn:
       if re.match(some match): canWrite = True
       if re.match(some match 2): break
       if canWrite: fpOut.write(line)

Body:
You need not nest the with statements. A single with statement can use multiple context managers.

with open(args.inPath + file, "r") as fpIn, open(args.outPath + file, "w") as fpOut:
    for line in fpIn:
       if re.match(some match): canWrite = True
       if re.match(some match 2): break
       if canWrite: fpOut.write(line)

It's a bit cleaner.


问:
java.lang.ClassCastException: android.support.v7.widget.SearchView cannot be cast to android.view.MenuItem
I am developing news app and I have implemented search view in navigation drawer in main activity but I am getting the following exception

java.lang.ClassCastException: android.support.v7.widget.SearchView cannot be cast to android.view.MenuItem
        at edgar.yodgorbek.sportnews.MainActivity.onCreateOptionsMenu(MainActivity.java:104)

below my MainActivity.java where I have implemented searchview

```<code>public class MainActivity extends AppCompatActivity {
    private DrawerLayout mDrawer;
    private Toolbar toolbar;
    private NavigationView nvDrawer;
    private ActionBarDrawerToggle drawerToggle;
    Context mContext;

    // Default active navigation menu
    int mActiveMenu;

    // TAGS
    public static final int MENU_FIRST = 0;
    public static final int MENU_SECOND = 1;
    public static final int MENU_THIRD = 2;
    public static final int MENU_FOURTH = 3;
    public static final int MENU_FIFTH = 3;

    // Action bar search widget
    SearchView searchView;
    String searchQuery = "";

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

        // Set a Toolbar to replace the ActionBar.
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Find our drawer view
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerToggle = setupDrawerToggle();

        // Tie DrawerLayout events to the ActionBarToggle
        mDrawer.addDrawerListener(drawerToggle);

        nvDrawer = (NavigationView) findViewById(R.id.nvView);

// Inflate the header view at runtime
        View headerLayout = nvDrawer.inflateHeaderView(R.layout.nav_header);
// We can now look up items within the header if needed
        ImageView ivHeaderPhoto = (ImageView) headerLayout.findViewById((R.id.header_image));
        ivHeaderPhoto.setImageResource(R.drawable.ic_sportnews);
        setupDrawerContent(nvDrawer);
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, new BBCSportFragment()).commit();
        fragmentManager.beginTransaction().replace(R.id.flContent, new FoxSportsFragment()).commit();
        fragmentManager.beginTransaction().replace(R.id.flContent, new TalkSportsFragment()).commit();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawer.openDrawer(GravityCompat.START);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);

        // Getting search action from action bar and setting up search view
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();

        // Setup searchView
        setupSearchView((MenuItem) searchView);

        return true;
    }

    private void setupSearchView(MenuItem searchItem) {
        SearchManager searchManager = (SearchManager) this.getSystemService(Context.SEARCH_SERVICE);
        if (searchManager != null) {
            SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
            searchView.setSearchableInfo(info);
        }

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextChange(String newText) {
                searchQuery = newText;

                // Load search data on respective fragment
                if (mActiveMenu == MENU_FIRST)   // First
                {
                    BBCSportFragment.doFilter(newText);
                }

                if (mActiveMenu == MENU_SECOND)   // First
                {
                    BBCSportFragment.doFilter(newText);
                }

                if (mActiveMenu == MENU_THIRD)   // First
                {
                    BBCSportFragment.doFilter(newText);
                }

                if (mActiveMenu == MENU_FOURTH)   // First
                {
                    BBCSportFragment.doFilter(newText);
                } else if (mActiveMenu == MENU_FIFTH) // Second
                {
                    ESPNFragment.doFilter(newText);
                }
                return true;
            }

            @Override
            public boolean onQueryTextSubmit(String query) {
                //searchView.clearFocus();
                return false;
            }
        });

        // Handling focus change of search view
        searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                // Focus changed after pressing back key or pressing done in keyboard
                if (!hasFocus) {
                    searchQuery = "";
                }
            }
        });
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                menuItem -> {
                    selectDrawerItem(menuItem);
                    return true;
                });
    }

    public void selectDrawerItem(MenuItem menuItem) {
        // Create a new fragment and specify the fragment to show based on nav item clicked
        Fragment fragment = null;
        Class fragmentClass = null;
        switch (menuItem.getItemId()) {
            case R.id.bbcsports_fragment:
                fragmentClass = BBCSportFragment.class;
                break;
            case R.id.talksports_fragment:
                fragmentClass = TalkSportsFragment.class;
                break;
            case R.id.foxsports_fragment:
                fragmentClass = FoxSportsFragment.class;
                break;

            case R.id.footballitalia_fragment:
                fragmentClass = FootballItaliaFragment.class;
                break;

            case R.id.espn_fragment:
                fragmentClass = ESPNFragment.class;
                break;

            default:

        }

        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Insert the fragment by replacing any existing fragment

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
        // Highlight the selected item has been done by NavigationView
        menuItem.setChecked(true);
        // Set action bar title
        setTitle(menuItem.getTitle());
        // Close the navigation drawer
        mDrawer.closeDrawers();
    }

    private ActionBarDrawerToggle setupDrawerToggle() {
        // NOTE: Make sure you pass in a valid toolbar reference.  ActionBarDrawToggle() does not require it
        // and will not render the hamburger icon without it.
        return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        drawerToggle.onConfigurationChanged(newConfig);
    }

}
</code>```

below main.xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search_white"
        android:title="@string/search_hint"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>
</code>```

答: A SearchView isn't a MenuItem and can't be cast into one.  Its a View.  Your setupSearchView function needs to take a SearchView instead of a MenuItem, and be adjusted accordingly.</p>

Body:
I am developing news app and I have implemented search view in navigation drawer in main activity but I am getting the following exception

java.lang.ClassCastException: android.support.v7.widget.SearchView cannot be cast to android.view.MenuItem
        at edgar.yodgorbek.sportnews.MainActivity.onCreateOptionsMenu(MainActivity.java:104)

below my MainActivity.java where I have implemented searchview

public class MainActivity extends AppCompatActivity {
    private DrawerLayout mDrawer;
    private Toolbar toolbar;
    private NavigationView nvDrawer;
    private ActionBarDrawerToggle drawerToggle;
    Context mContext;

    // Default active navigation menu
    int mActiveMenu;

    // TAGS
    public static final int MENU_FIRST = 0;
    public static final int MENU_SECOND = 1;
    public static final int MENU_THIRD = 2;
    public static final int MENU_FOURTH = 3;
    public static final int MENU_FIFTH = 3;

    // Action bar search widget
    SearchView searchView;
    String searchQuery = "";

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

        // Set a Toolbar to replace the ActionBar.
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        // Find our drawer view
        mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerToggle = setupDrawerToggle();

        // Tie DrawerLayout events to the ActionBarToggle
        mDrawer.addDrawerListener(drawerToggle);

        nvDrawer = (NavigationView) findViewById(R.id.nvView);

// Inflate the header view at runtime
        View headerLayout = nvDrawer.inflateHeaderView(R.layout.nav_header);
// We can now look up items within the header if needed
        ImageView ivHeaderPhoto = (ImageView) headerLayout.findViewById((R.id.header_image));
        ivHeaderPhoto.setImageResource(R.drawable.ic_sportnews);
        setupDrawerContent(nvDrawer);
        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, new BBCSportFragment()).commit();
        fragmentManager.beginTransaction().replace(R.id.flContent, new FoxSportsFragment()).commit();
        fragmentManager.beginTransaction().replace(R.id.flContent, new TalkSportsFragment()).commit();

    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // The action bar home/up action should open or close the drawer.
        switch (item.getItemId()) {
            case android.R.id.home:
                mDrawer.openDrawer(GravityCompat.START);
                return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);

        // Getting search action from action bar and setting up search view
        MenuItem searchItem = menu.findItem(R.id.action_search);
        SearchView searchView = (SearchView) searchItem.getActionView();

        // Setup searchView
        setupSearchView((MenuItem) searchView);

        return true;
    }

    private void setupSearchView(MenuItem searchItem) {
        SearchManager searchManager = (SearchManager) this.getSystemService(Context.SEARCH_SERVICE);
        if (searchManager != null) {
            SearchableInfo info = searchManager.getSearchableInfo(getComponentName());
            searchView.setSearchableInfo(info);
        }

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextChange(String newText) {
                searchQuery = newText;

                // Load search data on respective fragment
                if (mActiveMenu == MENU_FIRST)   // First
                {
                    BBCSportFragment.doFilter(newText);
                }

                if (mActiveMenu == MENU_SECOND)   // First
                {
                    BBCSportFragment.doFilter(newText);
                }

                if (mActiveMenu == MENU_THIRD)   // First
                {
                    BBCSportFragment.doFilter(newText);
                }

                if (mActiveMenu == MENU_FOURTH)   // First
                {
                    BBCSportFragment.doFilter(newText);
                } else if (mActiveMenu == MENU_FIFTH) // Second
                {
                    ESPNFragment.doFilter(newText);
                }
                return true;
            }

            @Override
            public boolean onQueryTextSubmit(String query) {
                //searchView.clearFocus();
                return false;
            }
        });

        // Handling focus change of search view
        searchView.setOnQueryTextFocusChangeListener(new View.OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                // Focus changed after pressing back key or pressing done in keyboard
                if (!hasFocus) {
                    searchQuery = "";
                }
            }
        });
    }

    private void setupDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                menuItem -> {
                    selectDrawerItem(menuItem);
                    return true;
                });
    }

    public void selectDrawerItem(MenuItem menuItem) {
        // Create a new fragment and specify the fragment to show based on nav item clicked
        Fragment fragment = null;
        Class fragmentClass = null;
        switch (menuItem.getItemId()) {
            case R.id.bbcsports_fragment:
                fragmentClass = BBCSportFragment.class;
                break;
            case R.id.talksports_fragment:
                fragmentClass = TalkSportsFragment.class;
                break;
            case R.id.foxsports_fragment:
                fragmentClass = FoxSportsFragment.class;
                break;

            case R.id.footballitalia_fragment:
                fragmentClass = FootballItaliaFragment.class;
                break;

            case R.id.espn_fragment:
                fragmentClass = ESPNFragment.class;
                break;

            default:

        }

        try {
            fragment = (Fragment) fragmentClass.newInstance();
        } catch (Exception e) {
            e.printStackTrace();
        }

        // Insert the fragment by replacing any existing fragment

        FragmentManager fragmentManager = getSupportFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.flContent, fragment).commit();
        // Highlight the selected item has been done by NavigationView
        menuItem.setChecked(true);
        // Set action bar title
        setTitle(menuItem.getTitle());
        // Close the navigation drawer
        mDrawer.closeDrawers();
    }

    private ActionBarDrawerToggle setupDrawerToggle() {
        // NOTE: Make sure you pass in a valid toolbar reference.  ActionBarDrawToggle() does not require it
        // and will not render the hamburger icon without it.
        return new ActionBarDrawerToggle(this, mDrawer, toolbar, R.string.drawer_open, R.string.drawer_close);
    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        drawerToggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Pass any configuration change to the drawer toggles
        drawerToggle.onConfigurationChanged(newConfig);
    }

}

below main.xml file

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/action_search"
        android:icon="@drawable/ic_search_white"
        android:title="@string/search_hint"
        app:showAsAction="collapseActionView|ifRoom"
        app:actionViewClass="android.support.v7.widget.SearchView" />
</menu>


问:
Getting the results of a promise in a multidimensional array
I have a multidimensional array of promises that I'm trying to resolve. If I console.log the result I can view the arrays and within each one is the promise along with a [[PromiseStatus]] and a [[PromiseValue]]. How do I get the promise value?

Here's a snippet of code:

(resourcePromises is just a multidimensional array of promises).

```<code>    Promise.all(resourcePromises).then(function(values)
    {
        console.log(values);
    });
</code>```

And then the variable values will hold multiple arrays, and within each of those arrays is a list of promises that I'm trying to grab the values from.

答:
Use this snippet for subarrays:</p>

```<code>const balancePromises = [...];
const symbolPromises = [...];

const [balances, symbols] = await Promise.all([
    Promise.all(balancePromises),
    Promise.all(symbolPromises)
]);
</code>```

Body:
I have a multidimensional array of promises that I'm trying to resolve. If I console.log the result I can view the arrays and within each one is the promise along with a [[PromiseStatus]] and a [[PromiseValue]]. How do I get the promise value?

Here's a snippet of code:

(resourcePromises is just a multidimensional array of promises).

    Promise.all(resourcePromises).then(function(values)
    {
        console.log(values);
    });

And then the variable values will hold multiple arrays, and within each of those arrays is a list of promises that I'm trying to grab the values from.

Body:
Use this snippet for subarrays:

const balancePromises = [...];
const symbolPromises = [...];

const [balances, symbols] = await Promise.all([
    Promise.all(balancePromises),
    Promise.all(symbolPromises)
]);


问:
How to calculate coefficients of polynomial using Lagrange interpolation
I need to calculate coefficients of polynomial using Lagrange interpolation polynomial, as my homework, I decide to do this in Javascript.

here is definition of Lagrange polynomial (L(x))

Lagrange basis polynomials are defined as follows

Calculate y value for specific X (W(x) function) is simple but I need to calculate coefficients of polynomial (array of [a0, a1, ..., an]) I need to do this to n<=10 but it will be nice to have arbitrary n, then I can put that function into horner function and draw that polynomial.

I have function that calculate denominator in first equation

```<code>function denominator(i, points) {
   var result = 1;
   var x_i = points[i].x;
   for (var j=points.length; j--;) {
      if (i != j) {
        result *= x_i - points[j].x;
      }
   }
   return result;
}
</code>```

and function that return y using horner method (I also have drawing function using canvas)

```<code>function horner(array, x_scale, y_scale) {
   function recur(x, i, array) {
      if (i == 0) {
         return x*array[0];
      } else {
         return array[i] + x*recur(x, --i, array);
      }
   }
   return function(x) {
      return recur(x*x_scale, array.length-1, array)*y_scale;
   };
}
</code>```

anybody know algorithm to do this, or idea how to calculate those coefficients

答:
You can find coefficients of Lagrange interpolation polynomial relatively easy if you use a matrix form of Lagrange interpolation presented in "Beginner's guide to mapping simplexes affinely
", section "Lagrange interpolation". I'm afraid, I don't know JavaScript to provide you with appropriate code, but I worked with Python a little bit, maybe the following can help (sorry for bad codestyle -- I'm mathematician, not programmer)

import numpy as np
# input
x = [0, 2, 4, 5]  # <- x's
y = [2, 5, 7, 7]  # <- y's
# calculating coefficients
M = [[_x**i*(-1)**(i*len(x)) for _x in x] for i in range(len(x))]
C = [np.linalg.det((M+[y]+M)[d:d+len(x)]) for d in range(len(x)+1)]
C = (C / C[0] * (-1)**(len(x)+1) )[1:]
# polynomial lambda-function
poly = lambda _x: sum([C[i] * _x**i for i in range(len(x))])
# output and tests
print("Coefficients:\n", C)
print("TESTING:")
for _x, _y in zip(x, y):
    result = "[OK]" if np.allclose(_y, poly(_x)) else "[ERROR]"
    print(_x, " mapped to: ", poly(_x), " ; expected: ", _y, result)
```

This code calculates coefficients of the Lagrange interpolation polynomial, prints them, and tests that given x's are mapped into expected y's. You can test this code with Google colab, so you don't have to install anything. Probably, you can translate it to JS.

Body:
I need to calculate coefficients of polynomial using Lagrange interpolation polynomial, as my homework, I decide to do this in Javascript.

here is definition of Lagrange polynomial (L(x))

Lagrange basis polynomials are defined as follows

Calculate y value for specific X (W(x) function) is simple but I need to calculate coefficients of polynomial (array of [a0, a1, ..., an]) I need to do this to n<=10 but it will be nice to have arbitrary n, then I can put that function into horner function and draw that polynomial.

I have function that calculate denominator in first equation

function denominator(i, points) {
   var result = 1;
   var x_i = points[i].x;
   for (var j=points.length; j--;) {
      if (i != j) {
        result *= x_i - points[j].x;
      }
   }
   return result;
}

and function that return y using horner method (I also have drawing function using canvas)

function horner(array, x_scale, y_scale) {
   function recur(x, i, array) {
      if (i == 0) {
         return x*array[0];
      } else {
         return array[i] + x*recur(x, --i, array);
      }
   }
   return function(x) {
      return recur(x*x_scale, array.length-1, array)*y_scale;
   };
}

anybody know algorithm to do this, or idea how to calculate those coefficients

Body:
You can find coefficients of Lagrange interpolation polynomial relatively easy if you use a matrix form of Lagrange interpolation presented in "Beginner's guide to mapping simplexes affinely
", section "Lagrange interpolation". I'm afraid, I don't know JavaScript to provide you with appropriate code, but I worked with Python a little bit, maybe the following can help (sorry for bad codestyle -- I'm mathematician, not programmer)

import numpy as np
# input
x = [0, 2, 4, 5]  # <- x's
y = [2, 5, 7, 7]  # <- y's
# calculating coefficients
M = [[_x**i*(-1)**(i*len(x)) for _x in x] for i in range(len(x))]
C = [np.linalg.det((M+[y]+M)[d:d+len(x)]) for d in range(len(x)+1)]
C = (C / C[0] * (-1)**(len(x)+1) )[1:]
# polynomial lambda-function
poly = lambda _x: sum([C[i] * _x**i for i in range(len(x))])
# output and tests
print("Coefficients:\n", C)
print("TESTING:")
for _x, _y in zip(x, y):
    result = "[OK]" if np.allclose(_y, poly(_x)) else "[ERROR]"
    print(_x, " mapped to: ", poly(_x), " ; expected: ", _y, result)

This code calculates coefficients of the Lagrange interpolation polynomial, prints them, and tests that given x's are mapped into expected y's. You can test this code with Google colab, so you don't have to install anything. Probably, you can translate it to JS.


问:
RVM, FSEvents, and CarbonCore on OS X
I'm setting up a project that uses SASS, which uses FSEvents to keep from polling the disk. It seems that this doesn't play nice with RVM, however. That means that when I run sass --watch I get this warning:

Warning: Unable to load CarbonCore. FSEvents will be unavailable.

I realize that it will still work, but I don't want to be polling my disk constantly. I want to get it working with FSEvents. The best information I could find about this was this thread:

http://groups.google.com/group/compass-users/browse_thread/thread/df7d9d0da9ec1eb1

I reinstalled my RVM Ruby (using 1.9.2) as described by Brandon Mathis and downloaded the linked RubyCocoa. However, I get an error on the first step of installing RubyCocoa:

```<code>[rvm 1.9.2] ~/Downloads/RubyCocoa-1.0.0 $ ruby install.rb config --build-universal=yes
install.rb: entering config phase...
create ext/rubycocoa/extconf.rb
create framework/GeneratedConfig.xcconfig
create framework/src/objc/Version.h
create tests/Makefile
---> framework
create /Users/xxx/Downloads/RubyCocoa-1.0.0/framework/src/objc/osx_ruby.h ...
config failed
hook /Users/xxx/Downloads/RubyCocoa-1.0.0/framework/post-config.rb failed:
No such file or directory - /Users/xxx/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/x86_64-darwin10.6.0/ruby.h
try 'ruby install.rb --help' for usage
</code>```

It looks like the problem stems from this being an older version of RubyCocoa (I notice the missing file has 1.9.1 in the path), but in the Google Groups post, Brandon Mathis says specifically to use the version he links and not the newest one.

Does anyone know how to get this configured, or have a link to a recent, hopefully simpler and clearer guide to getting FSEvents working with RVM?

Versions in question:

RVM 1.2.0

Ruby 1.9.2 patch level 136 (installed via RVM)

Mac OS X 10.6.6

HAML gem 3.0.25 (SASS is part of HAML)

Thanks!

答:
I tried the FSSM method above, to no avail...

Gemfile now has:

```<code>group :development do
  gem 'rb-fsevent'
  gem 'fssm', :git => 'https://github.com/ttilley/fssm.git'
end
</code>```

which installs:
  fssm (0.2.6.1)
  rb-fsevent (0.4.0)

Still getting this tho:
  Warning: Unable to load CarbonCore. FSEvents will be unavailable.

Anyone have install steps to make FSSM work nicely?

Title: RVM, FSEvents, and CarbonCore on OS X

Body:
I'm setting up a project that uses SASS, which uses FSEvents to keep from polling the disk. It seems that this doesn't play nice with RVM, however. That means that when I run sass --watch I get this warning:

Warning: Unable to load CarbonCore. FSEvents will be unavailable.

I realize that it will still work, but I don't want to be polling my disk constantly. I want to get it working with FSEvents. The best information I could find about this was this thread:

http://groups.google.com/group/compass-users/browse_thread/thread/df7d9d0da9ec1eb1

I reinstalled my RVM Ruby (using 1.9.2) as described by Brandon Mathis and downloaded the linked RubyCocoa. However, I get an error on the first step of installing RubyCocoa:

[rvm 1.9.2] ~/Downloads/RubyCocoa-1.0.0 $ ruby install.rb config --build-universal=yes
install.rb: entering config phase...
create ext/rubycocoa/extconf.rb
create framework/GeneratedConfig.xcconfig
create framework/src/objc/Version.h
create tests/Makefile
---> framework
create /Users/xxx/Downloads/RubyCocoa-1.0.0/framework/src/objc/osx_ruby.h ...
config failed
hook /Users/xxx/Downloads/RubyCocoa-1.0.0/framework/post-config.rb failed:
No such file or directory - /Users/xxx/.rvm/rubies/ruby-1.9.2-p136/lib/ruby/1.9.1/x86_64-darwin10.6.0/ruby.h
try 'ruby install.rb --help' for usage

It looks like the problem stems from this being an older version of RubyCocoa (I notice the missing file has 1.9.1 in the path), but in the Google Groups post, Brandon Mathis says specifically to use the version he links and not the newest one.

Does anyone know how to get this configured, or have a link to a recent, hopefully simpler and clearer guide to getting FSEvents working with RVM?

Versions in question:

RVM 1.2.0

Ruby 1.9.2 patch level 136 (installed via RVM)

Mac OS X 10.6.6

HAML gem 3.0.25 (SASS is part of HAML)

Thanks!

Body:
I tried the FSSM method above, to no avail...

Gemfile now has:

group :development do
  gem 'rb-fsevent'
  gem 'fssm', :git => 'https://github.com/ttilley/fssm.git'
end

which installs:
  fssm (0.2.6.1)
  rb-fsevent (0.4.0)

Still getting this tho:
  Warning: Unable to load CarbonCore. FSEvents will be unavailable.

Anyone have install steps to make FSSM work nicely?


问:
cassandra vs elastic search vs any other design suggestions
We have a need to run analytics queries on the data stored in rds. And that's becoming very very slow because of group by queries and ever increasing size of the tables.
For example we have following 3 tables in RDS :

```<code>alm(id,name,cli, group_id, con_id ...)
group(id, type,timestamp ...)
con(id,ip,port ...)
</code>```

each of the tables have very high amount of data and are being updated several times a minute as the new data comes in.

Now we want to run aggregation queries like :

```<code>select name from alm, group, con where alm.group_id=group.id and alm.con_id=con.id group by name, group.type, con.ip
</code>```

We also want users to run custom aggregation queries in the future as opposed to the fix query provided by us in future.

So far the options we are considering are moving to either Cassandra, Elasticsearch or Dynamo db so that aggregation would be faster. Can someone guide as to how to go about this problem ? Or any crumbs of experience ? Anybody know any technologies have severe advantage over others ?

答:
One more options is Column-oriented databases, this kind of DB is more suitable for 'analytics' cases  when you have many data fields and you want to perform aggregations or extract some subset of fields for big amount of data.

Recently Yandex ClickHouse becomes very popular and there is Column Oriented service from Amazon - Redshift. Also there are several other solutions

Body:
We have a need to run analytics queries on the data stored in rds. And that's becoming very very slow because of group by queries and ever increasing size of the tables.
For example we have following 3 tables in RDS :

alm(id,name,cli, group_id, con_id ...)
group(id, type,timestamp ...)
con(id,ip,port ...)

each of the tables have very high amount of data and are being updated several times a minute as the new data comes in.

Now we want to run aggregation queries like :

select name from alm, group, con where alm.group_id=group.id and alm.con_id=con.id group by name, group.type, con.ip

We also want users to run custom aggregation queries in the future as opposed to the fix query provided by us in future.

So far the options we are considering are moving to either Cassandra, Elasticsearch or Dynamo db so that aggregation would be faster. Can someone guide as to how to go about this problem ? Or any crumbs of experience ? Anybody know any technologies have severe advantage over others ?


问:
How to fix binary operator
Error C2676 binary '[': 'collection::item' does not define this operator or a conversion to a type acceptable to the predefined operator

I read few posts and Microsoft VS site, but cannot understand how to fix the problem

template<typename T1, typename T2>
class collection {
private:
    class item {
    public:
        T1 item; T2 key;
    };
    unsigned int top;
    item array = new item[top];
public:
    collection& operator[](unsigned int i) {
        return array[i];
    }
    collection(int top) {
        this->top = top;
    }
    void coutarr() {
        for (int i = 0; array[i] != 0; i++) {
            cout << array[i].item << endl;
        }
    }
    void extendarray() {
        item x = new item[top*2];
        for (int i = 0; i < top; i++) {
            x[i] = array[i];
        }
        delete []array;
        swap(array, x);
        top = top*2;

    }
    void addvar(int i, T1 item, T2 key) {
        array[i].item = item; array[i].key = key; //Here 2 Errors
    }
};
```

If someone can explain what shall I do, I'd be very grateful. Thanks.

答:
It seems you mean at least something like the following

```<code>template<typename T1, typename T2>
class collection {
private:
    class item {
    public:
        T1 item; T2 key;
    };
    unsigned int top;
    item *array;
    ^^^^^^^^^^^^^
public:
    auto & operator[](unsigned int i) {
    ^^^^
        return array[i];
    }

    collection(unsigned int top) : top( top ), array( new item[top]{} )
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    {
    }

    ~collection() { delete []array; }
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    collection( const collection & ) = delete;
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    collection & operator =( const collection & ) = delete;
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    void coutarr() {
        for (int i = 0; array[i] != 0; i++) {
            cout << array[i].item << endl;
        }
    }
    void extendarray() {
        item x = new item[top*2];
        for (int i = 0; i < top; i++) {
            x[i] = array[i];
        }
        delete []array;
        swap(array, x);
        top = top*2;

    }
    void addvar(int i, const T1 &item, const T2 &key) {
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        array[i].item = item; array[i].key = key; //Here 2 Errors
    }
};
</code>```

Of course you can futher develop the code.

Title: How to fix binary operator

Body:
Error C2676 binary '[': 'collection::item' does not define this operator or a conversion to a type acceptable to the predefined operator

I read few posts and Microsoft VS site, but cannot understand how to fix the problem

template<typename T1, typename T2>
class collection {
private:
    class item {
    public:
        T1 item; T2 key;
    };
    unsigned int top;
    item array = new item[top];
public:
    collection& operator[](unsigned int i) {
        return array[i];
    }
    collection(int top) {
        this->top = top;
    }
    void coutarr() {
        for (int i = 0; array[i] != 0; i++) {
            cout << array[i].item << endl;
        }
    }
    void extendarray() {
        item x = new item[top*2];
        for (int i = 0; i < top; i++) {
            x[i] = array[i];
        }
        delete []array;
        swap(array, x);
        top = top*2;

    }
    void addvar(int i, T1 item, T2 key) {
        array[i].item = item; array[i].key = key; //Here 2 Errors
    }
};

If someone can explain what shall I do, I'd be very grateful. Thanks.

Body:
It seems you mean at least something like the following

template<typename T1, typename T2>
class collection {
private:
    class item {
    public:
        T1 item; T2 key;
    };
    unsigned int top;
    item *array;
    ^^^^^^^^^^^^^
public:
    auto & operator[](unsigned int i) {
    ^^^^
        return array[i];
    }

    collection(unsigned int top) : top( top ), array( new item[top]{} )
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    {
    }

    ~collection() { delete []array; }
   ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    collection( const collection & ) = delete;
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    collection & operator =( const collection & ) = delete;
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

    void coutarr() {
        for (int i = 0; array[i] != 0; i++) {
            cout << array[i].item << endl;
        }
    }
    void extendarray() {
        item x = new item[top*2];
        for (int i = 0; i < top; i++) {
            x[i] = array[i];
        }
        delete []array;
        swap(array, x);
        top = top*2;

    }
    void addvar(int i, const T1 &item, const T2 &key) {
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        array[i].item = item; array[i].key = key; //Here 2 Errors
    }
};

Of course you can futher develop the code.