问:
Print model summary in R markdown without running model
I have run a logistic mixed model that took about 3 hours to fit. I saved the model as an object in my global environment, and I want to include the model summary in my R markdown document. However, I don't want knitr to run the model when putting the html together (that would take 3 more hours to run). I just want to print the summary of the model I've already run.

Knitr throws an error saying that the model object isn't in its scope.

How do I get knitr to access the model object I've already created and not re-run the model when compiling the document?

答: First thing to do should be to check your workspace with ls(). If the model is not there, you will need to rerun it. If you do see it, you can just print the summary in the console. When you try to knit your document it will want to run the entire rmd</p>


来源: stackexchange

问:
Pull data using regex and insert into a .csv file
So I am using regex to pull data from a webpage. Done.

Now I am trying to insert this data into a .csv file. No problem right?

So I am having trouble pulling my data from the loops I created to insert into the .csv file. It looks like the best way to conquer this is to create a list, and somehow insert the data into the list and write the data into the csv file. But how can I do that with my current setup?

```<code>import re
import sqlite3 as lite
import mysql.connector
import urllib.request
from bs4 import BeautifulSoup
import csv

#We're pulling info on socks from e-commerce site Aliexpress

url="https://www.aliexpress.com/premium/socks.html?SearchText=socks&ltype=wholesale&d=y&tc=ppc&blanktest=0&initiative_id=SB_20171202125044&origin=y&catId=0&isViewCP=y"

req = urllib.request.urlopen(url)
soup = BeautifulSoup(req, "html.parser")
div = soup.find_all("div", attrs={"class":"item"})

for item in div:
    title_pattern = '<img alt="(.*?)\"'
    comp = re.compile(title_pattern)
    href = re.findall(comp, str(item))
    for x in href:
        print(x)

    price_pattern = 'itemprop="price">(.*?)<'
    comp = re.compile(price_pattern)
    href = re.findall(comp, str(item))
    for x in href:
        print(x)

    seller_pattern = '<a class="store j-p4plog".*?>(.*?)<'
    comp = re.compile(seller_pattern)
    href = re.findall(comp, str(item))
    for x in href:
        print(x)

    orders_pattern = '<em title="Total Orders">.*?<'
    comp = re.compile(orders_pattern)
    href = re.findall(comp, str(item))
    for x in href:
        print(x[32:-1])

    feedback_pattern = '<a class="rate-num j-p4plog".*?>(.*)<'
    comp = re.compile(feedback_pattern)
    href = re.findall(comp, str(item))
    for x in href:
        print(x)

# Creation and insertion of CSV file

# csvfile = "aliexpress.csv"
# csv = open(csvfile, "w")
# columnTitleRow = "Title,Price,Seller,Orders,Feedback,Pair"
# csv.write(columnTitleRow)
#
# for stuff in div:
#     title =
#     price =
#     seller =
#     orders =
#     feedback =
#     row = title + "," + price + "," + seller + "," + orders + "," + feedback +
"," + "\n"
#     csv.write(row)
</code>```

I want to be able to print these lists by their row.

答:
It looks like the best way to conquer this is to create a list, and somehow insert the data into the list and write the data into the csv file. But how can I do that with my current setup?

Yes you're right. Replace your print statements with appends to a list:

```<code>data = []
for item in div:
    title_pattern = '<img alt="(.*?)\"'
    comp = re.compile(title_pattern)
    href = re.findall(comp, str(item))
    for x in href:
        data.append(x)

    price_pattern = 'itemprop="price">(.*?)<'
    comp = re.compile(price_pattern)
    href = re.findall(comp, str(item))
    for x in href:
        data.append(x)
</code>```

And then later

```<code>csv.writerow(data)
</code>```

From what I remember, csv.write takes a list and not a rendered CSV string anyways. That's the whole point, it takes the raw data and escapes it properly and adds the commas for you.

Edit: As explained in the comment, I misremembered the interface to csv writer. writerow takes a list, not write. Updated.

ContentLicense: CC BY-SA 3.0

Body:
So I am using regex to pull data from a webpage. Done.

Now I am trying to insert this data into a .csv file. No problem right?

So I am having trouble pulling my data from the loops I created to insert into the .csv file. It looks like the best way to conquer this is to create a list, and somehow insert the data into the list and write the data into the csv file. But how can I do that with my current setup?

import re
import sqlite3 as lite
import mysql.connector
import urllib.request
from bs4 import BeautifulSoup
import csv

#We're pulling info on socks from e-commerce site Aliexpress

url="https://www.aliexpress.com/premium/socks.html?SearchText=socks&ltype=wholesale&d=y&tc=ppc&blanktest=0&initiative_id=SB_20171202125044&origin=y&catId=0&isViewCP=y"

req = urllib.request.urlopen(url)
soup = BeautifulSoup(req, "html.parser")
div = soup.find_all("div", attrs={"class":"item"})

for item in div:
    title_pattern = '(.*?)<'
    comp = re.compile(price_pattern)
    href = re.findall(comp, str(item))
    for x in href:
        print(x)

    seller_pattern = '(.*?)<'
    comp = re.compile(seller_pattern)
    href = re.findall(comp, str(item))
    for x in href:
        print(x)

    orders_pattern = '.*?<'
    comp = re.compile(orders_pattern)
    href = re.findall(comp, str(item))
    for x in href:
        print(x[32:-1])

    feedback_pattern = '(.*)<'
    comp = re.compile(feedback_pattern)
    href = re.findall(comp, str(item))
    for x in href:
        print(x)

# Creation and insertion of CSV file

# csvfile = "aliexpress.csv"
# csv = open(csvfile, "w")
# columnTitleRow = "Title,Price,Seller,Orders,Feedback,Pair"
# csv.write(columnTitleRow)
#
# for stuff in div:
#     title =
#     price =
#     seller =
#     orders =
#     feedback =
#     row = title + "," + price + "," + seller + "," + orders + "," + feedback +
"," + "\n"
#     csv.write(row)

I want to be able to print these lists by their row.

Body:
It looks like the best way to conquer this is to create a list, and somehow insert the data into the list and write the data into the csv file. But how can I do that with my current setup?

Yes you're right. Replace your print statements with appends to a list:

data = []
for item in div:
    title_pattern = '<img alt="(.*?)\"'
    comp = re.compile(title_pattern)
    href = re.findall(comp, str(item))
    for x in href:
        data.append(x)

    price_pattern = 'itemprop="price">(.*?)<'
    comp = re.compile(price_pattern)
    href = re.findall(comp, str(item))
    for x in href:
        data.append(x)

And then later

csv.writerow(data)

From what I remember, csv.write takes a list and not a rendered CSV string anyways. That's the whole point, it takes the raw data and escapes it properly and adds the commas for you.

Edit: As explained in the comment, I misremembered the interface to csv writer. writerow takes a list, not write. Updated.


问:
Get JS Value From First PHP Page and Run on Second Page
I created a 3-step form.
the form is aimed to determine the price according to the number of employees entered.
the user is entering the number of employees in the first step.
JavaScript calculates the price according to this value.
The index1.php form looks like this:

```<code><form id="empnum" class="form-horizontal" method="GET" action="index2.php">
  <label class="control-label">employee number</label>
   <div class="controls">
  <input type="text" class="span6 " id="employee_number" name="employee_number" required>
     </div>
 <button type="submit" class="btn btn-success">Calculate</button>
  </form>
</code>```

The js code is shown below;

```<code>function calculate(){
$.ajaxSettings.cache = false;
var employee_number = $("#employee_number").val();

function time(s) {

    if(s>60){
        hour=Math.floor(s/60);
        mnts=s-(hour*60);
        if(mnts==0){result= hour +' hour';}else{result= hour +' hour '+ mnts + ' mnts' ;}
    }
    else{result= s +' mnts';}
    return result;
}

if (employee_number.length > 0)
{
    // -------------------
    a1=(employee_number*5)
    a2=(employee_number*10)
    a3=(employee_number*15)
    $(".a1").html(time(a1)+" /month");
    $(".a2").html(time(a2)+" /month");
    $(".a3").html(time(a3)+" /month");

    // -------------------

    a1=(employee_number*10)
    a2=(employee_number*20)
    a3=(employee_number*40)
    $(".b1").html(time(a1)+" /month");
    $(".b2").html(time(a2)+" /month");
    $(".b3").html(time(a3)+" /month");

    // -------------------

    if(employee_number>9 && employee_number<50){

        $(".c3").html(time(employee_number*10)+" /month");
    }
    else if(employee_number>49 && employee_number<250){

        $(".c3").html(time(employee_number*15)+" /month");
    }
    else if(employee_number>249){

        $(".c3").html(time(employee_number*20)+" /month");
    }
    else
    {
        $(".c3").html("-");
    }
}
}
</code>```

html code which i added on index2.php

```<code><table border="0" cellpadding="0" cellspacing="0" class="tb1">
    <tr>
        <th width="25%">danger level</th>
        <th width="25%" class="bg1">doctor working time</th>
        <th width="25%" class="bg2">expert's working time</th>
        <th width="25%" class="bg3">duration of other staff</th>
    </tr>
    <tr>
        <td><b>Less dangerous</b></td>
        <td class="a1">0</td>
        <td class="b1">0</td>
        <td class="c1">-</td>
    </tr>
    <tr>
        <td><b>dangerous</b></td>
        <td class="a2">0</td>
        <td class="b2">0</td>
        <td class="c2">-</td>
    </tr>
    <tr>
        <td><b>very dangerous</b></td>
        <td class="a3">0</td>
        <td class="b3">0</td>
        <td class="c3">0</td>
    </tr>
</table>
</code>```

I also added jquery and js tags and  onClick="calculate(); (inside button), but did not work again

How can I run JavaScript on the second page(index2.php) according to the value entered in the first page(index1.php)?

Note:It works fine on one page. But i have to make it dynamic with php(two page) because I will do attachments in the future.

答:
When you submit the form it will load index2.php and the value of employee_number is in

```<code>$_GET['employee_number'];
</code>```

if you want to keep your urls clean you can change the method to post and the vars will be in the $_POST array.

Body:
I created a 3-step form.
the form is aimed to determine the price according to the number of employees entered.
the user is entering the number of employees in the first step.
JavaScript calculates the price according to this value.
The index1.php form looks like this:

<form id="empnum" class="form-horizontal" method="GET" action="index2.php">
  employee number

  <input type="text" class="span6 " id="employee_number" name="employee_number" required>

 <button type="submit" class="btn btn-success">Calculate</button>
  </form>

The js code is shown below;

function calculate(){
$.ajaxSettings.cache = false;
var employee_number = $("#employee_number").val();

function time(s) {

    if(s>60){
        hour=Math.floor(s/60);
        mnts=s-(hour*60);
        if(mnts==0){result= hour +' hour';}else{result= hour +' hour '+ mnts + ' mnts' ;}
    }
    else{result= s +' mnts';}
    return result;
}

if (employee_number.length > 0)
{
    // -------------------
    a1=(employee_number*5)
    a2=(employee_number*10)
    a3=(employee_number*15)
    $(".a1").html(time(a1)+" /month");
    $(".a2").html(time(a2)+" /month");
    $(".a3").html(time(a3)+" /month");

    // -------------------

    a1=(employee_number*10)
    a2=(employee_number*20)
    a3=(employee_number*40)
    $(".b1").html(time(a1)+" /month");
    $(".b2").html(time(a2)+" /month");
    $(".b3").html(time(a3)+" /month");

    // -------------------

    if(employee_number>9 && employee_number<50){

        $(".c3").html(time(employee_number*10)+" /month");
    }
    else if(employee_number>49 && employee_number<250){

        $(".c3").html(time(employee_number*15)+" /month");
    }
    else if(employee_number>249){

        $(".c3").html(time(employee_number*20)+" /month");
    }
    else
    {
        $(".c3").html("-");
    }
}
}

