问:
Traversing an Array Javascript
I'm supposed to use a while loop to traverse this array and multiply each item by 2. The page just keeps loading forever when I try to run it.... What am I missing? Thank you.</p>

```<code>var prices = [4, 5, 8, 10];

var i = 0;
while (i < prices.length){
    prices[i]++;
    i*=2;
}

console.log(prices);
</code>```

答:
As others have pointed out, you have a logic error in the way you are calculating the updated prices. You are multiplying the iterator and not the price.

ES5 solution.

var prices = [4, 5, 8, 10];
var updatedPrices = prices.map(function(item) {
  return item *= 2;
});

console.log(updatedPrices);

/**
 [
  8,
  10,
  16,
  20
]
*/```
</div>
</div>
</p>

<p>ES6 solution.</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="true">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const prices = [4, 5, 8, 10];
const updatedPrices = prices.map(item => item *= 2);

console.log(updatedPrices);

/**
 [
  8,
  10,
  16,
  20
]
*/</code>```

Title: Traversing an Array Javascript

Body:
I'm supposed to use a while loop to traverse this array and multiply each item by 2. The page just keeps loading forever when I try to run it.... What am I missing? Thank you.

var prices = [4, 5, 8, 10];

var i = 0;
while (i < prices.length){
    prices[i]++;
    i*=2;
}

console.log(prices);

Body:
As others have pointed out, you have a logic error in the way you are calculating the updated prices. You are multiplying the iterator and not the price.

ES5 solution.

var prices = [4, 5, 8, 10];
var updatedPrices = prices.map(function(item) {
  return item *= 2;
});

console.log(updatedPrices);

/**
 [
  8,
  10,
  16,
  20
]
*/

ES6 solution.

const prices = [4, 5, 8, 10];
const updatedPrices = prices.map(item => item *= 2);

console.log(updatedPrices);

/**
 [
  8,
  10,
  16,
  20
]
*/


来源: stackexchange

问:
Eclipse CDT: Make a project rebuild when a library built in another project was rebuild
We have several C projects in Eclipse, using CDT (CodeSourcery++).

There are two projects that build libraries for use in the "main" project that builds the final application.

Now we find that rebuilding one of the libraries does not cause the main project to be also rebuild. Obviously, there is no dependency in the makefile to cause this.

The libraries themselves are linked in properly, but the final build result does not depend on them.

How can we create this dependency?

答:
You should use the CDT references page to specify the library configuration referenced by your main project.

```<code>Right click on Project > Properties > C/C++ General > Paths & Symbols > References
</code>```

CDT will then ensure that the library project is built first, and will ensure that the main executable is re-linked when the dependent library changes.

ContentLicense: CC BY-SA 2.5

Body:
You should use the CDT references page to specify the library configuration referenced by your main project.

Right click on Project > Properties > C/C++ General > Paths & Symbols > References

CDT will then ensure that the library project is built first, and will ensure that the main executable is re-linked when the dependent library changes.


问:
How to delete message on channel telegram?
I need telegram bot which can delete message in group channel
i googled it  but did not find a solution
Could you tell the library and the method for this, if you know, thank you in advance?</p>

答:
You may delete messages only with telegram api, not bot api. With telethon (python client for telegram API) you can do it this way: </p>

```<code>client.invoke(DeleteMessagesRequest(chat, [msg.id]))
</code>```

ContentLicense: CC BY-SA 3.0

Body:
You may delete messages only with telegram api, not bot api. With telethon (python client for telegram API) you can do it this way:

client.invoke(DeleteMessagesRequest(chat, [msg.id]))


问:
Beginner questions about Frtos compiler(s)
I want to learn FreeRtos I just started reading some pdf books online. I'm a total beginner in this area and I have a question:

I have googled and found out that "Visual Studio 2010 Express" compiler supports FreeRtos. Does that mean that If I write some C FreeRTOS code in this compiler just like I would do a normal .c program will it work fine? Also please explain what is a "port" when talking about RTOS.

Please help me clear this up as I'm planning to start compiling the examples that I read in my pdf books. Thank you.

答:
While the answer from @Richard indicates the FreeRTOS can be used in a Windows environment, this is not a typical use case.

FreeRTOS is generally used in an embedded microcontroller (i.e., appliances, peripherals, toys, industrial controllers, etc.) where there is no other operating system present. It provides basic functions for managing multiple tasks for time-critical functions.

If you have not yet done any embedded development, I would recommend choosing a microcontroller development board and learning how to develop simple stuff for it first, and then add FreeRTOS into the mix. This can be a steep but rewarding learning curve.

An embedded application is standard C, but it is not a "normal C program" in the sense you would run on your PC. You compile and flash the program to the chip, and it will automatically execute main() upon power up or reset. There is no separate OS, and you typically do not have stdio or any PC-like user interface. Your application is the only thing running and is responsible for literally everything. Libraries like FreeRTOS help with some complex or difficult tasks, or simple but common tasks. (The chip manufacturer will provide libraries for configuring and controlling its basic functions.)

A FreeRTOS "port" is an adaptation of FreeRTOS to a particular microcontroller family, tailoring it to the specific timers, control registers, or other hardware capabilities (or lack thereof) the chip provides. The core FreeRTOS files are unchanged, and you will choose the "port" files based on the chip you are using. Your application will include and link to the necessary FreeRTOS code files just like any other library.

Regarding compilers and other development tools, you will use whatever normal tools for the target chip. Visual Studio Express isn't really intended to be used for embedded development, and I don't believe it supports it out of the box (no cross-compiler). I have used a third-party plugin called VisualGDB, with an STM32 Discovery board to compile and run simple FreeRTOS-based applications - this worked quite well, and was easy to get running.

Ultimately I found this to be an uncommon solution, and hard to find help when I got stuck. I am transitioning to the standard GNU ARM Toolchain (with Visual Studio Code as an editor), and working through the tool learning curve myself.


问:
Incorrrect Merge, Instead of merging A to B I merged B to A in GIT LAB
Instead of merging B (Branch) to A(Feature) I merged A(Feature) to B(Branch) in GIT LAB.
Here is a graphical representation of what I did.
I have this as below. With this the "Branch A2" merges into "feature B2" which is not what i intended.
ISSUE: Now if i continue development, the Branch that will have to continue on is "feature B2" instead of "Branch A2"

```<code>Branch          A ----A1------ A2 <-- last commit
                 \              \  (merge into feature)
Branch(feature)   B -- -B1- - -- B2 <-- feature now contains Branch "A2" edits.
</code>```

This is what I wanted. To merged "feature B2" into "Branch A2"; In this way when I continue my development it would be on the "Branch A2" and not "feature B2"

```<code>Branch(feature) B ----B1------ B2 <-- last feature commit
                 \              \  (merge into Branch)
Branch            A -- -A1- - -- A2 <-- Branch now contains "B2" feature edits.
</code>```

What is the most clean way of fixing this so I can get Scenario 2 and continue working on "A2" Branch branch instead of "B2" feature branch?
Function wise, they both achieve the same thing whether you merged A2->B2 or B2->A2!

One way comes to mind is that I can rename the Merged branch and call it Branch A2

答:
Assuming your changes were not pushed upstream, I think a

```<code>git checkout feature
git reset B1 --hard
git checkout branch
git merge feature
</code>```

should do, where B1 is the commit before the merge.

One way comes to mind is that I can rename the Merged branch and call it Branch A2

When you're "done" with feature anyway, that might even be the cleaner solution in your case.

```<code>git branch -d branch branch-tmp # Delete branch
git branch -m feature branch # Rename feature into branch
</code>```

Body:
Instead of merging B (Branch) to A(Feature) I merged A(Feature) to B(Branch) in GIT LAB.
Here is a graphical representation of what I did.
I have this as below. With this the "Branch A2" merges into "feature B2" which is not what i intended.
ISSUE: Now if i continue development, the Branch that will have to continue on is "feature B2" instead of "Branch A2"

Branch          A ----A1------ A2 <-- last commit
                 \              \  (merge into feature)
Branch(feature)   B -- -B1- - -- B2 <-- feature now contains Branch "A2" edits.

This is what I wanted. To merged "feature B2" into "Branch A2"; In this way when I continue my development it would be on the "Branch A2" and not "feature B2"

Branch(feature) B ----B1------ B2 <-- last feature commit
                 \              \  (merge into Branch)
Branch            A -- -A1- - -- A2 <-- Branch now contains "B2" feature edits.

What is the most clean way of fixing this so I can get Scenario 2 and continue working on "A2" Branch branch instead of "B2" feature branch?
Function wise, they both achieve the same thing whether you merged A2->B2 or B2->A2!

One way comes to mind is that I can rename the Merged branch and call it Branch A2

Body:
Assuming your changes were not pushed upstream, I think a

git checkout feature
git reset B1 --hard
git checkout branch
git merge feature

should do, where B1 is the commit before the merge.

One way comes to mind is that I can rename the Merged branch and call it Branch A2

When you're "done" with feature anyway, that might even be the cleaner solution in your case.

git branch -d branch branch-tmp # Delete branch
git branch -m feature branch # Rename feature into branch


问:
TypeError: 'float' object has no attribute '__getitem__' in function
I am trying to pass a dataframe to a function and compute mean and std dev from different columns of the dataframe. When I execute each line of the function step by step (without writing a function as such) it works fine. However, when I try to write a function to compute, I keep getting this error:

```<code>TypeError: 'float' object has no attribute '__getitem__'
</code>```

This is my code:

```<code>def computeBias(data):

    meandata = np.array(data['mean'])
    sddata = np.array(data.sd)
    ni = np.array(data.numSamples)

    mean = np.average(meandata, weights=ni)
    pooled_sd = np.sqrt((np.sum(np.multiply((ni - 1), np.array(sddata)**2)))/(np.sum(ni) - 1))

    return mean, pooled_sd

mean,sd = df.apply(computeBias)
</code>```

This is sample data:

```<code>id           type             mean           sd              numSamples
------------------------------------------------------------------------
1             33              -0.43          0.40               101
2             23              -0.76          0.1                100
3             33               0.89          0.56               101
4             45               1.4           0.9                100
</code>```

This is the full error traceback:

```<code>---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-134-f4dc392140dd> in <module>()
----> 1 mean,sd = df.apply(computeBias)

C:\Users\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\series.pyc in apply(self, func, convert_dtype, args, **kwds)
   2353             else:
   2354                 values = self.asobject
-> 2355                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   2356
   2357         if len(mapped) and isinstance(mapped[0], Series):

pandas\_libs\src\inference.pyx in pandas._libs.lib.map_infer (pandas\_libs\lib.c:66440)()

<ipython-input-133-2af38e3e29f0> in computeBias(data)
      1 def computeBias(data):
      2
----> 3     meandata = np.array(data['mean'])
      4     sddata = np.array(data.sd)
      5     ni = np.array(data.numSamples)

TypeError: 'float' object has no attribute '__getitem__'
</code>```

Does anyone know of any workaround? TIA!

答:
```<code>meandata = np.array(data['mean'])
TypeError: 'float' object has no attribute '__getitem__'
</code>```

__getitem__ is the method that Python tries to call when you use indexing.  In the marked line that means data['mean'] is producing the error.  Evidently data is a number, a float object.  You can't index a number.

data['mean'] looks like you are either trying to get an item from a dictionary, or from a dataframe, using a named index.  I won't dig into the rest of your code to determine what you intend.

What you need to do it understand what data really it, and what produces it.

You are using this in a df.apply(....), and apparently think that it just means

```<code>computeBias(df)   # or
computeBias(df.data)
</code>```

Rather I suspect the apply is iterating, in some dimension, over the dataframe, and passing values or dataseries to your code.  It isn't passing the whole dataframe.

Body:
I am trying to pass a dataframe to a function and compute mean and std dev from different columns of the dataframe. When I execute each line of the function step by step (without writing a function as such) it works fine. However, when I try to write a function to compute, I keep getting this error:

TypeError: 'float' object has no attribute '__getitem__'

This is my code:

def computeBias(data):

    meandata = np.array(data['mean'])
    sddata = np.array(data.sd)
    ni = np.array(data.numSamples)

    mean = np.average(meandata, weights=ni)
    pooled_sd = np.sqrt((np.sum(np.multiply((ni - 1), np.array(sddata)**2)))/(np.sum(ni) - 1))

    return mean, pooled_sd

mean,sd = df.apply(computeBias)

This is sample data:

id           type             mean           sd              numSamples
------------------------------------------------------------------------
1             33              -0.43          0.40               101
2             23              -0.76          0.1                100
3             33               0.89          0.56               101
4             45               1.4           0.9                100

This is the full error traceback:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-134-f4dc392140dd> in <module>()
----> 1 mean,sd = df.apply(computeBias)

C:\Users\AppData\Local\Continuum\Anaconda2\lib\site-packages\pandas\core\series.pyc in apply(self, func, convert_dtype, args, **kwds)
   2353             else:
   2354                 values = self.asobject
-> 2355                 mapped = lib.map_infer(values, f, convert=convert_dtype)
   2356
   2357         if len(mapped) and isinstance(mapped[0], Series):

pandas\_libs\src\inference.pyx in pandas._libs.lib.map_infer (pandas\_libs\lib.c:66440)()

<ipython-input-133-2af38e3e29f0> in computeBias(data)
      1 def computeBias(data):
      2
----> 3     meandata = np.array(data['mean'])
      4     sddata = np.array(data.sd)
      5     ni = np.array(data.numSamples)

TypeError: 'float' object has no attribute '__getitem__'

Does anyone know of any workaround? TIA!

Body:
meandata = np.array(data['mean'])
TypeError: 'float' object has no attribute '__getitem__'

__getitem__ is the method that Python tries to call when you use indexing.  In the marked line that means data['mean'] is producing the error.  Evidently data is a number, a float object.  You can't index a number.

data['mean'] looks like you are either trying to get an item from a dictionary, or from a dataframe, using a named index.  I won't dig into the rest of your code to determine what you intend.

What you need to do it understand what data really it, and what produces it.

You are using this in a df.apply(....), and apparently think that it just means

computeBias(df)   # or
computeBias(df.data)

Rather I suspect the apply is iterating, in some dimension, over the dataframe, and passing values or dataseries to your code.  It isn't passing the whole dataframe.


问:
replaceing innerHTML of div with some html code
I have  a  div with id xyz.Now i have avariable which has some html code like follows

```<code>var mycode = "<br>jajaj<b>jjja</b> ";
</code>```

Now i want to replace content of div with this html code by using following

```<code>document.getElementbyid("xyz").innerHTML = mycode
</code>```

This doenot work.I am not getting why.mycode is dynamicallly created in my code.

if i do simple document.getElementById("xyz").innerHTML ="some text"  this works

答:
Have you type your code in this manner?

```<code><html>
<body>
<div id="xyz"></div>
<script>
var mycode = "<br>jajaj<b>jjja</b> ";
document.getElementById("xyz").innerHTML = mycode;
</script>
</body>
</html>
</code>```

This one worked for me. Please post your sample code so that we can see it.

Body:
I have  a  div with id xyz.Now i have avariable which has some html code like follows

var mycode = "
jajajjjja ";

Now i want to replace content of div with this html code by using following

document.getElementbyid("xyz").innerHTML = mycode

This doenot work.I am not getting why.mycode is dynamicallly created in my code.

if i do simple document.getElementById("xyz").innerHTML ="some text"  this works

Body:
Have you type your code in this manner?

<html>
<body>
<div id="xyz"></div>
<script>
var mycode = "<br>jajaj<b>jjja</b> ";
document.getElementById("xyz").innerHTML = mycode;
</script>
</body>
</html>

This one worked for me. Please post your sample code so that we can see it.


问:
img tag displays wrong orientation
I have an image at this link: http://d38daqc8ucuvuv.cloudfront.net/avatars/216/2014-02-19%2017.13.48.jpg

As you can see, this is a normal image with correct orientation. However, when I set this link to src attribute of my image tag, the image becomes upside down. http://jsfiddle.net/7j5xJ/

```

Do you have any idea what is going on?

答: An easy way to the fix the problem, sans coding, is to use Photoshop's Save for Web export function. In the dialog box one can chose to remove all or most of an image's EXIF data. I usually just keep copyright and contact info. Also, since images coming directly from a digital camera are greatly oversized for web display it is a good idea to downsize them via Save for the Web anyway. For those that are not Photoshop savvy, I have no doubt that there are online resources for resizing an image and stripping it of any unnecessary EXIF data.</p>

ContentLicense: CC BY-SA 4.0

Title: img tag displays wrong orientation

Body:
I have an image at this link: http://d38daqc8ucuvuv.cloudfront.net/avatars/216/2014-02-19%2017.13.48.jpg

As you can see, this is a normal image with correct orientation. However, when I set this link to src attribute of my image tag, the image becomes upside down. http://jsfiddle.net/7j5xJ/

Do you have any idea what is going on?


问:
How to access dynamic segment in a controller in Ember.js?
I have an example route:

```<code>this.route('client', {path: ':id'});
</code>```

I can access this in my route like this:

```<code>model: function(params) {
    console.log(params.id);
}
</code>```

How do I access the :id in my controller?

答:
If your id happens to be part of your model you can retrieve from the model itself.
For example, if you have a route with an object Bill as a model, and the path bills/:billId, on your controller you can retrieve it this way:

this.get('model').id

Body:
I have an example route:

this.route('client', {path: ':id'});

I can access this in my route like this:

model: function(params) {
    console.log(params.id);
}

How do I access the :id in my controller?


问:
VBScript problem
I am trying to run the following code in vbscript:

```<code>ReturnCode = WshShell.Run("C:\Program Files\Virtutech\Simics 4.2\Simics 4.2.9\x86-win32\bin\simics.exe", 0, True)
</code>```

I get an error when I run this script saying it cannot find the file.  I think the problem is spaces in the path, but I don't want to reinstall this application to a different path.  How do I get around this?

EDIT:  Also, I need to be able to put arguments after the executable.  Do the arguments go inside the quotes or outside?

答:
I've never been a big fan of multiple quotes appearing in my code, though it is definitely a solution that works.

What I prefer to do to make my code (to me) more readable is to use chr(34) (the ASCII version of the quotation mark) when I'm adding quotes designed to surround a file name or other string that must be encased in quotes.  It's more typing, but to me it avoids the potential confusion that a line like """x y"" ""z 1 2""" can cause.

For the example used by the OP, it would look like this:

```<code>ReturnCode = WshShell.Run(chr(34) & "C:\Program Files\Virtutech\Simics 4.2\Simics 4.2.9\x86-win32\bin\simics.exe" & chr(34), 0, True)
</code>```

The reason I like this is maybe a little clearer when it comes to a path where you're throwing in command line arguments.  For example, when you look at this:

```<code>"""C:\Program Files\Some Vendor\Application\program.exe"" -file ""data file.txt"""
</code>```

It's kind of hard to see what all those quotes are and to figure out what quotes are around what.

Compare that to:

```<code>chr(34) & "C:\Program Files\Some Vendor\Application\program.exe" & chr(34) & _
" -file" & chr(34) & "data file.txt" & chr(34)
</code>```

To my eye, the chr(34) becomes a way to easily visually differentiate between quotation marks that are part of a string definition (e.g., "data file.txt") and those which are needed for Windows to understand the path/filename properly (which show as chr(34) in the example).

If you're consistent about using chr(34) to mean "this is a quotation mark I need in order for Windows to understand the next item in the code" and the normal quotation mark to specify the beginning and ending of a string value, it can even make debugging issues a little easier.

But ultimately each person should do what works for them. My approach takes more typing and might confuse someone who doesn't know what chr() is.  The other takes less typing but requires you to do a bit more mental parsing of the string.  Neither is really right or wrong.

Title: VBScript problem

Body:
I am trying to run the following code in vbscript:

ReturnCode = WshShell.Run("C:\Program Files\Virtutech\Simics 4.2\Simics 4.2.9\x86-win32\bin\simics.exe", 0, True)

I get an error when I run this script saying it cannot find the file.  I think the problem is spaces in the path, but I don't want to reinstall this application to a different path.  How do I get around this?

EDIT:  Also, I need to be able to put arguments after the executable.  Do the arguments go inside the quotes or outside?

Body:
I've never been a big fan of multiple quotes appearing in my code, though it is definitely a solution that works.

What I prefer to do to make my code (to me) more readable is to use chr(34) (the ASCII version of the quotation mark) when I'm adding quotes designed to surround a file name or other string that must be encased in quotes.  It's more typing, but to me it avoids the potential confusion that a line like """x y"" ""z 1 2""" can cause.

For the example used by the OP, it would look like this:

ReturnCode = WshShell.Run(chr(34) & "C:\Program Files\Virtutech\Simics 4.2\Simics 4.2.9\x86-win32\bin\simics.exe" & chr(34), 0, True)

The reason I like this is maybe a little clearer when it comes to a path where you're throwing in command line arguments.  For example, when you look at this:

"""C:\Program Files\Some Vendor\Application\program.exe"" -file ""data file.txt"""

It's kind of hard to see what all those quotes are and to figure out what quotes are around what.

Compare that to:

chr(34) & "C:\Program Files\Some Vendor\Application\program.exe" & chr(34) & _
" -file" & chr(34) & "data file.txt" & chr(34)

To my eye, the chr(34) becomes a way to easily visually differentiate between quotation marks that are part of a string definition (e.g., "data file.txt") and those which are needed for Windows to understand the path/filename properly (which show as chr(34) in the example).

If you're consistent about using chr(34) to mean "this is a quotation mark I need in order for Windows to understand the next item in the code" and the normal quotation mark to specify the beginning and ending of a string value, it can even make debugging issues a little easier.

But ultimately each person should do what works for them. My approach takes more typing and might confuse someone who doesn't know what chr() is.  The other takes less typing but requires you to do a bit more mental parsing of the string.  Neither is really right or wrong.


问:
Magento 2 table weight name
I want to do a major changes in the weights of my products in Magento 2.

I don't want to manually change all the products, that will take days. I want to change them in the database directly, but in which table(s) are the product weights stored?

答:
```<code>use Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$_product = $objectManager->create('Magento\Catalog\Model\Product');
$_product = $_product->setWeight(4.0000);