html code which i added on index2.php

        danger level
        doctor working time
        expert's working time
        duration of other staff

        Less dangerous
        0
        0
        -

        dangerous
        0
        0
        -

        very dangerous
        0
        0
        0

I also added jquery and js tags and  onClick="calculate(); (inside button), but did not work again

How can I run JavaScript on the second page(index2.php) according to the value entered in the first page(index1.php)?

Note:It works fine on one page. But i have to make it dynamic with php(two page) because I will do attachments in the future.

Body:
When you submit the form it will load index2.php and the value of employee_number is in

$_GET['employee_number'];

if you want to keep your urls clean you can change the method to post and the vars will be in the $_POST array.


问:
Can't install redux-logger
I'm trying to install redux-logger by following actions:

```<code>npm install --save redux-logger
</code>```

after that I added import logger to the code:

```<code>import logger from 'redux-logger'
</code>```

and then I included logger to the applyMiddleware:

```<code>const createStoreWithMiddleware = applyMiddleware(thunk, logger)(createStore)
const reducer = combineReducers(reducers)
const store = createStoreWithMiddleware(reducer, undefined, autoRehydrate())
persistStore(store, persistConfig)
</code>```

But I get an error that it's not installed.
Does anybody know why it happens?

答:
Strangely, i did an

```<code>npm install 'redux-logger'
</code>```

and got the above error. Curious, i visited the redux-logger npm homepage and noticed the latest version was 3.0.6, but the npm default install pulled down ^2.10.2. I solved this by manually specifying 3.0.6 in my package.json and it fixed the issue after an npm install

Title: Can't install redux-logger

Body:
I'm trying to install redux-logger by following actions:

npm install --save redux-logger

after that I added import logger to the code:

import logger from 'redux-logger'

and then I included logger to the applyMiddleware:

const createStoreWithMiddleware = applyMiddleware(thunk, logger)(createStore)
const reducer = combineReducers(reducers)
const store = createStoreWithMiddleware(reducer, undefined, autoRehydrate())
persistStore(store, persistConfig)

But I get an error that it's not installed.
Does anybody know why it happens?

Body:
Strangely, i did an

npm install 'redux-logger'

and got the above error. Curious, i visited the redux-logger npm homepage and noticed the latest version was 3.0.6, but the npm default install pulled down ^2.10.2. I solved this by manually specifying 3.0.6 in my package.json and it fixed the issue after an npm install


问:
Adding zero to my complex number class
I'm creating my own complex number class (not using Python's built in one) and I'm running into a problem when I try to add zero to my complex number. For reference this is the error:

```<code>Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "display.py", line 25, in __init__
t.color(mandelbrot(c).getColor())
File "C:\Users\Joe\Desktop\Python\mandelbrot.py", line 10, in __init__
z = z*z + self.__starting_value
TypeError: unsupported operand type(s) for +: 'int' and 'complex'
</code>```

Where self.__starting_value is the complex number.

The addition definition goes as follows:

```<code>class complex:
    def __init__(self, a = 0, b = 0):
        self.__real = float(a)
        self.__imag = float(b)
    def __add__(self, other):
        return complex(self.__real + other.__real, self.__imag + other.__imag)
</code>```

The solution should be simple enough but I am still learning Python and could use the help.

答: __add__ is for addition when the left-hand-side operand is of the type you're writing. When Python fails to call the int __add__ method, it tries __radd__. If you define __radd__ (with the same behavior), you'll get the result you want.

Title: Adding zero to my complex number class

Body:
I'm creating my own complex number class (not using Python's built in one) and I'm running into a problem when I try to add zero to my complex number. For reference this is the error:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "display.py", line 25, in __init__
t.color(mandelbrot(c).getColor())
File "C:\Users\Joe\Desktop\Python\mandelbrot.py", line 10, in __init__
z = z*z + self.__starting_value
TypeError: unsupported operand type(s) for +: 'int' and 'complex'

Where self.__starting_value is the complex number.

The addition definition goes as follows:

class complex:
    def __init__(self, a = 0, b = 0):
        self.__real = float(a)
        self.__imag = float(b)
    def __add__(self, other):
        return complex(self.__real + other.__real, self.__imag + other.__imag)

The solution should be simple enough but I am still learning Python and could use the help.


问:
adjusting css font size by vh and vw
So I have text that I want to automatically resize based on the size of its container. However if I use something like

```<code>font-size: 5vw;
</code>```

it looks good, but when I shrink the page the height starts getting way too small

Is there anyway that I can resize the text based on both vh and vw so, for example, if I just decrease the width of the page the height doesn't decrease too?

like if I only decrease the width of the page, I want the height of the text to stay the same and vice versa.

Basically I want the text to always fit inside the box perfectly and have same proportions no matter what the size of the page/container is?

Is there anyway to base font size on both vh and vw like this in CSS/HTML?

答:
You can look into the vmin and vmax units.

While 1vw will return 1% of the viewport width and 1vh will return 1% of the viewport height, 1vmin will return 1% of the smallest viewport dimension, be it either the viewport width (vw) or its height (vh). Equally 1vmax will return 1% of whichever viewport dimension is the largest.

In order to have a whole container, including its text, to retain its aspect ratio you will have to apply the same kind of unit to both the container dimensions and its font size.

See the following example in full page mode and play around with the window width and height:

p {
  width: 80vmin;
  font-size: 6vmin;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><p>Try resizing both the width and height of the output frame. The <p> element and its contents will both respond to whichever dimension is the smallest.</p></code>```

Note

Internet Explorer 11 and Edge 12 does not support the vmax unit. More on browser support here.

Title: adjusting css font size by vh and vw

Body:
So I have text that I want to automatically resize based on the size of its container. However if I use something like

font-size: 5vw;

it looks good, but when I shrink the page the height starts getting way too small

Is there anyway that I can resize the text based on both vh and vw so, for example, if I just decrease the width of the page the height doesn't decrease too?

like if I only decrease the width of the page, I want the height of the text to stay the same and vice versa.

Basically I want the text to always fit inside the box perfectly and have same proportions no matter what the size of the page/container is?

Is there anyway to base font size on both vh and vw like this in CSS/HTML?

Body:
You can look into the vmin and vmax units.

While 1vw will return 1% of the viewport width and 1vh will return 1% of the viewport height, 1vmin will return 1% of the smallest viewport dimension, be it either the viewport width (vw) or its height (vh). Equally 1vmax will return 1% of whichever viewport dimension is the largest.

In order to have a whole container, including its text, to retain its aspect ratio you will have to apply the same kind of unit to both the container dimensions and its font size.

See the following example in full page mode and play around with the window width and height:

p {
  width: 80vmin;
  font-size: 6vmin;
}

<p>Try resizing both the width and height of the output frame. The &lt;p&gt; element and its contents will both respond to whichever dimension is the smallest.</p>

Note

Internet Explorer 11 and Edge 12 does not support the vmax unit. More on browser support here.


答:
Put a hidden input where you put your calculated value

document.getElementById('price').value = result```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="hidden" name="price"></code>```

And you have the price in your php by the name price

Title: Get JS Value From First PHP Page and Run on Second Page

Body:
Put a hidden input where you put your calculated value

document.getElementById('price').value = result

<input type="hidden" name="price">

And you have the price in your php by the name price


问:
Graph database and Social Network Analysis metrics
Just wanted to ask whether graph databases like OrientDB, Neo4j and Titan are capable of computing Social Network Analysis (SNA) metrics?

I have heard that Neo4j can be used with JUNG but I don't understand where are the benefits of using graph database come in if JUNG is the only solution.

Any clarification on how metrics such as network centrality, clustering coefficient and graph components are computed would be much appreciated!

Sample code in Gremlin or Cypher would be most welcomed!

答:
Although the question is already dated, here is my bit: it is possible to link Neo4j with Gephi via the Graph Streaming plugin of Gephi (it uses the GraphStreaming API).
The whole process is explained on a tutorial that was submitted to The Programming Historian.</p>


问:
Display json data from a javascript file to html list
I have the following javascript/json array and would like to display it as an html list but im stuck:

```<code>    var myFunction = function() {
        var myList = [
            {
                'name': 'Emely',
            },
            {
                'name': 'John',
            },
            {
                'name': 'Stewart',
            }
        ];
    var dataObject = JSON.parse(myList);
    var listItemString = $('#listItem').html();
    dataObject.forEach(buildNewList);
    function buildNewList(item, index) {
        var listItem = $('<li>' + listItemString + '</li>');
        var listItemTitle = $('.title', listItem);
        listItemTitle.html(item.name);
        $('#mydatalist').append(listItem);
    }
  };
</code>```

i am not sure what im doing wrong.Ive been trying for three hours now.

my html is as follows:

```<code><div id="listItem">
  <div class="row1">
    <div class="title"></div>
  </div>
</div>
</code>```

but my list is still not displaying

答:
JSON is (J)ava(S)cript (O)bject (N)otation

It is a way to represent a Javascript object as a string, primarily so it can be stored or transmitted.

JSON.stringify(object) will turn a JS object into a string, while JSON.parse(str) will turn a string into a JS object.

In your case, you have an Array of Objects assigned to the variable myList — it is an Object (an array is an object), not a JSON string, so it doesn't need to be parsed as you are doing with var dataObject = JSON.parse(myList); ... it is already an object. var dataObject = myList would get you the object you want, but that's pointless because you could use myList directly.

You would need to parse that data if you had received it as a string through an AJAX call, but you are working directly in Javascript.

There are other problems with your code, as others have pointed out -- e.g. you have your myFunction but you never call it (as EJK commented) so none of your code will ever be executed.

You also reference '#mydatalist' but you have no HTML element with that ID, so your append(...) does nothing.

Body:
I have the following javascript/json array and would like to display it as an html list but im stuck:

    var myFunction = function() {
        var myList = [
            {
                'name': 'Emely',
            },
            {
                'name': 'John',
            },
            {
                'name': 'Stewart',
            }
        ];
    var dataObject = JSON.parse(myList);
    var listItemString = $('#listItem').html();
    dataObject.forEach(buildNewList);
    function buildNewList(item, index) {
        var listItem = $('
' + listItemString + '
');
        var listItemTitle = $('.title', listItem);
        listItemTitle.html(item.name);
        $('#mydatalist').append(listItem);
    }
  };

i am not sure what im doing wrong.Ive been trying for three hours now.

my html is as follows:

but my list is still not displaying


问:
Solr/Lucene: Possible to have Strings tokenized?
I am indexing film titles. Currently I have two fields.

One is a the pre-configured textgen and one is a string, which I altered to be case insensitive.

I use the copyfield directives to index the same data in both fields.

I am using dismax request handler.

I do this to be able to find "lord rings" in the title "the lord of the rings" but as well boost exact matches. So for example "lord or the rings" scores higher than "rings of the lord" but both is found.

Now I played with string fields which seems to be necessary to have exact matching.

But I just dont get any results. I only get results if I search for the exact string. Not even spaces are working...

Is it even possible to have a String customized

What field configuraition / analyzation would you recommend for this use case?

答:
Have a look at the example solr/conf/schema.xml, there are a lot of different types of fields, well documented.

For your type of search you probably need a simple tokenised lower-cased field with positions, such as:

```<code><fieldType name="text" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StandardFilterFactory"/>
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
</fieldType>
</code>```

The ranking should be pretty good already with this.

For standard text search one uses "stopwords" and "stemming", to improve the ranking (as in field below) but for searching titles i would probably not do it:

```<code> <fieldType name="text" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StandardFilterFactory"/>
        <filter class="solr.ASCIIFoldingFilterFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.StopFilterFactory"
                ignoreCase="true"
                words="stopwords_spanish.txt"
                enablePositionIncrements="true"
                />
        <filter class="solr.SnowballPorterFilterFactory" language="English">
      </analyzer>
      <analyzer type="query">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StandardFilterFactory"/>
        <filter class="solr.ASCIIFoldingFilterFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.StopFilterFactory"
                ignoreCase="true"
                words="stopwords.txt"
                enablePositionIncrements="true"
                />
        <filter class="solr.SnowballPorterFilterFactory" language="English"/\
>
      </analyzer>
    </fieldType>
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Have a look at the example solr/conf/schema.xml, there are a lot of different types of fields, well documented.

For your type of search you probably need a simple tokenised lower-cased field with positions, such as:

<fieldType name="text" class="solr.TextField" positionIncrementGap="100">
    <analyzer type="index">
      <tokenizer class="solr.StandardTokenizerFactory"/>
      <filter class="solr.StandardFilterFactory"/>
      <filter class="solr.ASCIIFoldingFilterFactory"/>
      <filter class="solr.LowerCaseFilterFactory"/>
    </analyzer>
</fieldType>

The ranking should be pretty good already with this.

For standard text search one uses "stopwords" and "stemming", to improve the ranking (as in field below) but for searching titles i would probably not do it:

 <fieldType name="text" class="solr.TextField" positionIncrementGap="100">
      <analyzer type="index">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StandardFilterFactory"/>
        <filter class="solr.ASCIIFoldingFilterFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.StopFilterFactory"
                ignoreCase="true"
                words="stopwords_spanish.txt"
                enablePositionIncrements="true"
                />
        <filter class="solr.SnowballPorterFilterFactory" language="English">
      </analyzer>
      <analyzer type="query">
        <tokenizer class="solr.StandardTokenizerFactory"/>
        <filter class="solr.StandardFilterFactory"/>
        <filter class="solr.ASCIIFoldingFilterFactory"/>
        <filter class="solr.LowerCaseFilterFactory"/>
        <filter class="solr.StopFilterFactory"
                ignoreCase="true"
                words="stopwords.txt"
                enablePositionIncrements="true"
                />
        <filter class="solr.SnowballPorterFilterFactory" language="English"/\
>
      </analyzer>
    </fieldType>


问:
How to handle error in mongoose in Node.js app
I'm developing a node.js app with express and mongoDb and mongoose. The app saves the user in the code below with no problem, but in this code it always console error even if the process is success, and the user is saved.

I'm trying to make flash messages and validation but I can't go ahead with this problem.

Also, I'm not sure if I'm using the right post method or not(should I use   res.status(500).send('error')) inside the post?

```<code> newUser.save().then(function (error) {
  if (error) {
    console.log('error') // always prints this
  } else {
    console.log('success')
  }
})
</code>```

the full code

```<code>var User = require('../models/User')
var router = require('express').Router()

 router.route('/user/signup')
.get(function (request, response) {
  // render the form
  response.render('user/signup')
 })
 .post(function (request, response) {
  var username = request.body.name
  var password = request.body.password
  var newUser = new User({
  name: username,
  password: password
  })
  newUser.save().then(function (error) {
    if (error) {
    console.log('error')
  } else {
    console.log('success')
  }
 })
 response.redirect('/')
 })
</code>```

答:
I think you want to pass the function directly to save() as the callback

```<code>newUser.save(function (err, user) {
      if (err) ..
    })
</code>```

With the approach you're currently taking, I think you'll want to use catch

```<code>newUser.save().then(function (user) }})
   .catch((err) => ...);
</code>```

Source: mongoose docs

Body:
I'm developing a node.js app with express and mongoDb and mongoose. The app saves the user in the code below with no problem, but in this code it always console error even if the process is success, and the user is saved.

I'm trying to make flash messages and validation but I can't go ahead with this problem.

Also, I'm not sure if I'm using the right post method or not(should I use   res.status(500).send('error')) inside the post?

 newUser.save().then(function (error) {
  if (error) {
    console.log('error') // always prints this
  } else {
    console.log('success')
  }
})

the full code

var User = require('../models/User')
var router = require('express').Router()

 router.route('/user/signup')
.get(function (request, response) {
  // render the form
  response.render('user/signup')
 })
 .post(function (request, response) {
  var username = request.body.name
  var password = request.body.password
  var newUser = new User({
  name: username,
  password: password
  })
  newUser.save().then(function (error) {
    if (error) {
    console.log('error')
  } else {
    console.log('success')
  }
 })
 response.redirect('/')
 })

Body:
I think you want to pass the function directly to save() as the callback

newUser.save(function (err, user) {
      if (err) ..
    })

With the approach you're currently taking, I think you'll want to use catch

newUser.save().then(function (user) }})
   .catch((err) => ...);