$_product->save();
</code>```

It is a just example for you.

To achieve your requirement you have to getProductCollection make foreach loop over that collection and get product from that collection than you can apply this example as per your requirement.

This example will not work in .phtml file or your extension.

To check this file you need to create external .php file on root of your magento 2.

Hope this will helps you.

Title: Magento 2 table weight name

Body:
use Magento\Framework\App\Bootstrap;
include('app/bootstrap.php');
$bootstrap = Bootstrap::create(BP, $_SERVER);

$objectManager = $bootstrap->getObjectManager();

$state = $objectManager->get('Magento\Framework\App\State');
$state->setAreaCode('frontend');

$_product = $objectManager->create('Magento\Catalog\Model\Product');
$_product = $_product->setWeight(4.0000);

$_product->save();

It is a just example for you.

To achieve your requirement you have to getProductCollection make foreach loop over that collection and get product from that collection than you can apply this example as per your requirement.

This example will not work in .phtml file or your extension.

To check this file you need to create external .php file on root of your magento 2.

Hope this will helps you.


问:
foreign keys without on delete cascade
I have two tables:

```<code>Challenge:

challengeID INTEGER PRIMARY KEY
...
</code>```

And

```<code>UserChallenge:

ID INTEGER  PRIMARY KEY
challengeID INTEGER NOT NULL
...
FOREIGN KEY(challengeid) REFERENCES challenge(challengeID)
</code>```

If I have one row on challenge table, with challengeID = 1, and one row on UserChallenge table with challengeID = 1.

What would happen with UserChallenge table if I delete the row from the Challenge? May I use ON DELETE CASCADE with UserChallenge.challengeID?

Thanks.

答:
You could do a test...

If you delete the row from Challenge, the constraint on challengeID in UserChallenge gets violated. You have to delete all referencing records in this table as well, or update these records using another (correct) value or use a NULL. You could also use ON DELETE CASCADE when you want to delete the referencing records.

Title: foreign keys without on delete cascade

Body:
I have two tables:

Challenge:

challengeID INTEGER PRIMARY KEY
...

And

UserChallenge:

ID INTEGER  PRIMARY KEY
challengeID INTEGER NOT NULL
...
FOREIGN KEY(challengeid) REFERENCES challenge(challengeID)

If I have one row on challenge table, with challengeID = 1, and one row on UserChallenge table with challengeID = 1.

What would happen with UserChallenge table if I delete the row from the Challenge? May I use ON DELETE CASCADE with UserChallenge.challengeID?

Thanks.


问:
ImportError: No module named django.core.management when using manage.py
I'm trying to run python manage.py runserver on a Django application I have and I get this error:

```<code>Traceback (most recent call last):
File "manage.py", line 8, in <module>
 from django.core.management import execute_from_command_line
ImportError: No module named django.core.management
</code>```

Here is the output of pip freeze | grep -i django to show I do in fact have Django installed:

```<code>Django==1.6.5
django-cached-authentication-middleware==0.2.0
django-cors-headers==1.1.0
django-htmlmin==0.7.0
django-static-precompiler==0.9
djangorestframework==2.3.14
</code>```

Also, trying to run /usr/local/bin/python2.7 manage.py runserver yields the same error.

答:
I found that I could import the django module from the python interpreter, but django-admin.py could not import it when run from the command line.

I confirmed that I was using the python interpreter in my virtual environment.

I was using a 64-bit version of python. Uninstalling, and installing the 32-bit version, then re-creating my venv solved this for me.

Body:
I'm trying to run python manage.py runserver on a Django application I have and I get this error:

Traceback (most recent call last):
File "manage.py", line 8, in <module>
 from django.core.management import execute_from_command_line
ImportError: No module named django.core.management

Here is the output of pip freeze | grep -i django to show I do in fact have Django installed:

Django==1.6.5
django-cached-authentication-middleware==0.2.0
django-cors-headers==1.1.0
django-htmlmin==0.7.0
django-static-precompiler==0.9
djangorestframework==2.3.14

Also, trying to run /usr/local/bin/python2.7 manage.py runserver yields the same error.


问:
Error in javascript KeyListener
I have the error: index.html:12 Uncaught TypeError: Cannot read property 'addEventListener' of null
Not sure what went wrong? The code is suppose to store the result of the radio button selected into an array. But the function does not even run because it is null.

```<code><!DOCTYPE html>
<html>
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Video Test</title>
    <script>
      var arr = [];
      document.getElementById("continue").addEventListener("click", function() {
          var cbChecked = document.querySelectorAll('[name="white"]:checked')
          if (cbChecked != null) {
            arr.push(cbChecked.value)
          }
          console.log(arr)
      })
    </script>
  </head>
  <body>
    <div id="container">
      <div id="overlay">
        <form action="">
          <input type="radio" name="white" value="1" id="radio1"/>
          <input type="radio" name="white" value="2" id="radio2"/>
          <input type="radio" name="white" value="3" id="radio3"/>
          <input type="radio" name="white" value="4" id="radio4"/>
          <input type="button" id="continue" value="Continue"/>
        </form>
      </div>
      <div id="base">
        <video controls>
          <source src="videos/event_0_Junli_Standing_20150322_181647_00_0.6.mp4" type="video/mp4">
          Your browser does not support the video tag.
        </video>
      </div>
    </div>
  </body>
</html>
</code>```

答: You are running your

Title: Error in javascript KeyListener

Body:
I have the error: index.html:12 Uncaught TypeError: Cannot read property 'addEventListener' of null
Not sure what went wrong? The code is suppose to store the result of the radio button selected into an array. But the function does not even run because it is null.

<!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Video Test</title>

        <form action="">
          <input type="radio" name="white" value="1" id="radio1"/>
          <input type="radio" name="white" value="2" id="radio2"/>
          <input type="radio" name="white" value="3" id="radio3"/>
          <input type="radio" name="white" value="4" id="radio4"/>
          <input type="button" id="continue" value="Continue"/>
        </form>

        <video controls>
          <source src="videos/event_0_Junli_Standing_20150322_181647_00_0.6.mp4" type="video/mp4">
          Your browser does not support the video tag.
        </video>

Body: You are running your <script> before the DOM elements are there.  Move the <script> to the bottom of the <body> tag.


问:
How to get the value of an input box using angular

function DefaultController($scope, navBarService) {
    var vm = this;

    $scope.toggleHeader = true;
    $scope.userNameNav ='';
    //Sharing info with other controllers
    $scope.$on('toggleHeader', function(evt, data) {
        $scope.toggleHeader = data;
    });

    $scope.$on('changeName', function(evt, data) {
        $scope.userNameNav = data;
    });

    $scope.searchForItem = function() {
        console.log('button clicked');
        console.log($scope.userSearch);

    };

}//end DefaultController```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.Navigation {

    width:100%;
    height:25em;
    background-image: url('http://wallpapercave.com/wp/UYnUUzz.jpg');
    background-size: cover;
background-position:50% 50%;
position: sticky;

}

.navContent {
    float:right;
}

.searchNav {

    border: 0;
    border-bottom: 1px solid red;
    outline: 0;
}</code>```

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Rental app</title>
        <link rel="stylesheet" href="styles/userPage.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">
        <link rel="stylesheet" href="styles/register.css">
        <link rel="stylesheet" href="styles/style.css">

                    Logout
                    <input class='searchNav' type="button" name="button" value="Search" ng-click='searchForItem()' >
                    <input id='getUserInput' type="text"  placeholder="Search Item" ng-model='userSearch'/>{{ userSearch }}

Welcome {{userNameNav}}

            <ng-view></ng-view>

```

In the html file i want to get the value of the users search when i click the search button. I am able to get a console log of 'button clicked', but i can not get the value of the search box. I tried using vm too, but that didnt work so i took it out

答:
You should declare your variable in controller before you put it in model. You can write: $scope.formData = {}; and use this object in HTML and JS.

Use this version:

```<code>function DefaultController($scope, navBarService) {
    var vm = this;

    $scope.toggleHeader = true;
    $scope.userNameNav ='';
$scope.formData = {};
    //Sharing info with other controllers
    $scope.$on('toggleHeader', function(evt, data) {
        $scope.toggleHeader = data;
    });

    $scope.$on('changeName', function(evt, data) {
        $scope.userNameNav = data;
    });

    $scope.searchForItem = function() {
        console.log('button clicked');
        console.log($scope.formData.userSearch);

    };

}//end DefaultController
</code>```

And in your template:

```<code><input id='getUserInput' type="text"  placeholder="Search Item" ng-model='formData.userSearch'/>{{ formData.userSearch }}
</code>```

Body:
function DefaultController($scope, navBarService) {
    var vm = this;

    $scope.toggleHeader = true;
    $scope.userNameNav ='';
    //Sharing info with other controllers
    $scope.$on('toggleHeader', function(evt, data) {
        $scope.toggleHeader = data;
    });

    $scope.$on('changeName', function(evt, data) {
        $scope.userNameNav = data;
    });

    $scope.searchForItem = function() {
        console.log('button clicked');
        console.log($scope.userSearch);

    };

}//end DefaultController

.Navigation {

    width:100%;
    height:25em;
    background-image: url('http://wallpapercave.com/wp/UYnUUzz.jpg');
    background-size: cover;
background-position:50% 50%;
position: sticky;

}

.navContent {
    float:right;
}

.searchNav {

    border: 0;
    border-bottom: 1px solid red;
    outline: 0;
}

<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Rental app</title>
        <link rel="stylesheet" href="styles/userPage.css">
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/sweetalert/1.1.3/sweetalert.min.css">
        <link rel="stylesheet" href="styles/register.css">
        <link rel="stylesheet" href="styles/style.css">

                    Logout
                    <input class='searchNav' type="button" name="button" value="Search" ng-click='searchForItem()' >
                    <input id='getUserInput' type="text"  placeholder="Search Item" ng-model='userSearch'/>{{ userSearch }}

Welcome {{userNameNav}}

            <ng-view></ng-view>

In the html file i want to get the value of the users search when i click the search button. I am able to get a console log of 'button clicked', but i can not get the value of the search box. I tried using vm too, but that didnt work so i took it out

Body:
You should declare your variable in controller before you put it in model. You can write: $scope.formData = {}; and use this object in HTML and JS.

Use this version:

function DefaultController($scope, navBarService) {
    var vm = this;

    $scope.toggleHeader = true;
    $scope.userNameNav ='';
$scope.formData = {};
    //Sharing info with other controllers
    $scope.$on('toggleHeader', function(evt, data) {
        $scope.toggleHeader = data;
    });

    $scope.$on('changeName', function(evt, data) {
        $scope.userNameNav = data;
    });

    $scope.searchForItem = function() {
        console.log('button clicked');
        console.log($scope.formData.userSearch);

    };

}//end DefaultController

And in your template:

<input id='getUserInput' type="text"  placeholder="Search Item" ng-model='formData.userSearch'/>{{ formData.userSearch }}


问:
Codeigniter - matching user entered password to hashed password stored in DB always returns false. Please help
I have my controller Setup
my join_model
and my login_model

A user registers and after they have passed all validation and captcha etc and have clicked submit they are set to setup.

My setup controller loads the join_model and the create() method, takes all the post data and gets ready to send it to db. This is when the password they entered in the signup form get's hashed, salted etc.

After this I have an if statement that checks whether user passed the checkLogin method in the login_model with TRUE. This method is in the setup controller and I called it loginValidated.

If that is TRUE then user is re-directed to member area (dash).

When I test I keep getting sent to the failed page. I also changed the if state to (!this->loginValidated()) and then I get de-directed to the account area meaning the passwords must not match.

I was wondering if anyone could have a quick look through my code to see if they spot where I'm going wrong?

```<code><?php

class Setup extends Controller {

    public function index() {

        $this->load->model('join_model');
        $this->join_model->create();
        if ($this->loginValidated()) { //if user credentials passed validation

        redirect('dash'); //forward to dashboard
        }
        else {
            redirect('failed');
        }
    }
    public function loginValidated() {
        $this->load->model('login_model'); //load login_model model
        $this->login_model->checkLogin(); //load checkLogin method

    }
 }

<?php
//MY CONTROLLER

class Login_Model extends CI_Model {

    public function checkLogin() {
            return Join_Model::$u;

            $this->db->where('email', $this->input->post('email')); //compare db email to email entered in form
            $this->db->where('password', $u->password); //compare db password to password entered by user after hashing
            $query = $this->db->get('user'); // get the above info from 'user' table

            if ($query->num_rows == 1) { //if number of rows returned is 1

            $this->load->library('session');
            $this->session->set_userdata('user_id',$u->id);
            $this->session->set_userdata('username',$u->username);
            $this->session->set_userdata('first_name',$u->first_name);
            $this->session->set_userdata('last_name',$u->last_name);
            $this->session->set_userdata('logged_in', 'TRUE');

            return TRUE;
      }
   }
}

<?php
// MY JOIN MODEL

class Join_Model extends CI_Model {
    public static $u;
    public function create() {
                $this->load->helper('date');
                $this->load->library('encrypt');

  $u->first_name = $this->input->post('first_name');
                $u->last_name = $this->input->post('last_name');
                $u->email = $this->input->post('email');

                // sha1 and salt password
                $salt = $this->config->item('encryption_key');
  $password = $this->encrypt->sha1($this->input->post('password'));
                $start_hash = sha1($salt . $password);
                $end_hash = sha1($password . $salt);
                $hashed = sha1($start_hash . $password . $end_hash);
                $u->password = sha1($hashed);

                $u->birthday = $this->input->post('year') . '-' . $this->input->post('month') . '-' . $this->input->post('day');
                $u->sex = $this->input->post('sex');

                $u->created_at = date('Y-m-d H:i:s', now()); // date and time user joined the website

                $this->db->insert('user', $u);

    }
}
</code>```

答: You want to hash any user-entered password and then check the hash against the database, not the raw string the user entered.</p>

Body:
I have my controller Setup
my join_model
and my login_model

A user registers and after they have passed all validation and captcha etc and have clicked submit they are set to setup.

My setup controller loads the join_model and the create() method, takes all the post data and gets ready to send it to db. This is when the password they entered in the signup form get's hashed, salted etc.

After this I have an if statement that checks whether user passed the checkLogin method in the login_model with TRUE. This method is in the setup controller and I called it loginValidated.

If that is TRUE then user is re-directed to member area (dash).

When I test I keep getting sent to the failed page. I also changed the if state to (!this->loginValidated()) and then I get de-directed to the account area meaning the passwords must not match.

I was wondering if anyone could have a quick look through my code to see if they spot where I'm going wrong?

<?php

class Setup extends Controller {

    public function index() {

        $this->load->model('join_model');
        $this->join_model->create();
        if ($this->loginValidated()) { //if user credentials passed validation

        redirect('dash'); //forward to dashboard
        }
        else {
            redirect('failed');
        }
    }
    public function loginValidated() {
        $this->load->model('login_model'); //load login_model model
        $this->login_model->checkLogin(); //load checkLogin method

    }
 }

<?php
//MY CONTROLLER

class Login_Model extends CI_Model {

    public function checkLogin() {
            return Join_Model::$u;

            $this->db->where('email', $this->input->post('email')); //compare db email to email entered in form
            $this->db->where('password', $u->password); //compare db password to password entered by user after hashing
            $query = $this->db->get('user'); // get the above info from 'user' table

            if ($query->num_rows == 1) { //if number of rows returned is 1

            $this->load->library('session');
            $this->session->set_userdata('user_id',$u->id);
            $this->session->set_userdata('username',$u->username);
            $this->session->set_userdata('first_name',$u->first_name);
            $this->session->set_userdata('last_name',$u->last_name);
            $this->session->set_userdata('logged_in', 'TRUE');

            return TRUE;
      }
   }
}

<?php
// MY JOIN MODEL

class Join_Model extends CI_Model {
    public static $u;
    public function create() {
                $this->load->helper('date');
                $this->load->library('encrypt');

  $u->first_name = $this->input->post('first_name');
                $u->last_name = $this->input->post('last_name');
                $u->email = $this->input->post('email');

                // sha1 and salt password
                $salt = $this->config->item('encryption_key');
  $password = $this->encrypt->sha1($this->input->post('password'));
                $start_hash = sha1($salt . $password);
                $end_hash = sha1($password . $salt);
                $hashed = sha1($start_hash . $password . $end_hash);
                $u->password = sha1($hashed);

                $u->birthday = $this->input->post('year') . '-' . $this->input->post('month') . '-' . $this->input->post('day');
                $u->sex = $this->input->post('sex');

                $u->created_at = date('Y-m-d H:i:s', now()); // date and time user joined the website

                $this->db->insert('user', $u);

    }
}


问:
How to comment in react that will be compiled by webpack
It's all in the title really, I've try'ed:

```<code>/*Comment here*/
</code>```

and

```<code>//Comment here
</code>```

But both show up on the webpage.

答:
The only way to add comments in JSX is to use {/* ... */} syntax, for example:

```<code>...
<div>
  {/* A JSX comment */}
</div>
...
</code>```

The HTML comments  do not work, plain JS comments // and /* ... */ do not work too.

Body:
It's all in the title really, I've try'ed:

/*Comment here*/

and

//Comment here

But both show up on the webpage.

Body:
The only way to add comments in JSX is to use {/* ... */} syntax, for example:

...
<div>
  {/* A JSX comment */}
</div>
...

The HTML comments <!-- ... --> do not work, plain JS comments // and /* ... */ do not work too.


问:
XQuery concat not outputting document XML in expected way
```<code>let $d := doc('foo.xml')

return concat('let $d :=

', $d)
</code>```

returns

```<code>let $d :=

bar
</code>```

I need it to return:

```<code>let $d :=

<foo>bar</foo>
</code>```

答:
Use pipes to concatenate.
Eg: $a||$b
If your variables are of atomic type, then you can use a string-join.
eg:, $a||fn:string-join(($b),",")</p>

Body:
let $d := doc('foo.xml')