Source: mongoose docs


答:
Two problems:

You are only handling addition of a complex object to a complex object, when you want to also be able to handle complex object + int.

When adding in this order (int + custom type), you need to add a reflected addition method (__radd__)

```<code>class complex:
    def __init__(self, a = 0, b = 0):
        self.__real = float(a)
        self.__imag = float(b)
    def __add__(self, other):
        if isinstance(other, complex):
            return complex(self.__real + other.__real, self.__imag + other.__imag)
        else:
            return complex(self.__real + other, self.__imag)
    def __radd__(self, other):
        return self + other
</code>```

N.B.: It is considered bad style to shadow built-in names (like complex).

Title: Adding zero to my complex number class

Body:
Two problems:

You are only handling addition of a complex object to a complex object, when you want to also be able to handle complex object + int.

When adding in this order (int + custom type), you need to add a reflected addition method (__radd__)

class complex:
    def __init__(self, a = 0, b = 0):
        self.__real = float(a)
        self.__imag = float(b)
    def __add__(self, other):
        if isinstance(other, complex):
            return complex(self.__real + other.__real, self.__imag + other.__imag)
        else:
            return complex(self.__real + other, self.__imag)
    def __radd__(self, other):
        return self + other

N.B.: It is considered bad style to shadow built-in names (like complex).


问:
Getting values from related tables
I'm trying to find a route in which there are 2 cities. I have tables "route", "city" and "route_city". On input i have two city ids(from and to).
My tables:

city

```<code>id name
1  Kiev
2  Rome
</code>```

route

```<code>id name
1  Kiev-Rome
2  Rome-Kiev
</code>```

route_city

```<code>id route_id city_id sort
1         1        1   1
2         1        2   2
3         2        2   1
4         2        1   2
</code>```

I tried:

```<code>SELECT `route_id` FROM `route_city` WHERE (`route_city`.`city_id` IN ('1', '2')) GROUP BY `route_city`.`route_id`
</code>```

If i have from=Kiev and to=Rome, i get both routes.

1)How i can get only one route?

2)And how i can create this query in Yii2 Framework with ActiveRecord?

答:
is the sort column your code for from and to? Like this: if sort=1, it's from and if sort=2, it's to?

If yes, to do from=Kiev and to=Rome you can do :

```<code>SELECT `route_id` FROM `route_city` WHERE (`route_city`.`city_id` IN ('1', '2')) AND `route_city`.`sort`=1 GROUP BY `route_city`.`route_id`
</code>```

For Yii I can't be of any help !

Title: Getting values from related tables

Body:
I'm trying to find a route in which there are 2 cities. I have tables "route", "city" and "route_city". On input i have two city ids(from and to).
My tables:

city

id name
1  Kiev
2  Rome

route

id name
1  Kiev-Rome
2  Rome-Kiev

route_city

id route_id city_id sort
1         1        1   1
2         1        2   2
3         2        2   1
4         2        1   2

I tried:

SELECT `route_id` FROM `route_city` WHERE (`route_city`.`city_id` IN ('1', '2')) GROUP BY `route_city`.`route_id`

If i have from=Kiev and to=Rome, i get both routes.

1)How i can get only one route?

2)And how i can create this query in Yii2 Framework with ActiveRecord?

Body:
is the sort column your code for from and to? Like this: if sort=1, it's from and if sort=2, it's to?

If yes, to do from=Kiev and to=Rome you can do :

SELECT `route_id` FROM `route_city` WHERE (`route_city`.`city_id` IN ('1', '2')) AND `route_city`.`sort`=1 GROUP BY `route_city`.`route_id`

For Yii I can't be of any help !


问:
How to get value from a multi-array?
I want to get a specific value of a variable from multi array, if the condition matches.

When I print my array:

```<code>print_r($myarray);
</code>```

gives array like this:

```<code>Array
(
  [0] => Array
   (
     [id] => 21 //check for this value
     [customer_id] => 12456 //get this value
     [date] => 12-06-2017
   )
  [1] => Array
   (
     [id] => 15
     [customer_id] => 12541
     [date] => 12-06-2017
   )
  [2] => Array
   (
     [id] => 12
     [customer_id] => 25415
     [date] => 12-06-2017
   )
)
</code>```

I am trying to get customer number if the ID matches with 21

```<code>foreach ($myarray as $array){
  if($array[][id] == "21"){ //this is where I'm making mistake
    $cust_id = $myarray[]['customer_id'];
    return $cust_id;
  }
}
</code>```

答:
```<code>foreach ($myarray as $array){
  if($array["id"] == 21){
    $cust_id = $array['customer_id'];
    return $cust_id;
  }
}
</code>```

Title: How to get value from a multi-array?

Body:
I want to get a specific value of a variable from multi array, if the condition matches.

When I print my array:

print_r($myarray);

gives array like this:

Array
(
  [0] => Array
   (
     [id] => 21 //check for this value
     [customer_id] => 12456 //get this value
     [date] => 12-06-2017
   )
  [1] => Array
   (
     [id] => 15
     [customer_id] => 12541
     [date] => 12-06-2017
   )
  [2] => Array
   (
     [id] => 12
     [customer_id] => 25415
     [date] => 12-06-2017
   )
)

I am trying to get customer number if the ID matches with 21

foreach ($myarray as $array){
  if($array[][id] == "21"){ //this is where I'm making mistake
    $cust_id = $myarray[]['customer_id'];
    return $cust_id;
  }
}


问:
Visual Studio 2015 - Prerelease software. This license has expired
I have installed Visual Studio 2015 with an .ISO that works for a colleague. On opening the application I've signed into my MSDN account which has an Active subscription.

However I'm presented with the following splash screen:

License: Prerelease software This license has expired.

I've no option but to close at this point (pressing the Close button closes Visual Studio completely) – even though I can generate a license key via MSDN I have no way of entering it.

Any ideas?

答:
[EDIT]:

This is the only thing I eventually got to work having this problem with Visual Studio Community 2017!