return concat('let $d :=

', $d)

returns

let $d :=

bar

I need it to return:

let $d :=

<foo>bar</foo>


问:
CK metrics from C# project with Ndepend
I have project for school. Now I need to make from it report of all metrics CK (Chidamber Kemerer metrics). The report has to be like table of all those metrics. Question is how to make it from Ndepend this report which it generates it is not what I am looking for.

Please help and say how to do it... maybe some tips, documents or something this is very important...

答:
Ok, so if we are talking of these Chidamber Kemerer metrics, the NDepend ability to write Code Queries and Rules over LINQ queries (CQLinq) will answer all your needs. For example:

WMC Weighted Methods Per Class

```<code>warnif count > 0
from t in Application.Types
let methods = t.Methods
   .Where(m => !m.IsPropertyGetter &&
               !m.IsPropertySetter &&
               !m.IsConstructor)
where methods.Count() > 20
orderby methods.Count() descending
select new { t, methods }
</code>```

DIT Depth of Inheritance Tree

```<code>warnif count > 0
from t in JustMyCode.Types
where t.IsClass
let baseClasses = t.BaseClasses.ExceptThirdParty()
where baseClasses.Count() >= 5
select new { t, baseClasses,
                // The metric value DepthOfInheritance takes account
                // of third-party base classes
                t.DepthOfInheritance
}
</code>```

NOC Number of Children

```<code>from t in Types
where t.IsClass
let childClasses = t.DerivedTypes
where childClasses.Count() > 0
orderby childClasses.Count() descending
select new { t, childClasses }
</code>```

CBO Coupling between Object Classes

```<code>from t in Application.Types
let typesUsed = t.TypesUsed.ExceptThirdParty()
orderby typesUsed.Count() descending
select new { t, typesUsed }
</code>```

and so on...

Title: CK metrics from C# project with Ndepend

Body:
Ok, so if we are talking of these Chidamber Kemerer metrics, the NDepend ability to write Code Queries and Rules over LINQ queries (CQLinq) will answer all your needs. For example:

WMC Weighted Methods Per Class

warnif count > 0
from t in Application.Types
let methods = t.Methods
   .Where(m => !m.IsPropertyGetter &&
               !m.IsPropertySetter &&
               !m.IsConstructor)
where methods.Count() > 20
orderby methods.Count() descending
select new { t, methods }

DIT Depth of Inheritance Tree

warnif count > 0
from t in JustMyCode.Types
where t.IsClass
let baseClasses = t.BaseClasses.ExceptThirdParty()
where baseClasses.Count() >= 5
select new { t, baseClasses,
                // The metric value DepthOfInheritance takes account
                // of third-party base classes
                t.DepthOfInheritance
}

NOC Number of Children

from t in Types
where t.IsClass
let childClasses = t.DerivedTypes
where childClasses.Count() > 0
orderby childClasses.Count() descending
select new { t, childClasses }

CBO Coupling between Object Classes

from t in Application.Types
let typesUsed = t.TypesUsed.ExceptThirdParty()
orderby typesUsed.Count() descending
select new { t, typesUsed }

and so on...


问:
Conversion failed when converting the varchar value 'd1' to data type int
I have a column in the table of Varchar data type. Before inserting data in this field I am retrieving maximum value from the table using this query:

```<code>string max = g1.retrieve_val("select isnull(max(cast(substring(aid,3,(len(aid)-1)) as int)+1),1) from tbl_name");
max = "aid" + max;
</code>```

Then using insert query to enter data in this field. But while doing this I am getting this error:

Conversion failed when converting the varchar value 'd1' to data type int

Please guide me how can I rectify this? Am I doing something wrong? Although I have used the same approach in other tables, there I was no getting any error. But in this particular able I am getting this error.

答:
```<code>cnx.cmd = new SqlCommand("INSERT INTO Usuario(id,nombre,apellido) VALUES((SELECT CONVERT(int,(SELECT ISNULL(MAX(id)+1,1) FROM Usuario))),'" + Nombre + "','" + Apellido + "')", cnx.cn);
</code>```

Body:
I have a column in the table of Varchar data type. Before inserting data in this field I am retrieving maximum value from the table using this query:

string max = g1.retrieve_val("select isnull(max(cast(substring(aid,3,(len(aid)-1)) as int)+1),1) from tbl_name");
max = "aid" + max;

Then using insert query to enter data in this field. But while doing this I am getting this error:

Conversion failed when converting the varchar value 'd1' to data type int

Please guide me how can I rectify this? Am I doing something wrong? Although I have used the same approach in other tables, there I was no getting any error. But in this particular able I am getting this error.


问:
Finding headings for multiple lists in a single sheet and autofilling a formula from the bottom
Hopefully my title is clear. I am trying to first find the heading "WT/PC" in a list, going to the bottom of that list, copying the formula that is there all the way up until the header, and then find the next instance of "WT/PC" on the sheet (they aren't always in the same column) and then do the same for it. I want to do this about 10-20 times. I have a combination of Macro Recorder Code and some that I have added. I have located WT/Pc, went to the bottom of the list, but now am having syntactical issues with using Autofill to fill up the column using  xlUp

Sample picture to help better visualize: http://imgur.com/a/euYr1
http://imgur.com/a/euYr1
Current Code:

```<code>Sub Formula_Fill_Using_Find()

Dim lastRow As Long
Dim rowCount, row_ix, temp, i As Integer
Dim TD_COL_IX As Integer
Dim td_value As String
Dim td_values() As String

' #################
' Count rows starting in column A
' #################
 For row_ix = 1 To 25 ' 25 was previously "rowCount"

ActiveCell.Select
Cells.Find(What:="WT/PC", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate

Selection.End(xlDown).Select

ActiveCell.AutoFill Range(ActiveCell.Address & ":" &
Left(ActiveCell.Address, Len(ActiveCell.Address)) & xlUp)

Next row_ix

End Sub
</code>```

答:
Try this:</p>

```<code>Option Explicit

Public Sub ReverseFill()
    Dim ur As Range, found As Range, adr As Variant, cr As Range, lr As Long

    Set ur = Sheet1.UsedRange
    Set found = ur.Find("WT/PC", , xlFormulas, xlPart, xlByRows, , False)

    If Not found Is Nothing Then
        adr = found.Address

        Application.ScreenUpdating = False
        Do
            Set cr = found.CurrentRegion:          lr = cr.Rows.Count - 1
            cr.Columns(1).Offset(1).Resize(lr - 1).Formula = found.Offset(lr).Formula
            Set found = ur.FindNext(found)
        Loop While found.Address <> adr
        Application.ScreenUpdating = True
    End If
End Sub
</code>```

Body:
Hopefully my title is clear. I am trying to first find the heading "WT/PC" in a list, going to the bottom of that list, copying the formula that is there all the way up until the header, and then find the next instance of "WT/PC" on the sheet (they aren't always in the same column) and then do the same for it. I want to do this about 10-20 times. I have a combination of Macro Recorder Code and some that I have added. I have located WT/Pc, went to the bottom of the list, but now am having syntactical issues with using Autofill to fill up the column using  xlUp

Sample picture to help better visualize: http://imgur.com/a/euYr1
http://imgur.com/a/euYr1
Current Code:

Sub Formula_Fill_Using_Find()

Dim lastRow As Long
Dim rowCount, row_ix, temp, i As Integer
Dim TD_COL_IX As Integer
Dim td_value As String
Dim td_values() As String

' #################
' Count rows starting in column A
' #################
 For row_ix = 1 To 25 ' 25 was previously "rowCount"

ActiveCell.Select
Cells.Find(What:="WT/PC", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate

Selection.End(xlDown).Select

ActiveCell.AutoFill Range(ActiveCell.Address & ":" &
Left(ActiveCell.Address, Len(ActiveCell.Address)) & xlUp)

Next row_ix

End Sub

Body:
Try this:

Option Explicit

Public Sub ReverseFill()
    Dim ur As Range, found As Range, adr As Variant, cr As Range, lr As Long

    Set ur = Sheet1.UsedRange
    Set found = ur.Find("WT/PC", , xlFormulas, xlPart, xlByRows, , False)

    If Not found Is Nothing Then
        adr = found.Address

        Application.ScreenUpdating = False
        Do
            Set cr = found.CurrentRegion:          lr = cr.Rows.Count - 1
            cr.Columns(1).Offset(1).Resize(lr - 1).Formula = found.Offset(lr).Formula
            Set found = ur.FindNext(found)
        Loop While found.Address <> adr
        Application.ScreenUpdating = True
    End If
End Sub


问:
Combine grep and factor from different columns in selecting R dataframe rows
I am am changing values in the column df$AccPat in a dataframe based on values in other cells. Starting point:

```<code>      AccVs               Verb              Acc      LVs AccPat
0         2            pádsáda               fa        1      u
1         1     pácccaiiidncll               ma        2      u
2         0                saa               un        1      u
3         0               liss               un        0      u
4         1           litátoko               fa        0      u
5         1           wupágaak               ma        1      u
</code>```

I can combine multiple factors, thus:

```<code>df[df$Acc == "fa" & df$LVs == "0",]$AccPat <- "a"

      AccVs               Verb              Acc      LVs AccPat
0         2            pádsáda               fa        1      u
1         1     pácccaiiidncll               ma        2      u
2         0                saa               un        1      u
3         0               liss               un        0      u
4         1           litátoko               fa        0      a
5         1           wupágaak               ma        1      u
</code>```

or I can use grep to choose rows which match a regular expression in one column:

```<code>df[grep("^pá", df$Verb),]$AccPat <- "p"

      AccVs               Verb              Acc      LVs AccPat
0         2            pádsáda               fa        1      p
1         1     pácccaiiidncll               ma        2      p
2         0                saa               un        1      u
3         0               liss               un        0      u
4         1           litátoko               fa        0      a
5         1           wupágaak               ma        1      p
</code>```

but I would like to do both at the same time, so only choose rows matching the regular expression above that have a value of "1" in df$AccVs.

```<code>      AccVs               Verb              Acc      LVs AccPat
0         2            pádsáda               fa        1      u
1         1     pácccaiiidncll               ma        2      b
2         0                saa               un        1      u
3         0               liss               un        0      u
4         1           litátoko               fa        0      a
5         1           wupágaak               ma        1      u
</code>```

I used to think this was impossible, but this question makes me think it isn't. However, the solution given there does not work for me.

```<code>df[grep("^pá", df$Verb) & df$AccVs == "1"]$AccPat <- "b"
</code>```

results in the errors "undefined columns selected" and "longer object length is not a multiple of shorter object length", and

```<code>df[grep("^pá", df$Verb) & df$AccVs == "1",]$AccPat <- "b"
</code>```

attempts to print my entire dataframe (which is much larger than this sample one), and also results in the error "longer object length is not a multiple of shorter object length".

Note: Many of the values I am checking for are strings, so I need a solution that works for strings. I'm not doing anything numeric, so it's fine if I treat the integers as stings.

答:
Here's your data frame:

```<code>df <- data.frame(AccVs=c(2,1,0,0,1,1), Verb=c("pádsáda","pácccaiiidncll","saa","liss","litátoko","wupágaak"),
                 Acc=c("fa","ma","un","un","fa","ma"),
                 LVs=c(1,2,1,0,0,1),
                 AccPat=rep("u",6),
                 stringsAsFactors=F)
</code>```

grep and == return different classes:

```<code>grep("^pá", df$Verb)
[1] 1 2

df$AccVs == "1"
[1] FALSE  TRUE FALSE FALSE  TRUE  TRUE
</code>```

Use grepl to return logical

```<code>grepl("^pá", df$Verb)
[1] TRUE TRUE FALSE FALSE FALSE FALSE
</code>```

The result:

```<code>  AccVs           Verb Acc LVs AccPat
1     2        pádsáda  fa   1      u
2     1 pácccaiiidncll  ma   2      b
3     0            saa  un   1      u
4     0           liss  un   0      u
5     1       litátoko  fa   0      u
6     1       wupágaak  ma   1      u
</code>```

Body:
I am am changing values in the column df$AccPat in a dataframe based on values in other cells. Starting point:

      AccVs               Verb              Acc      LVs AccPat
0         2            pádsáda               fa        1      u
1         1     pácccaiiidncll               ma        2      u
2         0                saa               un        1      u
3         0               liss               un        0      u
4         1           litátoko               fa        0      u
5         1           wupágaak               ma        1      u

I can combine multiple factors, thus:

df[df$Acc == "fa" & df$LVs == "0",]$AccPat <- "a"

      AccVs               Verb              Acc      LVs AccPat
0         2            pádsáda               fa        1      u
1         1     pácccaiiidncll               ma        2      u
2         0                saa               un        1      u
3         0               liss               un        0      u
4         1           litátoko               fa        0      a
5         1           wupágaak               ma        1      u

or I can use grep to choose rows which match a regular expression in one column:

df[grep("^pá", df$Verb),]$AccPat <- "p"

      AccVs               Verb              Acc      LVs AccPat
0         2            pádsáda               fa        1      p
1         1     pácccaiiidncll               ma        2      p
2         0                saa               un        1      u
3         0               liss               un        0      u
4         1           litátoko               fa        0      a
5         1           wupágaak               ma        1      p

but I would like to do both at the same time, so only choose rows matching the regular expression above that have a value of "1" in df$AccVs.

      AccVs               Verb              Acc      LVs AccPat
0         2            pádsáda               fa        1      u
1         1     pácccaiiidncll               ma        2      b
2         0                saa               un        1      u
3         0               liss               un        0      u
4         1           litátoko               fa        0      a
5         1           wupágaak               ma        1      u

I used to think this was impossible, but this question makes me think it isn't. However, the solution given there does not work for me.

df[grep("^pá", df$Verb) & df$AccVs == "1"]$AccPat <- "b"

results in the errors "undefined columns selected" and "longer object length is not a multiple of shorter object length", and

df[grep("^pá", df$Verb) & df$AccVs == "1",]$AccPat <- "b"

attempts to print my entire dataframe (which is much larger than this sample one), and also results in the error "longer object length is not a multiple of shorter object length".

Note: Many of the values I am checking for are strings, so I need a solution that works for strings. I'm not doing anything numeric, so it's fine if I treat the integers as stings.

Body:
Here's your data frame:

df <- data.frame(AccVs=c(2,1,0,0,1,1), Verb=c("pádsáda","pácccaiiidncll","saa","liss","litátoko","wupágaak"),
                 Acc=c("fa","ma","un","un","fa","ma"),
                 LVs=c(1,2,1,0,0,1),
                 AccPat=rep("u",6),
                 stringsAsFactors=F)

grep and == return different classes:

grep("^pá", df$Verb)
[1] 1 2

df$AccVs == "1"
[1] FALSE  TRUE FALSE FALSE  TRUE  TRUE

Use grepl to return logical

grepl("^pá", df$Verb)
[1] TRUE TRUE FALSE FALSE FALSE FALSE

The result:

  AccVs           Verb Acc LVs AccPat
1     2        pádsáda  fa   1      u
2     1 pácccaiiidncll  ma   2      b
3     0            saa  un   1      u
4     0           liss  un   0      u
5     1       litátoko  fa   0      u
6     1       wupágaak  ma   1      u


问:
How to separate an array of hashes into different arrays if a key is equal?
I've got an array of hashes in the following form:

```<code>{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0}
{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.8499999999999996}
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0}
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}
</code>```

basically i want to separate that array into arrays that contain the same value for the key beneficiary_document, so for this example i'd expect two arrays, one containing:

```<code>{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0}
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0}
</code>```

and another one containing

```<code>{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}
{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.8499999999999996}
</code>```

How can i grant this?

Thanks a lot for reading.

答:
Here are three ways to obtain the desired result by constructing a hash and then extracting the values.

```<code>arr = [{"id"=>2, "name"=>"Pepo",   "doc"=>"43991028", "cal"=>5.0},
       {"id"=>2, "name"=>"Pepo",   "doc"=>"71730550", "cal"=>3.8},
       {"id"=>3, "name"=>"Carlos", "doc"=>"43991028", "cal"=>0.0},
       {"id"=>3, "name"=>"Carlos", "doc"=>"71730550", "cal"=>3.4}]
</code>```

#1

This uses the form of Hash::new that includes a block that is invoked when h[k] is executed, for a hash h that has no key k.

```<code>arr.each_with_object(Hash.new { |h,k| h[k]=[] }) { |g,h| h[g["doc"]] << g }.
    values
  #=> [[{"id"=>2, "name"=>"Pepo", "doc"=>"43991028", "cal"=>5.0},
  #     {"id"=>3, "name"=>"Carlos", "doc"=>"43991028", "cal"=>0.0}],
  #    [{"id"=>2, "name"=>"Pepo", "doc"=>"71730550", "cal"=>3.8},
  #     {"id"=>3, "name"=>"Carlos", "doc"=>"71730550", "cal"=>3.4}]]
</code>```

#2

This is equivalent to #1.

```<code>arr.each_with_object({}) { |g,h| (h[g["doc"]] ||= []) << g }.
    values
</code>```

#3

This uses the form of Hash#update (aka merge!) that employs a block (here { |_,o,n| o+n }) to determine the value of keys that are present in both hashes being merged. See the doc for the definitions of the three variables of the value-determining block.

```<code>arr.each_with_object({}) { |g,h| h.update(g["doc"]=>[g]) { |_,o,n| o+n } }.
    values
</code>```

Body:
I've got an array of hashes in the following form:

{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0}
{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.8499999999999996}
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0}
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}

basically i want to separate that array into arrays that contain the same value for the key beneficiary_document, so for this example i'd expect two arrays, one containing:

{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>5.0}
{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"43991028", "calification_by_qualifier"=>0.0}

and another one containing

{"user_id"=>3, "user_name"=>"Carlos", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.4}
{"user_id"=>2, "user_name"=>"Pepo", "beneficiary_document"=>"71730550", "calification_by_qualifier"=>3.8499999999999996}

How can i grant this?

Thanks a lot for reading.

Body:
Here are three ways to obtain the desired result by constructing a hash and then extracting the values.

arr = [{"id"=>2, "name"=>"Pepo",   "doc"=>"43991028", "cal"=>5.0},
       {"id"=>2, "name"=>"Pepo",   "doc"=>"71730550", "cal"=>3.8},
       {"id"=>3, "name"=>"Carlos", "doc"=>"43991028", "cal"=>0.0},
       {"id"=>3, "name"=>"Carlos", "doc"=>"71730550", "cal"=>3.4}]

#1

This uses the form of Hash::new that includes a block that is invoked when h[k] is executed, for a hash h that has no key k.

arr.each_with_object(Hash.new { |h,k| h[k]=[] }) { |g,h| h[g["doc"]] << g }.
    values
  #=> [[{"id"=>2, "name"=>"Pepo", "doc"=>"43991028", "cal"=>5.0},
  #     {"id"=>3, "name"=>"Carlos", "doc"=>"43991028", "cal"=>0.0}],
  #    [{"id"=>2, "name"=>"Pepo", "doc"=>"71730550", "cal"=>3.8},
  #     {"id"=>3, "name"=>"Carlos", "doc"=>"71730550", "cal"=>3.4}]]

#2

This is equivalent to #1.

arr.each_with_object({}) { |g,h| (h[g["doc"]] ||= []) << g }.
    values

#3

This uses the form of Hash#update (aka merge!) that employs a block (here { |_,o,n| o+n }) to determine the value of keys that are present in both hashes being merged. See the doc for the definitions of the three variables of the value-determining block.

arr.each_with_object({}) { |g,h| h.update(g["doc"]=>[g]) { |_,o,n| o+n } }.
    values


问:
Swinject: Resolving using a list of metatypes
I'm trying to create a function to return an array of metatypes, which I can then use to resolve instances from a Swinject Resolver. Here's my code:

```<code>protocol Task: class { }

func getTypes() -> [Task.Type] {
    return [ConcreteTaskA.self, ConcreteTaskB.self]
}

var concreteTasks = [Task]()
for type in getTypes() {
    // Use a Swinject Container to resolve the metatype.
    let task = container.resolver.resolve(type)! // Error here: Cannot invoke 'resolve' with an argument list of type '(Task.Type)'
    concreteTasks.append(task)
}
</code>```

I'm not sure how to solve this. Do I need to use generics somehow with the getTypes() method? Do I need to call some equivalent of type.self when resolving?

My requirements are that I can define a list of metatypes ([ConcreteTaskA.self, ConcreteTaskB.self]) to be resolved by a resolver.

答:
So it turns out the issue may lie with using a protocol. I can get the following to work...

```<code>for type in getTypes() {
    // Use a Swinject Container to resolve the metatype.
    if let aType = type as? ConcreteTaskA.Type {
        let task = container.resolver.resolve(aType)!
        concreteTasks.append(task)
    }
}
</code>```

...but obviously it would be nice to not need to check for every type first.

If we change the protocol to a base class, however, everything works as expected:

```<code>class Task { }
class ConcreteTaskA: Task { }
class ConcreteTaskB: Task { }

func getTypes() -> [Task.Type] {
    return [ConcreteTaskA.self, ConcreteTaskB.self]
}

var concreteTasks = [Task]()
for type in getTypes() {
    // Use a Swinject Container to resolve the metatype.
    let task = container.resolver.resolve(type)!
    concreteTasks.append(task)
}
</code>```

Body:
I'm trying to create a function to return an array of metatypes, which I can then use to resolve instances from a Swinject Resolver. Here's my code:

protocol Task: class { }

func getTypes() -> [Task.Type] {
    return [ConcreteTaskA.self, ConcreteTaskB.self]
}

var concreteTasks = [Task]()
for type in getTypes() {
    // Use a Swinject Container to resolve the metatype.
    let task = container.resolver.resolve(type)! // Error here: Cannot invoke 'resolve' with an argument list of type '(Task.Type)'
    concreteTasks.append(task)
}

I'm not sure how to solve this. Do I need to use generics somehow with the getTypes() method? Do I need to call some equivalent of type.self when resolving?

My requirements are that I can define a list of metatypes ([ConcreteTaskA.self, ConcreteTaskB.self]) to be resolved by a resolver.

Body:
So it turns out the issue may lie with using a protocol. I can get the following to work...

for type in getTypes() {
    // Use a Swinject Container to resolve the metatype.
    if let aType = type as? ConcreteTaskA.Type {
        let task = container.resolver.resolve(aType)!
        concreteTasks.append(task)
    }
}

...but obviously it would be nice to not need to check for every type first.

If we change the protocol to a base class, however, everything works as expected:

class Task { }
class ConcreteTaskA: Task { }
class ConcreteTaskB: Task { }

func getTypes() -> [Task.Type] {
    return [ConcreteTaskA.self, ConcreteTaskB.self]
}

var concreteTasks = [Task]()
for type in getTypes() {
    // Use a Swinject Container to resolve the metatype.
    let task = container.resolver.resolve(type)!
    concreteTasks.append(task)
}


问:
Selenium explicit wait for LinkedIn spinning circles
I am using Selenium and its Python bindings to webscrape from LinkedIn for a research project. I webscrape people's profiles.

In LinkedIn, when you load a person profile, the site puts spinning circles until the experiences and the education are fully loaded.
I want Selenium to wait until the spinning circles disappear, in order to get, in the HTML source code, the experience and the education sections.

So my question is: How can I code an explicit wait for the LinkedIn spinning circles?

EDIT: a more precise question would be: How can I get a locator for the spinning circles?
There is no time to do that from the browser development tools. They disappear too fast

EDIT 2: Another point. A person may or may not have an education section. So clicking or otherwise checking for the education section to be present is not a solution. The education section may not be present either because there is no education section (the person did not put any information on LinkedIn, which therefore is not putting an education section in the DOM) or because it is not loaded yet (there is a spinning circle). I want to know which one it is. If it is the second reason (there is a spinning circle), I want to wait. (the section is a div with a class named education-section). The same applies for the experiences

Here is the core of the project for the purpose of this question.

These are 2 functions inside of a class. self.getBrowser() return a WebDriver object. For the sake of clarity and brevity I have cut the non-interesting parts, including code inside the 2 functions, so the arguments which seems to not be used in reality are. I hope the remaining variables are self-explaining.

```<code>def waitForPresenceCondition(self, by, value, sleep = True, check_for_404 = True):
    try:
        condition = EC.visibility_of_element_located((by, value))
        WebDriverWait(self.getBrowser(), self.wait_timeout).until(condition)
    except TimeoutException:
        logging.critical("Timed out waiting for page element. Fatal. Exiting")
        raise
    except:
        logging.error("Unexpected exception waiting for page element. Exiting")
        raise
    else:
        logging.debug("Element found in URL")

# Scrape an organization
def scrape(self, url):
   self.getBrowser().get(url)
   try:
       self.waitForPresenceCondition(By.CLASS_NAME, "pv-profile-wrapper")
   except Error404:
       logging.info("waitForPresenceCondition raised 404 error. Returning False")
       return False
    #INSERT HERE EXPLICIT WAIT FOR THE SPINNING CIRCLES
</code>```

答:
You can update your code like below:

```<code>def waitForPresenceCondition(self, by, value, sleep=True, check_for_404=True, visible=True):
    try:
        if visible:
            condition = EC.visibility_of_element_located((by, value))
        else:
            condition = EC.invisibility_of_element_located((by, value))
        WebDriverWait(self.getBrowser(), self.wait_timeout).until(condition)
</code>```

This should allow you to use your waitForPresenceCondition() with visible=False parameter to wait until div with spinning circles dissapear

Body:
I am using Selenium and its Python bindings to webscrape from LinkedIn for a research project. I webscrape people's profiles.

In LinkedIn, when you load a person profile, the site puts spinning circles until the experiences and the education are fully loaded.
I want Selenium to wait until the spinning circles disappear, in order to get, in the HTML source code, the experience and the education sections.

So my question is: How can I code an explicit wait for the LinkedIn spinning circles?

EDIT: a more precise question would be: How can I get a locator for the spinning circles?
There is no time to do that from the browser development tools. They disappear too fast

EDIT 2: Another point. A person may or may not have an education section. So clicking or otherwise checking for the education section to be present is not a solution. The education section may not be present either because there is no education section (the person did not put any information on LinkedIn, which therefore is not putting an education section in the DOM) or because it is not loaded yet (there is a spinning circle). I want to know which one it is. If it is the second reason (there is a spinning circle), I want to wait. (the section is a div with a class named education-section). The same applies for the experiences

Here is the core of the project for the purpose of this question.

These are 2 functions inside of a class. self.getBrowser() return a WebDriver object. For the sake of clarity and brevity I have cut the non-interesting parts, including code inside the 2 functions, so the arguments which seems to not be used in reality are. I hope the remaining variables are self-explaining.

def waitForPresenceCondition(self, by, value, sleep = True, check_for_404 = True):
    try:
        condition = EC.visibility_of_element_located((by, value))
        WebDriverWait(self.getBrowser(), self.wait_timeout).until(condition)
    except TimeoutException:
        logging.critical("Timed out waiting for page element. Fatal. Exiting")
        raise
    except:
        logging.error("Unexpected exception waiting for page element. Exiting")
        raise
    else:
        logging.debug("Element found in URL")

# Scrape an organization
def scrape(self, url):
   self.getBrowser().get(url)
   try:
       self.waitForPresenceCondition(By.CLASS_NAME, "pv-profile-wrapper")
   except Error404:
       logging.info("waitForPresenceCondition raised 404 error. Returning False")
       return False
    #INSERT HERE EXPLICIT WAIT FOR THE SPINNING CIRCLES

Body:
You can update your code like below:

def waitForPresenceCondition(self, by, value, sleep=True, check_for_404=True, visible=True):
    try:
        if visible:
            condition = EC.visibility_of_element_located((by, value))
        else:
            condition = EC.invisibility_of_element_located((by, value))
        WebDriverWait(self.getBrowser(), self.wait_timeout).until(condition)

This should allow you to use your waitForPresenceCondition() with visible=False parameter to wait until div with spinning circles dissapear


问:
Sending keys using Selenium and headless Chrome
Using headless chrome and selenium I can succesfully send keys to websites on my Mac. When I port the same code to my Linux machine it crashes however. The offending line is the following one:

```<code>driver.find_element_by_xpath('//input[@id="username"]').send_keys(username)
</code>```

And I get the following error message:

```<code>"an X display is required for keycode conversions, consider using Xvfb"
</code>```

Why is this not working on Linux?

答:
This is a bug in chromedriver that is detailed here.

According to the new lead for chrome driver

The issue is in ChromeDriver. As its name implies, the sendKey command sends simulated key strokes to Chrome, and ChromeDriver is responsible for converting the input text string into corresponding keystrokes to send to Chrome. On Linux, ChromeDriver uses X display to do the conversion, and fails when no X display is available.

It has been fixed recently and will be released in v 2.31. Unfortunately the chromium team does not make nightly builds publicly available and there is no official release date yet.

In the meantime you can build your own chromedriver or download a prebuilt binary from a third party... Both a dockerfile and a working binary may be found at this github.

Body:
Using headless chrome and selenium I can succesfully send keys to websites on my Mac. When I port the same code to my Linux machine it crashes however. The offending line is the following one:

driver.find_element_by_xpath('//input[@id="username"]').send_keys(username)

And I get the following error message:

"an X display is required for keycode conversions, consider using Xvfb"

Why is this not working on Linux?


问:
How to remove html tags of data exported to excel on ASP.NET?
I am trying to export a table to excel but I get the data like this:

```<code><a href='filename.aspx?oecl_id=3'>1</a>
<a href='filename.aspx?oecl_id=62'>2</a>
</code>```

Because I am printing the data just like that:

```<code>cell = new HtmlTableCell();
cell.InnerHtml = "<a href='filename.aspx?oecl_id=" + rsCont.Rows[i]["ID"].ToString() + "'>" + rsCont.Rows[i]["PENDING"].ToString() + "</a>";
</code>```

So how can I get just the numbers on excel? In this example 1 and 2.

I am printing the data like this but this just remove the "" at the end of each row:

```<code>        foreach (HtmlTableCell celda in fila.Cells)
        {
            if (celda.InnerHtml.IndexOf("</a>") > 0)
            {
                cell = row.Cells.Add(celda.InnerHtml.Remove(celda.InnerHtml.IndexOf("</a>")));
            }
            else
            {
                cell = row.Cells.Add(celda.InnerHtml);
            }
        }
</code>```

答:
Finally, I just made another hidden table without the links, just with the data, like this:</p>

```<code><table id="table_excel" style="display:none" runat="server">
    <tr>
        <th>Column1</th>
        <th>Column2</th>
        <th>Column3 >50</th>
    </tr>
</table>
</code>```

Body:
I am trying to export a table to excel but I get the data like this:

1
2

Because I am printing the data just like that:

cell = new HtmlTableCell();
cell.InnerHtml = "" + rsCont.Rows[i]["PENDING"].ToString() + "";

So how can I get just the numbers on excel? In this example 1 and 2.

I am printing the data like this but this just remove the "" at the end of each row:

        foreach (HtmlTableCell celda in fila.Cells)
        {
            if (celda.InnerHtml.IndexOf("") > 0)
            {
                cell = row.Cells.Add(celda.InnerHtml.Remove(celda.InnerHtml.IndexOf("")));
            }
            else
            {
                cell = row.Cells.Add(celda.InnerHtml);
            }
        }

Body:
Finally, I just made another hidden table without the links, just with the data, like this:

<table id="table_excel" style="display:none" runat="server">
    <tr>
        <th>Column1</th>
        <th>Column2</th>
        <th>Column3 >50</th>
    </tr>
</table>


问:
Creating a browse button with PyQT5
I want to create a browse button with pyqt5, but I do not get it</p>

```<code>from PyQt5 import QtWidgets,QtCore, QtGui

import test3

class MyWindow(QtWidgets.QMainWindow):

    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.ui = test3.Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton_2.clicked.connect(self.getfiles)

    def getfiles(self):
        fileName = QtGui.QFileDialog.getOpenFileName(self,'Single File','C:\'','*.xlsm')
        self.ui.lineEdit.setText(fileName)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())
</code>```

答:
In your code there are 2 errors:

QFileDialog belongs to QtWidgets

The second is that the getOpenFileName function returns a tuple: (filename, filter), the first element is the filename, and the second is the filter.

For which functions you must change:

```<code>fileName = QtGui.QFileDialog.getOpenFileName(self,'Single File','C:\'','*.xlsm')
</code>```

to:

```<code>fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Single File', QtCore.QDir.rootPath() , '*.xlsm')
</code>```

Title: Creating a browse button with PyQT5

Body:
I want to create a browse button with pyqt5, but I do not get it

from PyQt5 import QtWidgets,QtCore, QtGui

import test3

class MyWindow(QtWidgets.QMainWindow):

    def __init__(self, parent=None):
        QtWidgets.QMainWindow.__init__(self, parent)
        self.ui = test3.Ui_MainWindow()
        self.ui.setupUi(self)

        self.ui.pushButton_2.clicked.connect(self.getfiles)

    def getfiles(self):
        fileName = QtGui.QFileDialog.getOpenFileName(self,'Single File','C:\'','*.xlsm')
        self.ui.lineEdit.setText(fileName)

if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())

Body:
In your code there are 2 errors:

QFileDialog belongs to QtWidgets

The second is that the getOpenFileName function returns a tuple: (filename, filter), the first element is the filename, and the second is the filter.

For which functions you must change:

fileName = QtGui.QFileDialog.getOpenFileName(self,'Single File','C:\'','*.xlsm')

to:

fileName, _ = QtWidgets.QFileDialog.getOpenFileName(self, 'Single File', QtCore.QDir.rootPath() , '*.xlsm')


问:
Can I use Google Analytics on AWS Lambda?
I am trying to embed the google analytics initialization call into an AWS Lambda function. I'm getting the exception ReferenceError: window is not defined which makes sense seeing as there isn't a browser window. Is there a way to initialize the script so I can make ga() calls in AWS Lambda?

Thanks!

答: I think you're using the wrong SDK. That initialisation is for the web app, which is meant to run on the front-end with access to window. Instead, use the Google Analytics Measurement Protocol.


问:
What solution choose for app user data storage in a cloud
We want to make possibility in our program for >1mln users to use their data in a cloud. The data sets are small (about 1-2MB) but the main requirement is that we don't want to have access to their data - desktop program should load data from cloud/server and every user should have his own account but we should'nt have access to raw data of users.

I see such possibilities

make possible to save ie. in Google Drive through their API

pros:

every user has data in their account - we dont have access to it

cons:

not everybody likes google,

user has to authorise access for our program to google (can look risky for users)

we cannot have our logo in user registering and account process (it is Google window and cannot be changed)

crypt all user data with user password and save in our server/Azure/Google Apps

pros:

even if a hacker would break into server he will not use the user data

cons:

users must remember their password - if they loose pass they cannot access data (and they use our program once a year so they could have lost it easily)

some hybrid of these two aproaches? Any ideas are welcome :)

答:
Evernote provides this functionality, they use method #2.

I have to enter my password every time to decrypt it and if I lose my password, the content cannot be recovered, but they clearly explained the usage/risks.

See if this user experience works for you.

https://help.evernote.com/hc/en-us/articles/209005547-How-to-encrypt-content-inside-Evernote


问:
How to write the EL3 registers of ARM
Currently I'm trying to write several system control registers with EL3 privilege for my AArch64 development board.

I put my code in the trusted firmware boot loader (BL31).

Here is my code that I put in the bl31_main of arm-trusted-firmware-source-code:

```<code>asm("MRS    %x[result], SCR_EL3"
    : [result] "=r" (scr)
);

asm("MSR    SCR_EL3, %x[value]"
    :
    : [value] "r"   (scr)
);
</code>```

I can read the values of these registers correctly so I assume my code running with EL3 privilege.

However, for several registers I tested, every time after I write new values to them, their values don't even change.

I cannot come up with what might cause this problem. Any suggestion is welcomed!

Thank you in advanced.

Simon

答:
If you really insist here is a compromise...OUTSIDE of any functions, NOT within a function but in a C file.

```<code>asm(".globl read_SCR_EL3; read_SCR_EL3: mrs x0,SCR_EL3; ret\n");
</code>```

...