https://www.laptopmag.com/articles/reset-windows-10-pc

References:

Visual Studio 2017 - Prerelease software. This license has expired

Visual Studio Community Support Ticket

Below is the original post of stuff that DIDN'T end up working for me:

-

I had the EXACT same problem with Visual Studio 2017!

"Prerelease software. This license has expired"

I tried everything above AND a bunch of things you'll probably find BELOW this search result in Google (ie. people at Microsoft can't seem to give a fix either!). DO NOT do what I did and attempt to uninstall all your VS related apps, and .NET & Visual C++ distributions, and then repair/reinstall VS, etc! NOT NEEDED (like some people have suggested) and a complete waste of time!

FIX ---
Remove the offending product key!

Open register editor

Start Menu -> Search regedit -> Right-Click -> Run as Administrator

Navigate to HKEY_CLASSES_ROOT\Licenses\5C505A59-E312-4B89-9508-E162F8150517 and delete it

Back it up first, if you want...

Execute a repair installation of VS 2017

BOOM! Jump for joy! I was stumped by this for a few days setting up an old machine as a new dev machine... apparently, I had an out-dated license in there! Hope that helps anyone else that shows up here!

[Edit] Seems to have reverted after restarting the machine and now the problem persists...

Reference: How to change Visual Studio 2017 License Key?

Tried theses too:

Devenv.exe /ResetSettings from this post on MSDN Forums

Ref: License expired after installation Microsoft Visual Studio 2015 community

Offline install (replaces iso install method from 2015): https://learn.microsoft.com/en-us/visualstudio/install/install-vs-inconsistent-quality-network


问:
Visual Studio 2015 loop performance degradation when storing pointers in struct
I found that the following loop

```<code>std::vector<int> x,y,z;
...
unsigned int res=0;
auto p=x.data();
auto q=y.data();
auto r=z.data();
for(unsigned int i=0;i<N;++i){
  res+=*p++ +*q++ +*r++;
}
</code>```

runs almost twice as fast as this one, which merely packs the pointers in a struct:

```<code>struct pdata{int *px,*py,*pz;};

unsigned int res=0;
pdata d{x.data(),y.data(),z.data()};
for(unsigned int i=0;i<N;++i){
  res+=*d.px++ +*d.py++ +*d.pz++;
}
return res;
</code>```

Is this a known performance issue? Please find below complete program and performance measurements for Visual C++ 2015 in 32-bit (x86) release mode (default settings), Windows 7 64-bit, Intel Core i5-2520M @2.5GHz:

```<code>#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <numeric>

std::chrono::high_resolution_clock::time_point measure_start,measure_pause;

template<typename F>
double measure(F f)
{
  using namespace std::chrono;

  static const int              num_trials=10;
  static const milliseconds     min_time_per_trial(200);
  std::array<double,num_trials> trials;
  volatile decltype(f())        res; /* to avoid optimizing f() away */

  for(int i=0;i<num_trials;++i){
    int                               runs=0;
    high_resolution_clock::time_point t2;

    measure_start=high_resolution_clock::now();
    do{
      res=f();
      ++runs;
      t2=high_resolution_clock::now();
    }while(t2-measure_start<min_time_per_trial);
    trials[i]=duration_cast<duration<double>>(t2-measure_start).count()/runs;
  }
  (void)res; /* var not used warn */

  std::sort(trials.begin(),trials.end());
  return std::accumulate(
    trials.begin()+2,trials.end()-2,0.0)/(trials.size()-4);
}

template<typename F>
double measure(unsigned int n,F f)
{
  double t=measure(f);
  return (t/n)*10E9;
}

#include <iostream>
#include <vector>

int main()
{
  static const unsigned int N=100000;
  std::vector<int> x(N),y(N),z(N);

  for(int i=0;i<N;i++){
    x[i]=i;
    y[i]=i+1;
    z[i]=i+2;
  }

  std::cout<<measure(N,[&]{
    unsigned int res=0;
    auto p=x.data();
    auto q=y.data();
    auto r=z.data();
    for(unsigned int i=0;i<N;++i){
      res+=*p++ +*q++ +*r++;
    }
    return res;
  })<<",";

  std::cout<<measure(N,[&]{
    struct pdata{int *px,*py,*pz;};

    unsigned int res=0;
    pdata d{x.data(),y.data(),z.data()};
    for(unsigned int i=0;i<N;++i){
      res+=*d.px++ +*d.py++ +*d.pz++;
    }
    return res;
  })<<"\n";
}
</code>```

Output

```<code>4.24541,7.44588
</code>```

Thank you,

答:
Fascinating. This seems to be indeed a performance/optimization issue.
Loop #1 uses MMX opcodes:

```<code>for(unsigned int i = 0; i < N; ++i) {
res += *p++ + *q++ + *r++;
00C812C0  lea         eax,[eax+20h]
00C812C3  lea         esi,[esi+20h]
00C812C6  lea         edx,[edx+20h]
00C812C9  movups      xmm0,xmmword ptr [esi-20h]
00C812CD  movups      xmm1,xmmword ptr [eax-20h]
00C812D1  paddd       xmm1,xmm0
00C812D5  movups      xmm0,xmmword ptr [edx-20h]
00C812D9  paddd       xmm1,xmm0
00C812DD  paddd       xmm3,xmm1
00C812E1  movups      xmm0,xmmword ptr [esi-10h]
00C812E5  movups      xmm1,xmmword ptr [eax-10h]
00C812E9  paddd       xmm1,xmm0
00C812ED  movups      xmm0,xmmword ptr [edx-10h]
00C812F1  paddd       xmm1,xmm0
00C812F5  paddd       xmm2,xmm1
00C812F9  sub         ecx,1
00C812FC  jne
</code>```

while Loop #2 uses standard opcodes:

```<code>for(unsigned int i = 0; i < N; ++i) {
res += *d.px++ + *d.py++ + *d.pz++;
00C81340  mov         eax,dword ptr [edi]
00C81342  lea         ecx,[ecx+14h]
00C81345  add         eax,dword ptr [esi]
00C81347  lea         edi,[edi+14h]
00C8134A  add         eax,dword ptr [ecx-14h]
00C8134D  lea         esi,[esi+14h]
00C81350  mov         edx,dword ptr [edi-4]
00C81353  add         ebx,eax
00C81355  mov         eax,dword ptr [edi-10h]
00C81358  add         eax,dword ptr [esi-10h]
00C8135B  add         eax,dword ptr [ecx-10h]
00C8135E  add         edx,dword ptr [esi-4]
for(unsigned int i = 0; i < N; ++i) {
res += *d.px++ + *d.py++ + *d.pz++;
00C81361  add         ebx,eax
00C81363  mov         eax,dword ptr [edi-0Ch]
00C81366  add         eax,dword ptr [esi-0Ch]
00C81369  add         eax,dword ptr [ecx-0Ch]
00C8136C  add         edx,dword ptr [ecx-4]
00C8136F  add         ebx,eax
00C81371  mov         eax,dword ptr [edi-8]
00C81374  add         eax,dword ptr [esi-8]
00C81377  add         eax,dword ptr [ecx-8]
00C8137A  add         ebx,eax
00C8137C  add         ebx,edx
00C8137E  sub         dword ptr [ebp-4],1
00C81382  jne         <lambda_90dad2b8e1a29d982a00cc5b5b0ef516>::operator()+20h (0C81340h)
</code>```

I have next to no knowledge about X86/MMX assembler, but obviously the MMX stuff is much faster.
I don't know why it is not as optimized when using a struct. The only real difference I see between the both is that you declare int* in your struct, but your auto variables should be const int*. But I already played a bit around with const and it didn't change anything.

Body:
I found that the following loop

std::vector<int> x,y,z;
...
unsigned int res=0;
auto p=x.data();
auto q=y.data();
auto r=z.data();
for(unsigned int i=0;i<N;++i){
  res+=*p++ +*q++ +*r++;
}

runs almost twice as fast as this one, which merely packs the pointers in a struct:

struct pdata{int *px,*py,*pz;};

unsigned int res=0;
pdata d{x.data(),y.data(),z.data()};
for(unsigned int i=0;i<N;++i){
  res+=*d.px++ +*d.py++ +*d.pz++;
}
return res;

Is this a known performance issue? Please find below complete program and performance measurements for Visual C++ 2015 in 32-bit (x86) release mode (default settings), Windows 7 64-bit, Intel Core i5-2520M @2.5GHz:

#include <algorithm>
#include <array>
#include <chrono>
#include <cmath>
#include <numeric>

std::chrono::high_resolution_clock::time_point measure_start,measure_pause;

template<typename F>
double measure(F f)
{
  using namespace std::chrono;

  static const int              num_trials=10;
  static const milliseconds     min_time_per_trial(200);
  std::array<double,num_trials> trials;
  volatile decltype(f())        res; /* to avoid optimizing f() away */

  for(int i=0;i<num_trials;++i){
    int                               runs=0;
    high_resolution_clock::time_point t2;

    measure_start=high_resolution_clock::now();
    do{
      res=f();
      ++runs;
      t2=high_resolution_clock::now();
    }while(t2-measure_start<min_time_per_trial);
    trials[i]=duration_cast<duration<double>>(t2-measure_start).count()/runs;
  }
  (void)res; /* var not used warn */

  std::sort(trials.begin(),trials.end());
  return std::accumulate(
    trials.begin()+2,trials.end()-2,0.0)/(trials.size()-4);
}

template<typename F>
double measure(unsigned int n,F f)
{
  double t=measure(f);
  return (t/n)*10E9;
}

#include <iostream>
#include <vector>

int main()
{
  static const unsigned int N=100000;
  std::vector<int> x(N),y(N),z(N);

  for(int i=0;i<N;i++){
    x[i]=i;
    y[i]=i+1;
    z[i]=i+2;
  }

  std::cout<<measure(N,[&]{
    unsigned int res=0;
    auto p=x.data();
    auto q=y.data();
    auto r=z.data();
    for(unsigned int i=0;i<N;++i){
      res+=*p++ +*q++ +*r++;
    }
    return res;
  })<<",";

  std::cout<<measure(N,[&]{
    struct pdata{int *px,*py,*pz;};

    unsigned int res=0;
    pdata d{x.data(),y.data(),z.data()};
    for(unsigned int i=0;i<N;++i){
      res+=*d.px++ +*d.py++ +*d.pz++;
    }
    return res;
  })<<"\n";
}

Output

4.24541,7.44588

Thank you,

Body:
Fascinating. This seems to be indeed a performance/optimization issue.
Loop #1 uses MMX opcodes:

for(unsigned int i = 0; i < N; ++i) {
res += *p++ + *q++ + *r++;
00C812C0  lea         eax,[eax+20h]
00C812C3  lea         esi,[esi+20h]
00C812C6  lea         edx,[edx+20h]
00C812C9  movups      xmm0,xmmword ptr [esi-20h]
00C812CD  movups      xmm1,xmmword ptr [eax-20h]
00C812D1  paddd       xmm1,xmm0
00C812D5  movups      xmm0,xmmword ptr [edx-20h]
00C812D9  paddd       xmm1,xmm0
00C812DD  paddd       xmm3,xmm1
00C812E1  movups      xmm0,xmmword ptr [esi-10h]
00C812E5  movups      xmm1,xmmword ptr [eax-10h]
00C812E9  paddd       xmm1,xmm0
00C812ED  movups      xmm0,xmmword ptr [edx-10h]
00C812F1  paddd       xmm1,xmm0
00C812F5  paddd       xmm2,xmm1
00C812F9  sub         ecx,1
00C812FC  jne

while Loop #2 uses standard opcodes:

for(unsigned int i = 0; i < N; ++i) {
res += *d.px++ + *d.py++ + *d.pz++;
00C81340  mov         eax,dword ptr [edi]
00C81342  lea         ecx,[ecx+14h]
00C81345  add         eax,dword ptr [esi]
00C81347  lea         edi,[edi+14h]
00C8134A  add         eax,dword ptr [ecx-14h]
00C8134D  lea         esi,[esi+14h]
00C81350  mov         edx,dword ptr [edi-4]
00C81353  add         ebx,eax
00C81355  mov         eax,dword ptr [edi-10h]
00C81358  add         eax,dword ptr [esi-10h]
00C8135B  add         eax,dword ptr [ecx-10h]
00C8135E  add         edx,dword ptr [esi-4]
for(unsigned int i = 0; i < N; ++i) {
res += *d.px++ + *d.py++ + *d.pz++;
00C81361  add         ebx,eax
00C81363  mov         eax,dword ptr [edi-0Ch]
00C81366  add         eax,dword ptr [esi-0Ch]
00C81369  add         eax,dword ptr [ecx-0Ch]
00C8136C  add         edx,dword ptr [ecx-4]
00C8136F  add         ebx,eax
00C81371  mov         eax,dword ptr [edi-8]
00C81374  add         eax,dword ptr [esi-8]
00C81377  add         eax,dword ptr [ecx-8]
00C8137A  add         ebx,eax
00C8137C  add         ebx,edx
00C8137E  sub         dword ptr [ebp-4],1
00C81382  jne         <lambda_90dad2b8e1a29d982a00cc5b5b0ef516>::operator()+20h (0C81340h)

I have next to no knowledge about X86/MMX assembler, but obviously the MMX stuff is much faster.
I don't know why it is not as optimized when using a struct. The only real difference I see between the both is that you declare int* in your struct, but your auto variables should be const int*. But I already played a bit around with const and it didn't change anything.


问:
Unable to create Dynamic from GADT Expression Type in Haskell
I have the following in Haskell (as a minimum example).

```<code>{-# LANGUAGE GADTs #-}
import Data.Dynamic

data Expr a where
  Lift  :: (Show a) => a -> Expr a --Lift some type into Expr
  Lam   :: (Expr a -> Expr b) -> Expr (a -> b)
  Const :: Expr a -> Expr b -> Expr a
</code>```

When I try to create a Dynamic from the following, I get an error that I'm unsure how to correct.

```<code>--This is the code
toDyn $ (Lam (Const (Lift 1)))
-- This is the error
-- • No instance for (Typeable b0) arising from a use of ‘toDyn’
-- • In the expression: toDyn (Lam (Const (Lift 1)))
--   In an equation for ‘it’: it = toDyn (Lam (Const (Lift 1)))
</code>```

Is there there any way around this? The other constructors all work fine (my actual program has over 100 others!) but Const is really giving me trouble!

答:
The error is saying that type of the second argument to Const, the one that is being thrown away, needs to be Typeable. But it's a fully general type variable, without a Typeable constraint. If you write something like

```<code>toDyn (Const (Lift 1) :: Expr Int -> Expr Int)
</code>```

or

```<code>toDyn (Lam (Const (Lift 1) :: Expr Int -> Expr Int))
</code>```

both work.

Body:
I have the following in Haskell (as a minimum example).

{-# LANGUAGE GADTs #-}
import Data.Dynamic

data Expr a where
  Lift  :: (Show a) => a -> Expr a --Lift some type into Expr
  Lam   :: (Expr a -> Expr b) -> Expr (a -> b)
  Const :: Expr a -> Expr b -> Expr a

When I try to create a Dynamic from the following, I get an error that I'm unsure how to correct.

--This is the code
toDyn $ (Lam (Const (Lift 1)))
-- This is the error
-- • No instance for (Typeable b0) arising from a use of ‘toDyn’
-- • In the expression: toDyn (Lam (Const (Lift 1)))
--   In an equation for ‘it’: it = toDyn (Lam (Const (Lift 1)))

Is there there any way around this? The other constructors all work fine (my actual program has over 100 others!) but Const is really giving me trouble!

Body:
The error is saying that type of the second argument to Const, the one that is being thrown away, needs to be Typeable. But it's a fully general type variable, without a Typeable constraint. If you write something like

toDyn (Const (Lift 1) :: Expr Int -> Expr Int)

or

toDyn (Lam (Const (Lift 1) :: Expr Int -> Expr Int))

both work.


问:
PLSQL ORACLE: Errors with triggers
I am trying to make a  trigger for a table PET that has a field Invitation and it turns Yes or No based on the value of a field called Phone from a table PEOPLE. If the phone value isn't null and some of the other fields in the PET table have valid values and aren't null, the value in Invitation field should turn to Yes.

I am able to do that but the problem is later on when I try to update my table and set one of the fields to null, it doesn't update the value of invitation field to No. So now I am working on making a trigger for the PET table itself that checks to see if the required fields are not null so that the value of invitation can be changed.

However, the problem is that the user has to enter data into the PET table before going towards the PEOPLE table. So my trigger isn't able to fetch any value when I am inserting data inside my table PET.

Here is what I did for the trigger:

```<code>create or replace trigger Phone_check
    before insert or update on PETS
    for each row
DECLARE
    SELECT phone INTO v_phone
    FROM PEOPLE
        INNER JOIN Family ON PEOPLE.ID=FAMILY.ID
        INNER JOIN PETS ON FAMILY.ID=PETS.ID
    WHERE PETS.ID=:NEW.ID;
    IF :NEW.NAME IS NOT NULL
    AND :NEW.AGE IS NOT NULL
    AND v_phone IS NOT NULL THEN
        :NEW.INVITATION:='Yes';
    ELSIF :NEW.NAME IS NULL
    OR :NEW.AGE IS NULL
    AND v_phone IS NULL THEN
       :NEW.INVITATION:='No';
    END IF;
END;
</code>```

I get what the problem with this trigger is:  there are no values in the people or family table yet. But the PET table is supposed to be the first table. How should I fix this? Is there a way to activate this trigger only after required values already exist inside other tables? I'm really confused.

答:
I think you are getting an error. Here is an example:

```<code>SQL> declare
  2  test number;
  3  begin
  4  select blocks into test from user_segments where segment_name='asdfasdfasdf';
  5  if test is not null then
  6    test := 1;
  7  end if;
  8  end;
  9  /
declare
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4
</code>```

You can't test a variable from a select into when the select doesn't return a result without getting the no data found error. I usually just do a count.

```<code>SQL> declare
  2  test number;
  3  begin
  4  select count(blocks) into test from user_segments where segment_name='asdfasdfasdf';
  5  if test > 0 then
  6      select blocks into test from user_segments where segment_name='asdfasdfasdf';
  7      test := 1;
  8  end if;
  9  end;
 10  /

PL/SQL procedure successfully completed.
</code>```

A select count on a table that exists will return a value.

Bobby

Title: PLSQL ORACLE: Errors with triggers

Body:
I am trying to make a  trigger for a table PET that has a field Invitation and it turns Yes or No based on the value of a field called Phone from a table PEOPLE. If the phone value isn't null and some of the other fields in the PET table have valid values and aren't null, the value in Invitation field should turn to Yes.

I am able to do that but the problem is later on when I try to update my table and set one of the fields to null, it doesn't update the value of invitation field to No. So now I am working on making a trigger for the PET table itself that checks to see if the required fields are not null so that the value of invitation can be changed.

However, the problem is that the user has to enter data into the PET table before going towards the PEOPLE table. So my trigger isn't able to fetch any value when I am inserting data inside my table PET.

Here is what I did for the trigger:

create or replace trigger Phone_check
    before insert or update on PETS
    for each row
DECLARE
    SELECT phone INTO v_phone
    FROM PEOPLE
        INNER JOIN Family ON PEOPLE.ID=FAMILY.ID
        INNER JOIN PETS ON FAMILY.ID=PETS.ID
    WHERE PETS.ID=:NEW.ID;
    IF :NEW.NAME IS NOT NULL
    AND :NEW.AGE IS NOT NULL
    AND v_phone IS NOT NULL THEN
        :NEW.INVITATION:='Yes';
    ELSIF :NEW.NAME IS NULL
    OR :NEW.AGE IS NULL
    AND v_phone IS NULL THEN
       :NEW.INVITATION:='No';
    END IF;
END;

I get what the problem with this trigger is:  there are no values in the people or family table yet. But the PET table is supposed to be the first table. How should I fix this? Is there a way to activate this trigger only after required values already exist inside other tables? I'm really confused.

Body:
I think you are getting an error. Here is an example:

SQL> declare
  2  test number;
  3  begin
  4  select blocks into test from user_segments where segment_name='asdfasdfasdf';
  5  if test is not null then
  6    test := 1;
  7  end if;
  8  end;
  9  /
declare
*
ERROR at line 1:
ORA-01403: no data found
ORA-06512: at line 4

You can't test a variable from a select into when the select doesn't return a result without getting the no data found error. I usually just do a count.

SQL> declare
  2  test number;
  3  begin
  4  select count(blocks) into test from user_segments where segment_name='asdfasdfasdf';
  5  if test > 0 then
  6      select blocks into test from user_segments where segment_name='asdfasdfasdf';
  7      test := 1;
  8  end if;
  9  end;
 10  /

PL/SQL procedure successfully completed.

A select count on a table that exists will return a value.

Bobby


问:
NHibernate.ISession does not contain a definition for Linq
I'm using NHibernate latest builds but unable to work with linq. I already added using NHibernate.Linq, so that's not the issue.

```<code>using (ISession session = NHibernateHelper.OpenSession())
{
    var sss = session.Linq<Category>().ToArray(); <-- Error mentioned above.
}
</code>```

Looks like there is no extention method Linq() for ISession, despite the fact thath NHibernate.Linq is in uses list. Any idea?

Thanks

答:
session.Linq<T>() is for the contrib provider for NHibernate 2.x

session.Query<T>() is for the built-in provider in NHibernate 3.x

Body:
I'm using NHibernate latest builds but unable to work with linq. I already added using NHibernate.Linq, so that's not the issue.

using (ISession session = NHibernateHelper.OpenSession())
{
    var sss = session.Linq<Category>().ToArray(); <-- Error mentioned above.
}

Looks like there is no extention method Linq() for ISession, despite the fact thath NHibernate.Linq is in uses list. Any idea?

Thanks


问:
Same result every time with random numbers (python)
```<code>def gDiceRoll():

    gDiceOptions.destroy()

    global gDiceRoll
    gDiceRoll = Tk()
    gDiceRoll.title("Green Dice Roll")
    gDiceRoll.config(background="#32cd32")

    lbloutcome = Label(gDiceRoll, text="?", width="12", height="8", bg="#32cd32")

    play()

    while True:

        outcomeG = random.randint(1, 100)
        lbloutcome = Label(gDiceRoll, text="?", width="12", height="8", bg="#32cd32")

        if outcomeG <= 25:

            lbloutcome.config(text="G1", font=(25))
            gDiceRoll.update()
            f = open("Logs.txt", "a")
            ts = time.time()
            sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
            f.write(sttime + "G1 \n")
            f.close()
            photo = PhotoImage(file=r"C:\Temp\Dice_Roll\pics\G1.gif")
            lblop = Label(gDiceRoll, image=photo)
            lblop.pack()
            lbloutcome.pack()
            gDiceRoll.mainloop()
            gDiceRoll.after(1)
            os.execl(sys.executable, sys.executable, *sys.argv)
            break

        elif outcomeG <= 22:

            lbloutcome.config(text="G2", font=(25))
            gDiceRoll.update()
            f = open("Logs.txt", "a")
            ts = time.time()
            sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
            f.write(sttime + "G2 \n")
            f.close()
            photo = PhotoImage(file=r"C:\Temp\Dice_Roll\pics\G2.gif")
            lblop = Label(gDiceRoll, image=photo)
            lblop.pack()
            lbloutcome.pack()
            gDiceRoll.mainloop()
            gDiceRoll.after(1)
            os.execl(sys.executable, sys.executable, *sys.argv)
            break
        #etc
</code>```

Every time I run the program ir ALWAYS comes out with G1. I have tried to fix it many ways but they just create other problems. The elif G1 <= 25 means it has a 25% chance of doing G1 but it always does G1.

How can I fix this? Any help will be greatly appreciated

答:
let's say outcomeG <= 22

then your code encounters outcomeG <= 25 condition first, and enters first condition, always.

You have to swap your if and elif to test <=22 first

Of course you have to do something if outcomeG > 25 else you're looping for nothing.

Body:
def gDiceRoll():

    gDiceOptions.destroy()

    global gDiceRoll
    gDiceRoll = Tk()
    gDiceRoll.title("Green Dice Roll")
    gDiceRoll.config(background="#32cd32")

    lbloutcome = Label(gDiceRoll, text="?", width="12", height="8", bg="#32cd32")

    play()

    while True:

        outcomeG = random.randint(1, 100)
        lbloutcome = Label(gDiceRoll, text="?", width="12", height="8", bg="#32cd32")

        if outcomeG <= 25:

            lbloutcome.config(text="G1", font=(25))
            gDiceRoll.update()
            f = open("Logs.txt", "a")
            ts = time.time()
            sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
            f.write(sttime + "G1 \n")
            f.close()
            photo = PhotoImage(file=r"C:\Temp\Dice_Roll\pics\G1.gif")
            lblop = Label(gDiceRoll, image=photo)
            lblop.pack()
            lbloutcome.pack()
            gDiceRoll.mainloop()
            gDiceRoll.after(1)
            os.execl(sys.executable, sys.executable, *sys.argv)
            break

        elif outcomeG <= 22:

            lbloutcome.config(text="G2", font=(25))
            gDiceRoll.update()
            f = open("Logs.txt", "a")
            ts = time.time()
            sttime = datetime.datetime.fromtimestamp(ts).strftime('%Y%m%d_%H:%M:%S - ')
            f.write(sttime + "G2 \n")
            f.close()
            photo = PhotoImage(file=r"C:\Temp\Dice_Roll\pics\G2.gif")
            lblop = Label(gDiceRoll, image=photo)
            lblop.pack()
            lbloutcome.pack()
            gDiceRoll.mainloop()
            gDiceRoll.after(1)
            os.execl(sys.executable, sys.executable, *sys.argv)
            break
        #etc

Every time I run the program ir ALWAYS comes out with G1. I have tried to fix it many ways but they just create other problems. The elif G1 <= 25 means it has a 25% chance of doing G1 but it always does G1.

How can I fix this? Any help will be greatly appreciated


问:
Exchange EWS Calendar title rewrite for room mailboxes
Our IT has provided me with a service account (ex-sa-devtest@mydomain.de) that has delegate rights to a room's mailbox (EX-Room-A@mydomain.de) and a user's mailbox (user.a@mydomain.de).

In Outlook, running as user.a, I created an event using EX-Room-A as room. Now here is the matrix what happens in Outlook Web Access and by using the EWS API FindItems (resp. GetItem):

using the credentials of user.a, I see the correct event details (Subject and Body) on the mailbox of user.a. When accessing the mailbox of ex-room-a, I get "ErrorFolderNotFound: The specified folder could not be found in the store."

Using the credentials of ex-sa-devtest on mailbox of ex-room-a, I see Subject="User A " (note the space at the end) and Body is empty. On mailbox of user.a, I see correct Subject and Body.

What causes the "rewrite" of the Subject field and the emptying of the Body field when the service account accesses the room mailbox?

The SOAP XML I use is:

```<code><SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:ns2="http://schemas.microsoft.com/exchange/services/2006/messages">
<SOAP-ENV:Header><ns1:RequestServerVersion Version="Exchange2013_SP1"/><ns1:TimeZoneContext><ns1:TimeZoneDefinition Id="W. Europe Standard Time"/></ns1:TimeZoneContext></SOAP-ENV:Header>
<SOAP-ENV:Body>
<ns2:FindItem>
<ns2:ItemShape><ns1:BaseShape>AllProperties</ns1:BaseShape></ns2:ItemShape>
<ns2:CalendarView StartDate="2017-12-06T00:00:00+01:00" EndDate="2017-12-06T23:59:59+01:00"/>
<ns2:ParentFolderIds>
<ns1:DistinguishedFolderId Id="calendar"><ns1:Mailbox><ns1:EmailAddress>ex-room-a@mydomain.de</ns1:EmailAddress></ns1:Mailbox></ns1:DistinguishedFolderId>
</ns2:ParentFolderIds>
</ns2:FindItem>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>
</code>```

答:
For security reason this information is removed by the Mailbox assistant as part of the Automatic Processing logic. You can configure this using the Set-CalendarProcessing cmdlet https://technet.microsoft.com/en-us/library/dd335046%28v=exchg.160%29.aspx eg

The DeleteSubject parameter specifies whether to remove or keep the subject of incoming meeting requests. Valid input for this parameter is $true or $false. The default value is $true.
  This parameter is used only on resource mailboxes where the AutomateProcessing parameter is set to AutoAccept.

Body:
Our IT has provided me with a service account (ex-sa-devtest@mydomain.de) that has delegate rights to a room's mailbox (EX-Room-A@mydomain.de) and a user's mailbox (user.a@mydomain.de).

In Outlook, running as user.a, I created an event using EX-Room-A as room. Now here is the matrix what happens in Outlook Web Access and by using the EWS API FindItems (resp. GetItem):

using the credentials of user.a, I see the correct event details (Subject and Body) on the mailbox of user.a. When accessing the mailbox of ex-room-a, I get "ErrorFolderNotFound: The specified folder could not be found in the store."

Using the credentials of ex-sa-devtest on mailbox of ex-room-a, I see Subject="User A " (note the space at the end) and Body is empty. On mailbox of user.a, I see correct Subject and Body.

What causes the "rewrite" of the Subject field and the emptying of the Body field when the service account accesses the room mailbox?

The SOAP XML I use is:

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ns1="http://schemas.microsoft.com/exchange/services/2006/types" xmlns:ns2="http://schemas.microsoft.com/exchange/services/2006/messages">
<SOAP-ENV:Header><ns1:RequestServerVersion Version="Exchange2013_SP1"/><ns1:TimeZoneContext><ns1:TimeZoneDefinition Id="W. Europe Standard Time"/></ns1:TimeZoneContext></SOAP-ENV:Header>
<SOAP-ENV:Body>
<ns2:FindItem>
<ns2:ItemShape><ns1:BaseShape>AllProperties</ns1:BaseShape></ns2:ItemShape>
<ns2:CalendarView StartDate="2017-12-06T00:00:00+01:00" EndDate="2017-12-06T23:59:59+01:00"/>
<ns2:ParentFolderIds>
<ns1:DistinguishedFolderId Id="calendar"><ns1:Mailbox><ns1:EmailAddress>ex-room-a@mydomain.de</ns1:EmailAddress></ns1:Mailbox></ns1:DistinguishedFolderId>
</ns2:ParentFolderIds>
</ns2:FindItem>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>


问:
R ggplot geom_bar Error: Discrete value supplied to continuous scale
I have proportion response data for 4 experimental groups, with 2 different statistics computed for each group. I want the following figure (which I can achieve):

I obtain this figure with the following code:

```<code>Group<-c('a','b','c','d','a','b','c','d')
Statistic<-c('Mean','Mean','Mean','Mean','d','d','d','d')
Val<-c(.75,.83,.79,.69,.5,.02,.1,.3)
dfm2<-data.frame(cbind(Group,Statistic,Val))
ggplot(dfm2,aes(x = Group,y = Val)) +
 geom_bar(aes(fill = Statistic),position = dodge',stat='identity')
</code>```

However, when I change the limits of the y-axis (to [0,1] since I have proportions) by adding the line of code:

```<code>+ scale_y_continuous(limits=c(0, 1))
</code>```

I get

Error: Discrete value supplied to continuous scale

So I understand this means I have a non-continuous variable. I have tried converting my Statistic variable by using as.numeric() and countless other options but to no avail.  If anyone can assist me in solving this problem and/or explain what causes it, I would be most appreciative.

答:
Try the following.</p>
```<code>ggplot(dfm2,aes(x = Group,y = as.numeric(as.character(Val)))) +
  geom_bar(aes(fill = Statistic),position = 'dodge',stat='identity')+
  scale_y_continuous(limits=c(0, 1))
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have proportion response data for 4 experimental groups, with 2 different statistics computed for each group. I want the following figure (which I can achieve):

I obtain this figure with the following code:

Group<-c('a','b','c','d','a','b','c','d')
Statistic<-c('Mean','Mean','Mean','Mean','d','d','d','d')
Val<-c(.75,.83,.79,.69,.5,.02,.1,.3)
dfm2<-data.frame(cbind(Group,Statistic,Val))
ggplot(dfm2,aes(x = Group,y = Val)) +
 geom_bar(aes(fill = Statistic),position = dodge',stat='identity')

However, when I change the limits of the y-axis (to [0,1] since I have proportions) by adding the line of code:

+ scale_y_continuous(limits=c(0, 1))

I get

Error: Discrete value supplied to continuous scale

So I understand this means I have a non-continuous variable. I have tried converting my Statistic variable by using as.numeric() and countless other options but to no avail.  If anyone can assist me in solving this problem and/or explain what causes it, I would be most appreciative.

Body:
Try the following.

ggplot(dfm2,aes(x = Group,y = as.numeric(as.character(Val)))) +
  geom_bar(aes(fill = Statistic),position = 'dodge',stat='identity')+
  scale_y_continuous(limits=c(0, 1))


问:
List Comprehension returns none but I don't have anything that can result in none
```<code>list_of_strings = ["a", "2", "7", "zebra"]

def safe_int(list):
    try:
        list[i] = int(list[i])
    except ValueError:
        list[i] = 0

new_list = [safe_int(list_of_strings) for i in range(len(list_of_strings))]

print new_list
</code>```

expected result : [0, 2, 7, 0]

outcome : [None, None, None, None]

答:
Define your function so that it returns the result of the conversion or the number zero

```<code>def safe_int(l, i):
    try:
        return int(l[i])
    except ValueError:
        return 0
</code>```

(note that I've passed explicitly i to the function because the value of i in the list comprehension is visible in the function due to a bad design decision in Python 2 that was corrected in Python 3) and then build the new_list

```<code> new_list = [ safe_int(list_of_strings, i) for ...]
</code>```

I have to say that your approach is not idiomatic, I'd prefer to write

```<code>def safe_int(a_string):
    try:
        return int(a_string)
    except ValueError:
        return 0

new_list = [safe_int(s) for s in list_of_strings]
</code>```

Body:
list_of_strings = ["a", "2", "7", "zebra"]

def safe_int(list):
    try:
        list[i] = int(list[i])
    except ValueError:
        list[i] = 0

new_list = [safe_int(list_of_strings) for i in range(len(list_of_strings))]

print new_list

expected result : [0, 2, 7, 0]

outcome : [None, None, None, None]

Body:
Define your function so that it returns the result of the conversion or the number zero

def safe_int(l, i):
    try:
        return int(l[i])
    except ValueError:
        return 0

(note that I've passed explicitly i to the function because the value of i in the list comprehension is visible in the function due to a bad design decision in Python 2 that was corrected in Python 3) and then build the new_list

 new_list = [ safe_int(list_of_strings, i) for ...]

I have to say that your approach is not idiomatic, I'd prefer to write

def safe_int(a_string):
    try:
        return int(a_string)
    except ValueError:
        return 0

new_list = [safe_int(s) for s in list_of_strings]


问:
A Google Form creates an Event in Google Calendar (without using responses)
This is more of a simple yes or no question with the hope that someone could point me in the right direction.

My company has Google Calendar and Google Forms.  What we want to do is create a Registration Form using Google Forms, once the Registration Form is created then it will automatically create an event within our Google Calendar with the Registration Form Link.

We do not want to use the responses to create an event, we want to use the form to create the event.   The responses are set up within the form to be emailed to the a specific person where they can tally and confirm all the registries.

Our company also has a wordpress site, so maybe there is a plugin for wordpress that creates the form and automatically creates an event on our Google Calendar.

Is this possible?

答: From the Google Form editor you could create a bounded script project and add to it an script that creates a Google Calendar event, so yes, it's possible.</p>


问:
MsgBox within an If statement not working
I'm trying to use the following code to open a password protected file if the Windows user is "bhope" or "jdean" and display a message box if the user is anyone else. It opens the file as needed when the user is "bhope" or "jdean" but if another user clicks the button, nothing happens/no error. What am I missing?

```<code>Sub Button1_Click()

Dim wb As Workbook
Dim strUser As String
strUser = Environ("USERNAME")

  Application.ScreenUpdating = False

  Select Case strUser

    ' Full Workbook Access
    Case Is = "bhope", "jdean"
       If ActiveWorkbook.ReadOnly Then _
          Set wb = Workbooks.Open(Filename:="M:\...", Password:="TEST")

    ' Limit Access
    Case Is = "mjackson" 'also tried "Case Is <> "bhope", "jdean"
       If Not ActiveWorkbook.ReadOnly Then _
          MsgBox ("This button is reserved for SAMs")
  End Select

  Application.ScreenUpdating = True
End Sub
</code>```

If it helps, I used this link to start the base of the code and tried to modify it from there. Thanks and cheers!

答:
I figured out the solution. Apparently the "case else" I said I tried earlier was actually done to another test file with similar code as I usually have several open when I'm testing to compare behaviors. I also had to delete the line below "case else" so that only the msg box line would run after that. Below is the code I used should anyone need it in the future:

```<code>Sub Button1_Click()

Dim wb As Workbook
Dim strUser As String
strUser = Environ("USERNAME")

Application.ScreenUpdating = False

Select Case LCase(strUser)
' Full Workbook Access
Case Is = "bhope", "jdean"
If ThisWorkbook.ReadOnly Then _
Set wb = Workbooks.Open(Filename:="M:...", Password:="TEST")
' Limit Access
Case Else
MsgBox ("This button is reserved for SAMs")
End Select
Application.ScreenUpdating = True
End Sub
</code>```

To answer earlier questions: my understanding of screen update is that if it's turned off, the application will run non-visually so as not to cause concern for the users who will be using this file. Also, this code makes it run faster, does it not?

As far as the purpose of the workbook and security concerns... the button will be used on a read only workbook that houses many portions of our company's metrics. The file is made read only so that users cannot save over it. Since the file is kind of big and a lot of data is expected to go into it, my thought process was to load the "Shell" of the main file then have buttons that determine who should be allowed to add info to certain sheets. By having both files read only and password-protected, I'm able to open the 2nd sheet when the appropriate user clicks the button, then have data transfer back and forth between the workbooks. I still intend on password protecting the VBA code so I don't see how their could be a security concern. Also, @ashleedog, I meant that everyone in our company has lower case user names.

Body:
I'm trying to use the following code to open a password protected file if the Windows user is "bhope" or "jdean" and display a message box if the user is anyone else. It opens the file as needed when the user is "bhope" or "jdean" but if another user clicks the button, nothing happens/no error. What am I missing?

Sub Button1_Click()

Dim wb As Workbook
Dim strUser As String
strUser = Environ("USERNAME")

  Application.ScreenUpdating = False

  Select Case strUser

    ' Full Workbook Access
    Case Is = "bhope", "jdean"
       If ActiveWorkbook.ReadOnly Then _
          Set wb = Workbooks.Open(Filename:="M:\...", Password:="TEST")

    ' Limit Access
    Case Is = "mjackson" 'also tried "Case Is <> "bhope", "jdean"
       If Not ActiveWorkbook.ReadOnly Then _
          MsgBox ("This button is reserved for SAMs")
  End Select

  Application.ScreenUpdating = True
End Sub

If it helps, I used this link to start the base of the code and tried to modify it from there. Thanks and cheers!

Body:
I figured out the solution. Apparently the "case else" I said I tried earlier was actually done to another test file with similar code as I usually have several open when I'm testing to compare behaviors. I also had to delete the line below "case else" so that only the msg box line would run after that. Below is the code I used should anyone need it in the future:

Sub Button1_Click()

Dim wb As Workbook
Dim strUser As String
strUser = Environ("USERNAME")

Application.ScreenUpdating = False

Select Case LCase(strUser)
' Full Workbook Access
Case Is = "bhope", "jdean"
If ThisWorkbook.ReadOnly Then _
Set wb = Workbooks.Open(Filename:="M:...", Password:="TEST")
' Limit Access
Case Else
MsgBox ("This button is reserved for SAMs")
End Select
Application.ScreenUpdating = True
End Sub

To answer earlier questions: my understanding of screen update is that if it's turned off, the application will run non-visually so as not to cause concern for the users who will be using this file. Also, this code makes it run faster, does it not?

As far as the purpose of the workbook and security concerns... the button will be used on a read only workbook that houses many portions of our company's metrics. The file is made read only so that users cannot save over it. Since the file is kind of big and a lot of data is expected to go into it, my thought process was to load the "Shell" of the main file then have buttons that determine who should be allowed to add info to certain sheets. By having both files read only and password-protected, I'm able to open the 2nd sheet when the appropriate user clicks the button, then have data transfer back and forth between the workbooks. I still intend on password protecting the VBA code so I don't see how their could be a security concern. Also, @ashleedog, I meant that everyone in our company has lower case user names.


问:
How is this dispatch function coming from props?
I'm trying to learn from reading this app's code, and I am confused how you get dispatch from the props in this line of code:

```<code> _handleSubmit(e) {
    e.preventDefault();

    const { email, password } = this.refs;
    const { dispatch } = this.props;

    dispatch(Actions.signIn(email.value, password.value));
  }
</code>```

https://github.com/bigardone/phoenix-trello/blob/master/web/static/js/views/sessions/new.js#L17

Hoping someone can explain how calling this.props will return a dispatch?

答:
const { dispatch } = this.props; is just deconstructing this.props.dispatch into a dispatch variable so it's used from props and where do they come to props? From react-redux connect:

```<code>export default connect(mapStateToProps)(SessionsNew);
</code>```

connect is just Higher Order Component which basically connects your component with the store. As part of this process it puts dispatch into component's props

Edit:

The main idea is that connect is a function that takes whatever components and extends it's props with dispatch property (it returns another react components that wraps your component). You can also map some properties from state to your component and bind actions with dispatch using mapDispatchToProps and mapStateToProps

Body:
I'm trying to learn from reading this app's code, and I am confused how you get dispatch from the props in this line of code:

 _handleSubmit(e) {
    e.preventDefault();

    const { email, password } = this.refs;
    const { dispatch } = this.props;

    dispatch(Actions.signIn(email.value, password.value));
  }

https://github.com/bigardone/phoenix-trello/blob/master/web/static/js/views/sessions/new.js#L17

Hoping someone can explain how calling this.props will return a dispatch?

Body:
const { dispatch } = this.props; is just deconstructing this.props.dispatch into a dispatch variable so it's used from props and where do they come to props? From react-redux connect:

export default connect(mapStateToProps)(SessionsNew);

connect is just Higher Order Component which basically connects your component with the store. As part of this process it puts dispatch into component's props

Edit:

The main idea is that connect is a function that takes whatever components and extends it's props with dispatch property (it returns another react components that wraps your component). You can also map some properties from state to your component and bind actions with dispatch using mapDispatchToProps and mapStateToProps


问:
How to pass the dropdown and text value to email subject line using Javascript
Need your urgent help

I have one HTML page with 2 text box, 1 dropdown and 1 button, on button click I want to open the email(as currently I am doing with javascript) with subject line as whatever is selected in the drop down and whatever is written in text box.

```<code><body>
<form id='sampleform' method='post' action='' >
   Emp Number: <input type='text' name='empnum' />

   </p>

   <p>
       Unit Name: <input type='text' name='unit' />
   </p>
   <p>
       Type of subscription you want:
   <p>
       <select name="type">
           <option value="standard">Standard - Free</option>
           <option value="prof">Professional - Paid</option>
       </select>
   </p>
   </p>
   <p>
      <input type='submit' name='Submit' value='Submit' onClick="parent.location='mailto:er.saurav1@gmail.com?subject=Thanks for writing &body=Hi,%0A%0CThanks for writing. We will get back to you soon. %0A%0C%0D%0AThanks and Regards,%0A%0CSaurav Kumar%0A%0C%0A%0CFor further assistance call 81111'">
   </p>
</form>

</body>
</code>```

I want when my email will open the subject line output should be:

Emp Num | Unit Name | Selected value
  from the drop down

答:
Run this in your onclick:

```<code>var form = document.forms.sampleform;
var subject = form.empnum.value + ' | ' + form.unit.value + ' | ' + form.type.value;
parent.location = 'mailto:er.saurav1@gmail.com?subject=' + encodeURIComponent(subject) + '&body=...';
</code>```

Body:
Need your urgent help

I have one HTML page with 2 text box, 1 dropdown and 1 button, on button click I want to open the email(as currently I am doing with javascript) with subject line as whatever is selected in the drop down and whatever is written in text box.

<form id='sampleform' method='post' action='' >
   Emp Number: <input type='text' name='empnum' />

       Unit Name: <input type='text' name='unit' />

       Type of subscription you want:

       <select name="type">
           <option value="standard">Standard - Free</option>
           <option value="prof">Professional - Paid</option>
       </select>

      <input type='submit' name='Submit' value='Submit' onClick="parent.location='mailto:er.saurav1@gmail.com?subject=Thanks for writing &body=Hi,%0A%0CThanks for writing. We will get back to you soon. %0A%0C%0D%0AThanks and Regards,%0A%0CSaurav Kumar%0A%0C%0A%0CFor further assistance call 81111'">

</form>

I want when my email will open the subject line output should be:

Emp Num | Unit Name | Selected value
  from the drop down

Body:
Run this in your onclick:

var form = document.forms.sampleform;
var subject = form.empnum.value + ' | ' + form.unit.value + ' | ' + form.type.value;
parent.location = 'mailto:er.saurav1@gmail.com?subject=' + encodeURIComponent(subject) + '&body=...';


问:
SQL - How to join two tables that are based on a bit condition and will always populate the field

I am trying to join two tables in MS SQL Server.

One table contains the persons Name and their ID.

```<code>+----+---------+--------------+---------+
| ID |  Name   |    phone     |  email  |
+----+---------+--------------+---------+
|  1 | John A. | 111-111-1111 | a@email |
|  2 | Sara B. | 111-111-1112 | b@email |
|  3 | Joe C.  | 111-111-1113 | c@email |
|  4 | Jane D. | 111-111-1114 | d@email |
+----+---------+--------------+---------+
</code>```

The other table contains the ID, the languages they know, and a bit that indicates if it is their native language.

```<code>+----+----------+---------+
| ID | Language | Native  |
+----+----------+---------+
|  1 | English  | True    |
|  1 | Spanish  | False   |
|  2 | Spanish  | True    |
|  2 | English  | False   |
|  2 | French   | False   |
|  3 | French   | False   |
|  3 | Spanish  | False   |
|  4 | English  | True    |
+----+----------+---------+
</code>```

The table I want should show the id, persons name, their native language or which ever language is returned first, if this is their native language, phone number, email.

```<code>+----+---------+----------+--------+--------------+---------+
| ID |  Name   | Language | Native |    phone     |  email  |
+----+---------+----------+--------+--------------+---------+
|  1 | John A. | English  | True   | 111-111-1111 | a@email |
|  2 | Sara B. | Spanish  | True   | 111-111-1112 | b@email |
|  3 | Joe C.  | French   | False  | 111-111-1113 | c@email |
|  4 | Jane D. | English  | True   | 111-111-1114 | d@email |
+----+---------+----------+--------+--------------+---------+
</code>```

I have tried joining the tables and providing a where condition but it either returns only the native languages or all of the languages that the person knows.  I have also tried grouping by the ID, which said that the columns are invalid in the selected list.  I put all the columns into the group by clause but that gave me operand data type bit is invalid for max operator.

```<code>SELECT p.ID
      ,p.Name
      ,l.Language
      ,coalesce(max(l.native),0) as native
      ,p.phone
      ,p.email
  FROM people as p
  JOIN Languages as l on p.ID = l.ID
  group by p.id
</code>```

Body:
I am trying to join two tables in MS SQL Server.

One table contains the persons Name and their ID.

+----+---------+--------------+---------+
| ID |  Name   |    phone     |  email  |
+----+---------+--------------+---------+
|  1 | John A. | 111-111-1111 | a@email |
|  2 | Sara B. | 111-111-1112 | b@email |
|  3 | Joe C.  | 111-111-1113 | c@email |
|  4 | Jane D. | 111-111-1114 | d@email |
+----+---------+--------------+---------+

The other table contains the ID, the languages they know, and a bit that indicates if it is their native language.

+----+----------+---------+
| ID | Language | Native  |
+----+----------+---------+
|  1 | English  | True    |
|  1 | Spanish  | False   |
|  2 | Spanish  | True    |
|  2 | English  | False   |
|  2 | French   | False   |
|  3 | French   | False   |
|  3 | Spanish  | False   |
|  4 | English  | True    |
+----+----------+---------+

The table I want should show the id, persons name, their native language or which ever language is returned first, if this is their native language, phone number, email.

+----+---------+----------+--------+--------------+---------+
| ID |  Name   | Language | Native |    phone     |  email  |
+----+---------+----------+--------+--------------+---------+
|  1 | John A. | English  | True   | 111-111-1111 | a@email |
|  2 | Sara B. | Spanish  | True   | 111-111-1112 | b@email |
|  3 | Joe C.  | French   | False  | 111-111-1113 | c@email |
|  4 | Jane D. | English  | True   | 111-111-1114 | d@email |
+----+---------+----------+--------+--------------+---------+

I have tried joining the tables and providing a where condition but it either returns only the native languages or all of the languages that the person knows.  I have also tried grouping by the ID, which said that the columns are invalid in the selected list.  I put all the columns into the group by clause but that gave me operand data type bit is invalid for max operator.

SELECT p.ID
      ,p.Name
      ,l.Language
      ,coalesce(max(l.native),0) as native
      ,p.phone
      ,p.email
  FROM people as p
  JOIN Languages as l on p.ID = l.ID
  group by p.id

Body:
SQL Server solution:

create table person (
    id int,
    name varchar (45),
    phone varchar (45),
    email varchar (45)
    );
create table languages (
    id int,
    language varchar (45),
    Native bit
    );
insert into person values
(1, 'John A.', '111-111-1111', 'a@email'),
(2, 'Sara B.', '111-111-1112', 'b@email'),
(3, 'Joe C.', '111-111-1113', 'c@email'),
(4, 'Jane D.', '111-111-1114', 'd@email');
insert into languages values
(1, 'English', 1 ),
(1, 'Spanish', 0),
(2, 'Spanish', 1 ),
(2, 'English', 0),
(2, 'French', 0),
(3, 'French', 0),
(3, 'Spanish', 0),
(4, 'English', 1 );

select t1.id, t1.name, t2.language, t2.native, t1.phone, t1.email
from person t1 inner join
(select *, row_number () over (partition by id order by id) rn
 from languages) t2 on t1.id = t2.id
 where t2.rn =1

Results:

+----+---------+----------+--------+--------------+---------+
| id |  name   | language | native |    phone     |  email  |
+----+---------+----------+--------+--------------+---------+
|  1 | John A. | English  | True   | 111-111-1111 | a@email |
|  2 | Sara B. | Spanish  | True   | 111-111-1112 | b@email |
|  3 | Joe C.  | French   | False  | 111-111-1113 | c@email |
|  4 | Jane D. | English  | True   | 111-111-1114 | d@email |
+----+---------+----------+--------+--------------+---------+


问:
doGet and doPost in one class
When i try to use doGet and doPost in one class and pass parameters using post method I get

HTTP Status 405 - HTTP method GET is not supported by this URL

But when I comment doGet it works just fine. Why is that? doGet and doPost can't be used in the same class?

Here is class code:

```<code>package pl.javastart.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class wypisz_parametry extends HttpServlet {
private static final long serialVersionUID = 1321321321L;

/*public void doGet(HttpServletRequest request,
        HttpServletResponse response)    throws ServletException, IOException {
  PrintWriter out = response.getWriter();

  String parametr1 = request.getParameter("parametr1");
  String parametr2 = request.getParameter("parametr2");
  String parametr3 = request.getParameter("parametr3");

  out.println("Wczytanie 3 parametrow z zadania :");
  out.println(parametr1);
  out.println(parametr2);
  out.println(parametr3);
  }*/

public void doPost(HttpServletRequest request,
        HttpServletResponse response)   throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    out.println("Wczytanie 3 parametrow z zadania :");
    out.println(request.getParameter("parametr1"));
    out.println(request.getParameter("parametr2"));
    out.println(request.getParameter("parametr3"));
}

}
</code>```

And html:

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
  <TITLE>Przyklad POST</TITLE>
</HEAD>

<H1 ALIGN="CENTER">Przyklad HTTP POST</H1>

<FORM ACTION="http://localhost:8080/Parameters/wypisz_parametry"
  METHOD="POST">
Parametr 1:
<INPUT TYPE="TEXT" NAME="parametr1"><BR>
Parametr 2:
<INPUT TYPE="TEXT" NAME="parametr2"><BR>
Parametr 3:
<INPUT TYPE="TEXT" NAME="parametr3"><BR>
<INPUT TYPE="SUBMIT" VALUE="Wyslij">
</FORM>

</BODY>
</HTML>
</code>```

web.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <servlet>
    <servlet-name>Parameters</servlet-name>
    <servlet-class>pl.javastart.servlets.wypisz_parametry</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Parameters</servlet-name>
    <url-pattern>/wypisz_parametry</url-pattern>
  </servlet-mapping>
</web-app>
</code>```

答:
Both doGet() and doPost() methods can call the same servlet. So the issue is absolutely with something else. Maybe there is something wrong with your URL mappings in web.xml.

There is at least one issue with mapping:
On page we have:

```<code>ACTION="http://localhost:8080/Parameters/wypisz_parametry"
</code>```

But in web.xml we expect:

```<code>ACTION="http://localhost:8080/wypisz_parametry"
</code>```

Also it would be better to use relative path:

```<code>ACTION="/wypisz_parametry"
</code>```

Title: doGet and doPost in one class

Body:
When i try to use doGet and doPost in one class and pass parameters using post method I get

HTTP Status 405 - HTTP method GET is not supported by this URL

But when I comment doGet it works just fine. Why is that? doGet and doPost can't be used in the same class?

Here is class code:

package pl.javastart.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class wypisz_parametry extends HttpServlet {
private static final long serialVersionUID = 1321321321L;

/*public void doGet(HttpServletRequest request,
        HttpServletResponse response)    throws ServletException, IOException {
  PrintWriter out = response.getWriter();

  String parametr1 = request.getParameter("parametr1");
  String parametr2 = request.getParameter("parametr2");
  String parametr3 = request.getParameter("parametr3");

  out.println("Wczytanie 3 parametrow z zadania :");
  out.println(parametr1);
  out.println(parametr2);
  out.println(parametr3);
  }*/

public void doPost(HttpServletRequest request,
        HttpServletResponse response)   throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    out.println("Wczytanie 3 parametrow z zadania :");
    out.println(request.getParameter("parametr1"));
    out.println(request.getParameter("parametr2"));
    out.println(request.getParameter("parametr3"));
}

}

And html:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

  <TITLE>Przyklad POST</TITLE>

Przyklad HTTP POST

<FORM ACTION="http://localhost:8080/Parameters/wypisz_parametry"
  METHOD="POST">
Parametr 1:
<INPUT TYPE="TEXT" NAME="parametr1">

Parametr 2:
<INPUT TYPE="TEXT" NAME="parametr2">

Parametr 3:
<INPUT TYPE="TEXT" NAME="parametr3">

<INPUT TYPE="SUBMIT" VALUE="Wyslij">
</FORM>

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <servlet>
    <servlet-name>Parameters</servlet-name>
    <servlet-class>pl.javastart.servlets.wypisz_parametry</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Parameters</servlet-name>
    <url-pattern>/wypisz_parametry</url-pattern>
  </servlet-mapping>
</web-app>

Body:
Both doGet() and doPost() methods can call the same servlet. So the issue is absolutely with something else. Maybe there is something wrong with your URL mappings in web.xml.

There is at least one issue with mapping:
On page we have:

ACTION="http://localhost:8080/Parameters/wypisz_parametry"

But in web.xml we expect:

ACTION="http://localhost:8080/wypisz_parametry"

Also it would be better to use relative path:

ACTION="/wypisz_parametry"