```<code>unsigned int read_SCR_EL3 ( void );
</code>```

...

```<code>value=read_SCR_EL3();
</code>```

which is just another way of doing real assembly.

If you want to do inline, AFTER you have real assembly working then figure out how to get that inline like you were trying to do.  Figure out what/if you were doing wrong (which I would have hoped someone here would or will help) (I will add an assembly tag even though this is C/compiler language stuff).

do it inside a simple function that wraps the inline asm and say returns the value from the read.  DISASSEMBLE (vs -S output) the binary, find that function and inspect what the compiler produced and if it would/should work or not...Optimized it should somewhat exactly resemble the simple mrs x0,registername/ret code, maybe do something like add one to the value before returning but after reading to see that it is using/manipulating the right register...

Title: How to write the EL3 registers of ARM

Body:
Currently I'm trying to write several system control registers with EL3 privilege for my AArch64 development board.

I put my code in the trusted firmware boot loader (BL31).

Here is my code that I put in the bl31_main of arm-trusted-firmware-source-code:

asm("MRS    %x[result], SCR_EL3"
    : [result] "=r" (scr)
);

asm("MSR    SCR_EL3, %x[value]"
    :
    : [value] "r"   (scr)
);

I can read the values of these registers correctly so I assume my code running with EL3 privilege.

However, for several registers I tested, every time after I write new values to them, their values don't even change.

I cannot come up with what might cause this problem. Any suggestion is welcomed!

Thank you in advanced.

Simon

Body:
If you really insist here is a compromise...OUTSIDE of any functions, NOT within a function but in a C file.

asm(".globl read_SCR_EL3; read_SCR_EL3: mrs x0,SCR_EL3; ret\n");

...

unsigned int read_SCR_EL3 ( void );

...

value=read_SCR_EL3();

which is just another way of doing real assembly.

If you want to do inline, AFTER you have real assembly working then figure out how to get that inline like you were trying to do.  Figure out what/if you were doing wrong (which I would have hoped someone here would or will help) (I will add an assembly tag even though this is C/compiler language stuff).

do it inside a simple function that wraps the inline asm and say returns the value from the read.  DISASSEMBLE (vs -S output) the binary, find that function and inspect what the compiler produced and if it would/should work or not...Optimized it should somewhat exactly resemble the simple mrs x0,registername/ret code, maybe do something like add one to the value before returning but after reading to see that it is using/manipulating the right register...


问:
OData v4 Client Code Generator
OData v4 Client Code Generator , How developer can generate OData Entity Classes on client side,
Please explain the steps.

Appreciate Help

Thanks

答:
Assuming the OData v4 code generator is installed. If not installed see here

If your endpoint require authentication(You must manual download the metadata)

Retrieve the endpoint metadata using $metadata on your favourite browser  (EX: http://MyCompany.com/ODataV4/$metadata);

Save the the edmx file inside your solution folder;

Add the code generator item on visual studio;

Set the MetadataDocumentUri  to the fullpath of the edmx (EX : c:\Projects\Mysolution\Myproject\metadata.edmx)

Right click the .tt(T4 code generator) file -> Run Custom Tool

If it's a public OData endpoint SEE tutorial

Add the code generator item on visual studio;

Set the MetadataDocumentUri to the URL of the endpoint (EX: http://MyCompany.com/ODataV4)

Right click the .tt(T4 code generator) file -> Run Custom Tool

You should have all entities and necessary methods to use the ODATA endpoint.

Title: OData v4 Client Code Generator


问:
Don't allow to select past date and time in jquery-simple-datetimepicker
I have used jquery-simple-datetimepicker

available here

```<code>https://github.com/mugifly/jquery-simple-datetimepicker
</code>```

my code is

```<code><input name="day_time" id="day_time_input" type="text" value="" />

 jQuery(function () {
         jQuery('#day_time_input').appendDtpicker();
 });
</code>```

now want to prevent user from selecting past dates.

so how do to that?

答:
you want to add futureOnly: true

```<code>$("#div").appendDtpicker({
    futureOnly: true
});
</code>```

Body:
I have used jquery-simple-datetimepicker

available here

https://github.com/mugifly/jquery-simple-datetimepicker

my code is

<input name="day_time" id="day_time_input" type="text" value="" />

 jQuery(function () {
         jQuery('#day_time_input').appendDtpicker();
 });

now want to prevent user from selecting past dates.

so how do to that?

Body:
you want to add futureOnly: true

$("#div").appendDtpicker({
    futureOnly: true
});


问:
Why is the @ sign needed in this macro definition?
In the following when macro:

```<code>(defmacro when (condition &rest body)
  `(if ,condition (progn ,@body)))
</code>```

Why is  there an "at" @ sign?

答:
The @ can also be thought of deconstructing the list and appending it to the list appears in as described in Practical Common Lisp.

`(a ,@(list 1 2) c)
```

<p>is the equivalent of: </p>

```(append (list 'a) (list 1 2) (list 'c))
```

<p>which produces: </p>

```(a 1 2 c)
```

Body:
In the following when macro:

(defmacro when (condition &rest body)
  `(if ,condition (progn ,@body)))

Why is  there an "at" @ sign?

Body:
The @ can also be thought of deconstructing the list and appending it to the list appears in as described in Practical Common Lisp.

`(a ,@(list 1 2) c)

is the equivalent of:

(append (list 'a) (list 1 2) (list 'c))

which produces:

(a 1 2 c)


问:
Official Windows C/C++ Compiler and C Libraries
I've been coding C/C++ in a Linux environment, and that has been a breeze (Open terminal > Vim > code > gcc > done). I'm trying to get into doing the same in Windows, and it hasn't been nearly as easy. I've gotten Vim to run out of terminal, as I do not like IDEs, thus I'm looking for a Windows compiler that I can work with via command-line.

My problem is that I can't find the official Windows compiler for C/C++, Microsoft support was useless, and MSDN keeps pointing me to Visual Studio. There are a plethora of questions here on SO, and the web about compilers for C/C++ on Windows, with suggestions like Dev-C++, but that comes with GCC. Visual Studio supports C/C++, and I would assume that compiler is the official one, but I've had no luck in finding just the compiler. The closest I've gotten is either the Windows SDK or Visual Studio Express 2015.

Additionally, I was told in the Stackoverflow C chat room, that C is no longer a subset of C++, so does that mean I need to find 2 compilers, one for C and one for C++?

I'm also trying to figure out where C/C++ libraries are. On Linux, they're already there. Is that the case with Windows, if not where do I find their C/C++ libraries?

I didn't expect it to be so difficult to get started, nor did I expect to get lost so quickly.

答:
First of all there is no "official" compiler for Windows; the fact that Microsoft produce both development tools and operating-systems is a historical coincidence I won't do into.  There would be all sorts of anti-trust issues if they tried you to force you to use only their tools.  There is an official Windows SDK; and that is only available with Microsoft tools; but that too is not a barrier to Windows API development using other tools.

Visual Studio is the name of Microsoft's IDE that supports a number of development tools and languages.  The C++ compiler component of Visual Studio also supports C compilation (in common with more-or-less all C++ toolchains - that's why you often see the much hated on SO term C/C++ - because most often the toolchain is a C and C++ toolchain - not because there is a language of that name).  The fact that C is no longer an exact subset of C++ is not really an issue.

All compilers, regardless of whether or not they come embedded in some IDE have a command line interface.  Microsoft fully document theirs, so I am not sure why you could not find it: https://msdn.microsoft.com/en-us/library/f35ctcxw.aspx.

To get Microsoft's tools you have to install one edition or another of Visual Studio, but you do not need to use Visual Studio to drive the compiler.  However perhaps the most compelling reason to use Visual Studio is its debugger - by far the best debugger available for any platform (IMO).  There is a command-line debugger CDB, but unless you love whipping yourself with birch twigs or using GDB (much the same thing), then you'll hate it.

Microsoft have long concentrated on C++, and for a long time C was left at the ISO C90 level of compliance; this has changed somewhat in more recent releases and while 2015 is improved, you would do better to use Visual Studio 2017.  There is no longer an express edition of Visual Studio, it has been replaced with the "Community Edition" with slightly less permissive licensing.  https://www.visualstudio.com/downloads/

All that said, you do not have to use Microsoft's compiler to write Windows applications in C.  MinGW (http://www.mingw.org/) is a native Windows GCC based toolchain that instead of using the POSIX dependent GNU C library, uses Microsoft's C runtime (via the DLL's included with Windows), and includes the necessary header files and export libraries to access the Windows API DLLs too.  Since Microsoft no longer licence the official Windows SDK (and the open-source MinGW could hardly use it in any case), the MinGW Windows SDK headers used to lag somewhat, but since Microsoft have more-or-less abandoned the Windows C API in favour of .NET, the API is more or less fossilised.

The advantage of MinGW is that it is the same GNU toolchain you are used to, and includes all expected GNU utilities such as make, gdb and binutils.  It even includes a bash-like shell MSYS (which you do not have to use, but makes porting, configuring and building some open-source projects easier).

Like Visual Studio, Dev-C++ is not a compiler or toolchain.  It is an IDE. It typically uses MinGW as its toolchain.  The same goes for Code::Blocks for example.

One issue with using the command line in Windows for development is that it is not as complete or fully functional a shell as say bash for example.  You may get frustrated with it is you are a bask power-user.