问:
T-SQL: SUSER_SNAME vs SUSER_NAME?
The MSDN documentation says for SUSER_SNAME function:

Returns the login identification name from a user's security identification number (SID).

More over, it says for the SUSER_NAME function:

Returns the login identification name of the user.

Nonetheless, when I execute the following SQL statements I get the same result:

```<code>SELECT SUSER_NAME();
SELECT SUSER_SNAME();
</code>```

So, what are differences, and which one shall I use? Is there a situation I should use one rather that the other?

Please advice,

Thanks in advance :)

答:
SUSER_NAME() will return the name associated with an sid that exists in sys.server_principals.  The sid must exist in sys.server_principals.

SUSER_SNAME() can do that but also can return the sid of a login if the login is a member of an active directory group

So if you have [CONTOSO\MyGroup] in Active Directory and that group has one user [CONTOSO\MyUser]

And you add that group to SQL Server:
CREATE LOGIN [CONTOSO\MyGroup] FROM WINDOWS;

SELECT SUSER_ID('CONTOSO\MyUser'), SUSER_SID('CONTOSO\MyUser')

will give you
NULL, CONTOSO\MyUser
because CONTOSO\MyUser is not in sys.server_principals but is in A/D

Title: T-SQL: SUSER_SNAME vs SUSER_NAME?

Body:
The MSDN documentation says for SUSER_SNAME function:

Returns the login identification name from a user's security identification number (SID).

More over, it says for the SUSER_NAME function:

Returns the login identification name of the user.

Nonetheless, when I execute the following SQL statements I get the same result:

SELECT SUSER_NAME();
SELECT SUSER_SNAME();

So, what are differences, and which one shall I use? Is there a situation I should use one rather that the other?

Please advice,

Thanks in advance :)


来源: stackexchange

问:
MS Access Formula to Update one field in a table based on the amount "between" two other fields
I'm hoping someone can help me out.  I was hoping I could do an update query in MS Access that will update a field I have called "Materiality by Fiscal Year", based on whether or not another field "Brand Savings" is equal to or between a set of dollar ranges I have in another table.  The first table is as follows, which is the primary table:

```<code>+----------+------------+---------------+----------------------------+
|  Brand   | Project ID | Brand Savings | Materiality by Fiscal Year |
+----------+------------+---------------+----------------------------+
| aBS Corp |        121 | $110,000.00   |                            |
| aBS Corp |        151 | $17,640.67    |                            |
| aBS Corp |        152 | $5,682.37     |                            |
| aBS Corp |        154 | $564,669.58   |                            |
| aBS Corp |        157 | $5,097.00     |                            |
| aBS Corp |        159 | $33,798.00    |                            |
| aBS Corp |        190 | $200,000.00   |                            |
| aBS Corp |        193 | $250,000.00   |                            |
| aBS Corp |        194 | $366,666.67   |                            |
| aBS Corp |        197 | $90,799.00    |                            |
| aBS Corp |         20 | $14,000.00    |                            |
| aBS Corp |        219 | $2,800.00     |                            |
| aBS Corp |        222 | $132.58       |                            |
| aBS Corp |         23 | $2,068.30     |                            |
| aBS Corp |        233 | $32,908.60    |                            |
| aBS Corp |         25 | $9,143.18     |                            |
| aBS Corp |         34 | $11,674.85    |                            |
| aBS Corp |         35 | $11,615.60    |                            |
| aBS Corp |         36 | $14,959.28    |                            |
| aBS Corp |         39 | $35,000.00    |                            |
| aBS Corp |         40 | $100,000.00   |                            |
| aBS Corp |         60 | $55,000.00    |                            |
| aBS Corp |         61 | $250,094.72   |                            |
| aBS Corp |         64 | $925,000.00   |                            |
| aBS Corp |         69 | $400,000.00   |                            |
| aBS Corp |         75 | $14,625.00    |                            |
+----------+------------+---------------+----------------------------+
</code>```

The second table is a reference table:

```<code>+------------+-------------------+--------------------+----------------+
| FiscalYear |     Low Range     |     High Range     |     Result     |
+------------+-------------------+--------------------+----------------+
|       2016 |  (100,000,000.00) |         24,999.00  | 0-24.9K        |
|       2016 |  25,000.00        |         49,999.00  | 25-49.9K       |
|       2016 |  50,000.00        |         99,999.00  | 50-99.9K       |
|       2016 |  100,000.00       |  1,000,000,000.00  | 100K or Higher |
+------------+-------------------+--------------------+----------------+
</code>```

I was hoping to be able to reference the 2nd table in order to update the "Materiality by  fiscal Year" field based on whether or not the value in "Brand Savings" is BETWEEN the "Low Range" and "High Range" fields.  I couldn't figure it out however, and it's driving me crazy.  Instead, I have 4 different queries that will update the "Materiality by Fiscal Year" field (an example of the formula used in the query is below:)

IIf(([Brand Savings]>=0) And ([Brand Savings]<=24999),"$0-24.9K")

Basically what I'm asking is whether or not there's a formula I can use to reference the "Low range" and "High range" fields in the reference table to determine if the "Brand Savings" value from the main table is BETWEEN those two amounts, and if so, populate the "Materiality by Fiscal Year" field with the "Result" field from the Reference table?

Sorry, that's kind of "wordy", just don't know how else to explain it.

Thanks all!

答:
You can use a DLookUp in your update query to look up the appropriate value:

DLookUp("Result", "SecondTable", CDbl([Brand Savings]) & " Between [Low Range] And [High Range]")

For SELECT queries, you could also use a join, but I doubt if that would work in an UPDATE query.

ContentLicense: CC BY-SA 3.0

Body:
I'm hoping someone can help me out.  I was hoping I could do an update query in MS Access that will update a field I have called "Materiality by Fiscal Year", based on whether or not another field "Brand Savings" is equal to or between a set of dollar ranges I have in another table.  The first table is as follows, which is the primary table:

+----------+------------+---------------+----------------------------+
|  Brand   | Project ID | Brand Savings | Materiality by Fiscal Year |
+----------+------------+---------------+----------------------------+
| aBS Corp |        121 | $110,000.00   |                            |
| aBS Corp |        151 | $17,640.67    |                            |
| aBS Corp |        152 | $5,682.37     |                            |
| aBS Corp |        154 | $564,669.58   |                            |
| aBS Corp |        157 | $5,097.00     |                            |
| aBS Corp |        159 | $33,798.00    |                            |
| aBS Corp |        190 | $200,000.00   |                            |
| aBS Corp |        193 | $250,000.00   |                            |
| aBS Corp |        194 | $366,666.67   |                            |
| aBS Corp |        197 | $90,799.00    |                            |
| aBS Corp |         20 | $14,000.00    |                            |
| aBS Corp |        219 | $2,800.00     |                            |
| aBS Corp |        222 | $132.58       |                            |
| aBS Corp |         23 | $2,068.30     |                            |
| aBS Corp |        233 | $32,908.60    |                            |
| aBS Corp |         25 | $9,143.18     |                            |
| aBS Corp |         34 | $11,674.85    |                            |
| aBS Corp |         35 | $11,615.60    |                            |
| aBS Corp |         36 | $14,959.28    |                            |
| aBS Corp |         39 | $35,000.00    |                            |
| aBS Corp |         40 | $100,000.00   |                            |
| aBS Corp |         60 | $55,000.00    |                            |
| aBS Corp |         61 | $250,094.72   |                            |
| aBS Corp |         64 | $925,000.00   |                            |
| aBS Corp |         69 | $400,000.00   |                            |
| aBS Corp |         75 | $14,625.00    |                            |
+----------+------------+---------------+----------------------------+

The second table is a reference table:

+------------+-------------------+--------------------+----------------+
| FiscalYear |     Low Range     |     High Range     |     Result     |
+------------+-------------------+--------------------+----------------+
|       2016 |  (100,000,000.00) |         24,999.00  | 0-24.9K        |
|       2016 |  25,000.00        |         49,999.00  | 25-49.9K       |
|       2016 |  50,000.00        |         99,999.00  | 50-99.9K       |
|       2016 |  100,000.00       |  1,000,000,000.00  | 100K or Higher |
+------------+-------------------+--------------------+----------------+

I was hoping to be able to reference the 2nd table in order to update the "Materiality by  fiscal Year" field based on whether or not the value in "Brand Savings" is BETWEEN the "Low Range" and "High Range" fields.  I couldn't figure it out however, and it's driving me crazy.  Instead, I have 4 different queries that will update the "Materiality by Fiscal Year" field (an example of the formula used in the query is below:)

IIf(([Brand Savings]>=0) And ([Brand Savings]<=24999),"$0-24.9K")

Basically what I'm asking is whether or not there's a formula I can use to reference the "Low range" and "High range" fields in the reference table to determine if the "Brand Savings" value from the main table is BETWEEN those two amounts, and if so, populate the "Materiality by Fiscal Year" field with the "Result" field from the Reference table?

Sorry, that's kind of "wordy", just don't know how else to explain it.

Thanks all!


问:
Avoid changes on FK table Django Models 1.11
This is the way that I modeled my shopping cart.
I have a Product table, a "temporary" cart which is deleted after the order is complete. And my CompleteOrders list, which contains the data of each order of the user.
The thing is that when I modify the price or the name of my product, it changes on CompleteOrders list too. Is there a way to avoid this?

```<code>class Product(models.Model):
    name = models.CharField(max_length=30)
    price = models.IntegerField()

class Cart(models.Model):
    product = models.ForeignKey(Product)

class CompleteOrders(models.Model):
    product = models.ForeignKey(Product)
</code>```

My approach was to store in CompleteOrder the info of the product instead of using the FK but I didn't see that very optimal.

Thanks in advance.

答:
Foreign key refers to another table and it will always show current data. You cannot avoid this. There is no other way than storing product data at the time order is completed.

I usually use JSON data type to store such information.

Body:
This is the way that I modeled my shopping cart.
I have a Product table, a "temporary" cart which is deleted after the order is complete. And my CompleteOrders list, which contains the data of each order of the user.
The thing is that when I modify the price or the name of my product, it changes on CompleteOrders list too. Is there a way to avoid this?

class Product(models.Model):
    name = models.CharField(max_length=30)
    price = models.IntegerField()

class Cart(models.Model):
    product = models.ForeignKey(Product)

class CompleteOrders(models.Model):
    product = models.ForeignKey(Product)

My approach was to store in CompleteOrder the info of the product instead of using the FK but I didn't see that very optimal.

Thanks in advance.


问:
new ActionResult that can render the view generated and send contents via email
I was wondering if it were possible to write a file FileResult that worked something like this.

```<code>public ActionResult Generate(int id)
{
    //Fill Model
    string ViewName = "template1";

    return new FileResult(ViewName, @"c:\save"+ id +".txt");
}
</code>```

where it would take the model, and combine it with the view to give you the output that would normally be displayed to the screen but instead just save it with the filename specified.

Note: This file will be saved on the webserver

答: Yes, it's possible, but you don't use FileResult. If you set the content type and disposition headers to something unknown, the browser will prompt the user to save the result.</p>

OwnerDisplayName: Schotime

Body:
I was wondering if it were possible to write a file FileResult that worked something like this.

public ActionResult Generate(int id)
{
    //Fill Model
    string ViewName = "template1";

    return new FileResult(ViewName, @"c:\save"+ id +".txt");
}

where it would take the model, and combine it with the view to give you the output that would normally be displayed to the screen but instead just save it with the filename specified.

Note: This file will be saved on the webserver

LastEditorDisplayName: Schotime

OwnerDisplayName: Craig Stuntz

ContentLicense: CC BY-SA 2.5


问:
uninstall dialogs
I am composing a setup project in VS2010 . I want to add a dialog with checkbox for the user to specify if he wants to delete the database or not. But I can't figure out how to do it: the user interface doesn't represent the uninstall dialogs on the "view dialogs" form. So I can show a messagebox instead, but then there is another problem: how can a person specify whether the database should be deleted or not if the uninstaller is launched in a quited mode? In that case some parameters should be passed to the setup project somehow. Got any thoughts?</p>

答:
Right now I am trying to use Orca, it is a part of Windows Installer SDK.
http://www.microsoft.com/downloads/details.aspx?FamilyId=A55B6B43-E24F-4EA3-A93E-40C0EC4F68E5&displaylang=en
It might solve my problem.</p>

Title: uninstall dialogs


问:
How to pass js scripts to specific page type?
Currently I have all page scripts in site.js and passing it through apostrophe-assets like this:

```<code>module.exports = {
  stylesheets: [...],
  scripts: [
    {
      name: 'site'
    }
]
</code>```

How can I pass some server/client-side js code to a specific page type?

答:
Currently Apostrophe doesn't specifically provide a way to do this. Surprisingly, it's not a terrible idea to just add a script tag to the page template. You can load it at the end of the body tag by overriding the  extraBody nunjucks block in your page template:

```<code>{% block extraBody %}
  <script src="/modules/my-module/js/special-page.js"></script>
{% endblock %}
</code>```

Due to the way Apostrophe provides symbolic links to each module's assets, this path will find the file here:

lib/modules/my-module/js/special-page.js

The reason this is not terrible is this: the .js assets you push to Apostrophe are minified and sent together on every page... which means the browser caches them. But if there are separate asset "scenes" for every page type, then minifying them all together would require a separate minified "big fat .js file" for each page type, and there would be no caching benefit when moving between pages of different types.

So allowing Apostrophe to minify the stuff you always/nearly always use, and separately sending the stuff you rarely use, turns out to be a win a lot of the time. You keep the universal stuff from your cache and get just a little bit of custom stuff for the specific page type.

Of course if you write a script tag like this Apostrophe doesn't minify the .js file for you. You can address that by using your own gulp workflow to build the .js file, which is not uncommon anyway for project specific code if you're eager to use ES6 features cross-browser.

See also:

Incorporating gulp to compile js in apostrophe?

But consider this... once you realize the user is going to visit several types of pages in a site visit, it's not a big step to deciding you should just push it all together and let Apostrophe minify it all together. The exception should be when the special payload for one page type is really, really large and the user probably won't visit that page in most site visits. In that edge case, we've been known to follow this technique too. Apostrophe itself relies on ckeditor's dynamic loader to avoid pushing all of the ckeditor rich text editor code on every login.

Body:
Currently I have all page scripts in site.js and passing it through apostrophe-assets like this:

module.exports = {
  stylesheets: [...],
  scripts: [
    {
      name: 'site'
    }
]

How can I pass some server/client-side js code to a specific page type?

Body:
Currently Apostrophe doesn't specifically provide a way to do this. Surprisingly, it's not a terrible idea to just add a script tag to the page template. You can load it at the end of the body tag by overriding the  extraBody nunjucks block in your page template:

{% block extraBody %}
  <script src="/modules/my-module/js/special-page.js"></script>
{% endblock %}

Due to the way Apostrophe provides symbolic links to each module's assets, this path will find the file here:

lib/modules/my-module/js/special-page.js

The reason this is not terrible is this: the .js assets you push to Apostrophe are minified and sent together on every page... which means the browser caches them. But if there are separate asset "scenes" for every page type, then minifying them all together would require a separate minified "big fat .js file" for each page type, and there would be no caching benefit when moving between pages of different types.

So allowing Apostrophe to minify the stuff you always/nearly always use, and separately sending the stuff you rarely use, turns out to be a win a lot of the time. You keep the universal stuff from your cache and get just a little bit of custom stuff for the specific page type.

Of course if you write a script tag like this Apostrophe doesn't minify the .js file for you. You can address that by using your own gulp workflow to build the .js file, which is not uncommon anyway for project specific code if you're eager to use ES6 features cross-browser.

See also:

Incorporating gulp to compile js in apostrophe?

But consider this... once you realize the user is going to visit several types of pages in a site visit, it's not a big step to deciding you should just push it all together and let Apostrophe minify it all together. The exception should be when the special payload for one page type is really, really large and the user probably won't visit that page in most site visits. In that edge case, we've been known to follow this technique too. Apostrophe itself relies on ckeditor's dynamic loader to avoid pushing all of the ckeditor rich text editor code on every login.


问:
C#: Remove Excess Text From String
Okay, so after looking around here on SO, I have found a solution that meets about 95% of my requirement, although I believe it may need to be redone at this point.

ISSUE

Say I have a value range supplied as "1000 - 1009 ABC1 ABC SOMETHING ELSE" where I just need the 1000 - 1009 part. I need to be able to remove excess characters from the string supplied, even if they truly are accepted characters, but only if they are part of secondary strings with text. (Sorry if that description seems odd, my mind isn't full power today.)

CURRENT SOLUTION

I currently have a simple method utilizing Linq to return only accepted characters, however this will return "1000 - 10091" which is not the range I am needing. I've thought about looping through the strings individual characters and comparing to previous characters as I go using IsDigit and IsLetter to my advantage, but then comes the issue of replacing the unacceptable characters or removing them. I think if I gave it a day or two I could figure it out with a clear mind, but it needs to be done by the end of the day, and I am banging my head against the keyboard.

```<code>void RemoveExcessText(ref string val) {
    string allowedChars = "0123456789-+>";
    val = new string(val.Where(c => allowedChars.Contains(c)).ToArray());
}

// Alternatively?
char previousChar = ' ';
for (int i = 0; i < val.Length; i++) {
    if (char.IsLetter(val[i])) {
        previousChar = val[i];
        val.Remove(i, 1);
    } else if (char.IsDigit(val[i])) {
        if (char.IsLetter(previousChar)) {
            val.Remove(i, 1);
        }
    }
}
</code>```

But how do I calculate white space and leave in the +, -, and > charactrers? I am losing my mind on this one today.

答:
Why not use a regular expression?

```<code>Regex.Match("1000 - 1009 ABC1 ABC SOMETHING ELSE", @"^(\d+)([\s\-]+)(\d+)");
</code>```

Should give you what you want

I made a fiddle

Title: C#: Remove Excess Text From String

Body:
Okay, so after looking around here on SO, I have found a solution that meets about 95% of my requirement, although I believe it may need to be redone at this point.

ISSUE

Say I have a value range supplied as "1000 - 1009 ABC1 ABC SOMETHING ELSE" where I just need the 1000 - 1009 part. I need to be able to remove excess characters from the string supplied, even if they truly are accepted characters, but only if they are part of secondary strings with text. (Sorry if that description seems odd, my mind isn't full power today.)

CURRENT SOLUTION

I currently have a simple method utilizing Linq to return only accepted characters, however this will return "1000 - 10091" which is not the range I am needing. I've thought about looping through the strings individual characters and comparing to previous characters as I go using IsDigit and IsLetter to my advantage, but then comes the issue of replacing the unacceptable characters or removing them. I think if I gave it a day or two I could figure it out with a clear mind, but it needs to be done by the end of the day, and I am banging my head against the keyboard.

void RemoveExcessText(ref string val) {
    string allowedChars = "0123456789-+>";
    val = new string(val.Where(c => allowedChars.Contains(c)).ToArray());
}

// Alternatively?
char previousChar = ' ';
for (int i = 0; i < val.Length; i++) {
    if (char.IsLetter(val[i])) {
        previousChar = val[i];
        val.Remove(i, 1);
    } else if (char.IsDigit(val[i])) {
        if (char.IsLetter(previousChar)) {
            val.Remove(i, 1);
        }
    }
}

But how do I calculate white space and leave in the +, -, and > charactrers? I am losing my mind on this one today.

Body:
Why not use a regular expression?

Regex.Match("1000 - 1009 ABC1 ABC SOMETHING ELSE", @"^(\d+)([\s\-]+)(\d+)");

Should give you what you want

I made a fiddle


问:
getting data from 2 tables in inner join
I am  not new in inner join but i don't know why i am getting data from two tables

Look i have some tables

Table One

```<code>select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionD
</code>```

TransactionMId    ModelNumber EmeiNo  Color

c174f2c0-72f4-4746-b83d-21ffca6a5a61  620G    10001   grey

c174f2c0-72f4-4746-b83d-21ffca6a5a61  ONE 10005   black

4fa11531-886a-4d15-af5c-7355cc3648f5  620G    10001   grey

Table Two

```<code>select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionP
</code>```

TransactionMId    ModelNumber EmeiNo  Color

c174f2c0-72f4-4746-b83d-21ffca6a5a61  620G    10001   grey

c174f2c0-72f4-4746-b83d-21ffca6a5a61  ONE 10005   black

table three

```<code>select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionS
</code>```

TransactionMId    ModelNumber EmeiNo  Color

4fa11531-886a-4d15-af5c-7355cc3648f5  620G    10001   grey

now i want to show the data which is in table one and two but not in table three

Here is my Inner Join

```<code>SELECT TD.BrandId,TD.Color,TD.EmeiNo FROM dbo.tblTransactionD AS TD
INNER JOIN dbo.tblTransactionP AS TP
ON
TP.transactionMId=TD.transactionMId
INNER JOIN dbo.tblTransactionS AS TS
ON
TP.EmeiNo != TS.EmeiNo
</code>```

but the executed result is showing data like this

```<code>BrandId Color   EmeiNo
1   grey    10001
1   black   10005
</code>```

the record of 10001 should not be shown in the query because it is in table three

what is wrong in my inner join

答:
Following query will work:</p>

```<code>SELECT TD.BrandId,TD.Color,TD.EmeiNo FROM dbo.tblTransactionD AS TD
INNER JOIN dbo.tblTransactionP AS TP
ON
TP.transactionMId=TD.transactionMId
where TP.EmeiNo not in (select distinct EmeiNo from dbo.tblTransactionS);
</code>```

Body:
I am  not new in inner join but i don't know why i am getting data from two tables

Look i have some tables

Table One

select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionD

TransactionMId    ModelNumber EmeiNo  Color

c174f2c0-72f4-4746-b83d-21ffca6a5a61  620G    10001   grey

c174f2c0-72f4-4746-b83d-21ffca6a5a61  ONE 10005   black

4fa11531-886a-4d15-af5c-7355cc3648f5  620G    10001   grey

Table Two

select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionP

TransactionMId    ModelNumber EmeiNo  Color

c174f2c0-72f4-4746-b83d-21ffca6a5a61  620G    10001   grey

c174f2c0-72f4-4746-b83d-21ffca6a5a61  ONE 10005   black

table three

select TransactionMId,ModelNumber,EmeiNo,Color from tblTransactionS

TransactionMId    ModelNumber EmeiNo  Color

4fa11531-886a-4d15-af5c-7355cc3648f5  620G    10001   grey

now i want to show the data which is in table one and two but not in table three

Here is my Inner Join

SELECT TD.BrandId,TD.Color,TD.EmeiNo FROM dbo.tblTransactionD AS TD
INNER JOIN dbo.tblTransactionP AS TP
ON
TP.transactionMId=TD.transactionMId
INNER JOIN dbo.tblTransactionS AS TS
ON
TP.EmeiNo != TS.EmeiNo

but the executed result is showing data like this

BrandId Color   EmeiNo
1   grey    10001
1   black   10005

the record of 10001 should not be shown in the query because it is in table three

what is wrong in my inner join

Body:
Following query will work:

SELECT TD.BrandId,TD.Color,TD.EmeiNo FROM dbo.tblTransactionD AS TD
INNER JOIN dbo.tblTransactionP AS TP
ON
TP.transactionMId=TD.transactionMId
where TP.EmeiNo not in (select distinct EmeiNo from dbo.tblTransactionS);


问:
Generating service class from discovery file of iOS
I have a discovery file in rpc format but using a new generator I can't generate it.

How can I generate the file for iOS using new service generator?

答: You need to get a REST format discovery file.</p>


问:
laravel access to model constant in blade
I want to access a class constant in a Blade file without using the full path:

class PaymentMethod extends Model
{
    const PAYPAL_ACCOUNT = 'paypal_account';
    const CREDIT_CARD    = 'credit_card';
}
```
<p>In my blade file this works:</p>
```{{ App\Classes\Models\PaymentMethod::CREDIT_CARD }}
```
<p>...but this throws <code>Class 'PaymentMethod' not found</code></p>
```{{ PaymentMethod::CREDIT_CARD }}
```

Is there a less verbose way to access this constant?

答:
You may use aliases:

in your config\app.php under aliases section :

```<code>aliases => [
     ....
    'PaymentMethod' => App\Classes\Models\PaymentMethod::class
]
</code>```

then use it in your blade file

```<code>{{ PaymentMethod::CREDIT_CARD }}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want to access a class constant in a Blade file without using the full path:

class PaymentMethod extends Model
{
    const PAYPAL_ACCOUNT = 'paypal_account';
    const CREDIT_CARD    = 'credit_card';
}

In my blade file this works:

{{ App\Classes\Models\PaymentMethod::CREDIT_CARD }}

...but this throws Class 'PaymentMethod' not found

{{ PaymentMethod::CREDIT_CARD }}

Is there a less verbose way to access this constant?

Body:
You may use aliases:

in your config\app.php under aliases section :

aliases => [
     ....
    'PaymentMethod' => App\Classes\Models\PaymentMethod::class
]

then use it in your blade file

{{ PaymentMethod::CREDIT_CARD }}


问:
Null Reference Exception from APIGatewayProxyFunction
I finally managed to get my API into a state where I can upload it to AWS Lambda, and then I get the error below whenever I try to use the API Gateway to test it.

{
  "errorType": "AggregateException",
  "errorMessage": "One or more errors occurred. (Object reference not set to an instance of an object.)",
  "stackTrace": [
    "at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)",
    "at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)",
    "at lambda_method(Closure , Stream , Stream , ContextInfo )"
  ],
  "cause": {
    "errorType": "NullReferenceException",
    "errorMessage": "Object reference not set to an instance of an object.",
    "stackTrace": [
      "at Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction.MarshallRequest(InvokeFeatures features, APIGatewayProxyRequest apiGatewayRequest)",
      "at Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction.<FunctionHandlerAsync>d__12.MoveNext()"
    ]
  }
}

```
<p>code:</p>
<pre class="lang-cs prettyprint-override"><code>public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
{
    protected override void Init(IWebHostBuilder builder)
    {
        try
        {
            builder
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .UseApiGateway();
        }
        catch (Exception ex)
        {
            LambdaLogger.Log("Exception throw in LambdaEntryPoint: " + ex);
        }
    }
}
</code>```

I don't get any exceptions logged from my Startup or LambdaEntryPoint. I'm really new to AWS, so I'm not sure what else to check.

Any ideas on this one?

答:
This may be the same issue that someone from AWS has addressed with someone else on the AWS github repo for AWS .NET Lambda integration:
https://github.com/aws/aws-lambda-dotnet/issues/168</p>

Body:
I finally managed to get my API into a state where I can upload it to AWS Lambda, and then I get the error below whenever I try to use the API Gateway to test it.

{
  "errorType": "AggregateException",
  "errorMessage": "One or more errors occurred. (Object reference not set to an instance of an object.)",
  "stackTrace": [
    "at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)",
    "at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)",
    "at lambda_method(Closure , Stream , Stream , ContextInfo )"
  ],
  "cause": {
    "errorType": "NullReferenceException",
    "errorMessage": "Object reference not set to an instance of an object.",
    "stackTrace": [
      "at Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction.MarshallRequest(InvokeFeatures features, APIGatewayProxyRequest apiGatewayRequest)",
      "at Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction.<FunctionHandlerAsync>d__12.MoveNext()"
    ]
  }
}

code:

public class LambdaEntryPoint : Amazon.Lambda.AspNetCoreServer.APIGatewayProxyFunction
{
    protected override void Init(IWebHostBuilder builder)
    {
        try
        {
            builder
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseStartup<Startup>()
                .UseApiGateway();
        }
        catch (Exception ex)
        {
            LambdaLogger.Log("Exception throw in LambdaEntryPoint: " + ex);
        }
    }
}

I don't get any exceptions logged from my Startup or LambdaEntryPoint. I'm really new to AWS, so I'm not sure what else to check.

Any ideas on this one?


问:
Rearranging File Structure Throwing "Element type is invalid" Error
I'm reorganizing the code in my application into a bunch of sub-folders. I'm moving a top-nav component into a subfolder called navigation, this component makes up part of a 'main-nav' container. However, when I shift top-nav into the new folder I start getting the following erro

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.
  Check the render method of TopNavTemplate.

I've been reading through a lot of threads and I can't figure out why shifting the poisition would cause this. I've made sure that the component is pointing to the appropriate imports within the file restructure (these errors get thrown before the current error anyway, so it at least thinks that it's pulling everything in correctly.) I also don't think it's a syntax error in the import statement - I'm connecting the top-nav to my redux store as a default export, and I'm not importing it between {}.

Code for the top-nav export can be found below:

```<code>import React from 'react';
import {Link} from 'react-router-dom';
import ClickOutside from 'react-click-outside';
import {IconSprite} from '../general/icons.js';
import {Modal} from './modal.js';
import {HeaderSelect} from './select.js';
//Import statements that connect TopNav to the redux store
import * as actionCreators from '../../actions/actionCreator.js';
import { bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import logo from '../../logo.svg';

export class TopNavTemplate extends React.Component {
//Render function and a bunch of code goes here
}

function mapStateToProps(state) {
  return {
    selectedTarget: state.selectedTarget,
    availableTargets: state.availableTargets,
    modal: state.modal,
    currentUser: state.currentUser,
    isLoggedIn: state.isLoggedIn
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch);
}

const TopNav = connect(mapStateToProps, mapDispatchToProps)(TopNavTemplate);

export default TopNav;
</code>```

I then import the TopNav into my main-nav layout like so:

```<code>import React from 'react';
import TopNav from '../components/navigation/top-nav.js';
import {SideNav} from '../components/side-nav.js';

export class MainNav extends React.Component{

    render(){
        return ([
            <TopNav />,
            <SideNav />
        ])
    }
  }
</code>```

If I change the import statement to pull from the old version of the file

import TopNav from ../components/top-nav.js

everything works like a charm. I've even tried removing that file to prevent any kind of web-pack confusion but that doesn't seem to the issue. For some reason, moving this file into a different folder is now causing the export to be undefined instead of a proper react component? Feeling very lost.

答: It turned out to be a very stupid mistake - I'd forgotten to save one of the files I was importing while shifting everything around. For some reason this wasn't throwing an error that the import couldn't be found, and was instead causing the wrapped connect component to return as undefined.</p>

Body:
I'm reorganizing the code in my application into a bunch of sub-folders. I'm moving a top-nav component into a subfolder called navigation, this component makes up part of a 'main-nav' container. However, when I shift top-nav into the new folder I start getting the following erro

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.
  Check the render method of TopNavTemplate.

I've been reading through a lot of threads and I can't figure out why shifting the poisition would cause this. I've made sure that the component is pointing to the appropriate imports within the file restructure (these errors get thrown before the current error anyway, so it at least thinks that it's pulling everything in correctly.) I also don't think it's a syntax error in the import statement - I'm connecting the top-nav to my redux store as a default export, and I'm not importing it between {}.

Code for the top-nav export can be found below:

import React from 'react';
import {Link} from 'react-router-dom';
import ClickOutside from 'react-click-outside';
import {IconSprite} from '../general/icons.js';
import {Modal} from './modal.js';
import {HeaderSelect} from './select.js';
//Import statements that connect TopNav to the redux store
import * as actionCreators from '../../actions/actionCreator.js';
import { bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import logo from '../../logo.svg';

export class TopNavTemplate extends React.Component {
//Render function and a bunch of code goes here
}

function mapStateToProps(state) {
  return {
    selectedTarget: state.selectedTarget,
    availableTargets: state.availableTargets,
    modal: state.modal,
    currentUser: state.currentUser,
    isLoggedIn: state.isLoggedIn
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators(actionCreators, dispatch);
}

const TopNav = connect(mapStateToProps, mapDispatchToProps)(TopNavTemplate);

export default TopNav;

I then import the TopNav into my main-nav layout like so:

import React from 'react';
import TopNav from '../components/navigation/top-nav.js';
import {SideNav} from '../components/side-nav.js';

export class MainNav extends React.Component{

    render(){
        return ([
            <TopNav />,
            <SideNav />
        ])
    }
  }

If I change the import statement to pull from the old version of the file

import TopNav from ../components/top-nav.js

everything works like a charm. I've even tried removing that file to prevent any kind of web-pack confusion but that doesn't seem to the issue. For some reason, moving this file into a different folder is now causing the export to be undefined instead of a proper react component? Feeling very lost.


问:
How do I store userinputs that I get from using getch();?
I have this code set up to read what keystrokes the user has inputted. But my next part of my assignment asks me to then output what the user has inputted after the user hits the "~" key. For example if the user inputs ais6d9123~ then output ais6d9123. It is pretty simple, but I am confused on how to capture the keystrokes from getch(). I think I need to use a string and an array, but Im not quite sure how to implement it into what I have so far.</p>

```<code>#include "stdafx.h"
#include <iostream>
#include <string>
#include <iostream>
#include <conio.h>
#include <Windows.h>

using namespace std;

class Node
{
public:
    char c;
    Node* next;
};

void main()
{
    char c;
    c = _getch();

    system("pause");
}
</code>```

答:
```<code>#include <string>
#include <iostream>
#include <conio.h>
#include <Windows.h>
#include <vector>
using namespace std;

class Node
{
public:
    char c;
    Node* next;
};

void main()
{
    char c;
    vector<char> v;
    while ((c=_getch())!='~')
    {
        v.push_back(c);
    }

    for (std::vector<char>::iterator it = v.begin(); it != v.end(); ++it)
        cout <<  *it;
    cout << '\n';

    system("pause");
}
</code>```

Body:
I have this code set up to read what keystrokes the user has inputted. But my next part of my assignment asks me to then output what the user has inputted after the user hits the "~" key. For example if the user inputs ais6d9123~ then output ais6d9123. It is pretty simple, but I am confused on how to capture the keystrokes from getch(). I think I need to use a string and an array, but Im not quite sure how to implement it into what I have so far.

#include "stdafx.h"
#include <iostream>
#include <string>
#include <iostream>
#include <conio.h>
#include <Windows.h>

using namespace std;

class Node
{
public:
    char c;
    Node* next;
};

void main()
{
    char c;
    c = _getch();

    system("pause");
}


问:
ViewModel objects to EF model entities conversion where?
I currently have a repository based on Entity Framework v4 entities (CRUD and GET operations implemented). I'm in the process of creating the corresponding View Models for these entities. Where should I put the conversion/mapping between them? In the controller or modify the repository to perform the mapping in its methods and return back (or accept) the View Model typed objects?

Should I do this

```<code>    public ActionResult Index()
    {
        var person = new PersonRepository().Get();

        var personViewModel = new PersonViewModel();
        personViewModel.InjectFrom(person)
            .InjectFrom<CountryToLookup>(person);

        return View(personViewModel);
    }
</code>```

or this

```<code>     public ActionResult Index()
        {
            var personViewModel = new PersonRepository().Get(); // returns object of type PersonViewModel

// and move this to repository
//            var personViewModel = new PersonViewModel();
//            personViewModel.InjectFrom(person)
//               .InjectFrom<CountryToLookup>(person);

            return View(personViewModel);
        }
</code>```

答:
I would never put transformation code into your repository.

Repositories abstract data access from other concerns. Views abstract

UI formatting from other concerns.

Mixing the two is just throwing all of your careful decoupling away.

The book definition of MVC strongly implies transformation should be done inside the controller:

"The controller receives input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and viewport to perform actions based on that input."

Body:
I currently have a repository based on Entity Framework v4 entities (CRUD and GET operations implemented). I'm in the process of creating the corresponding View Models for these entities. Where should I put the conversion/mapping between them? In the controller or modify the repository to perform the mapping in its methods and return back (or accept) the View Model typed objects?

Should I do this

    public ActionResult Index()
    {
        var person = new PersonRepository().Get();

        var personViewModel = new PersonViewModel();
        personViewModel.InjectFrom(person)
            .InjectFrom<CountryToLookup>(person);

        return View(personViewModel);
    }

or this

     public ActionResult Index()
        {
            var personViewModel = new PersonRepository().Get(); // returns object of type PersonViewModel

// and move this to repository
//            var personViewModel = new PersonViewModel();
//            personViewModel.InjectFrom(person)
//               .InjectFrom<CountryToLookup>(person);

            return View(personViewModel);
        }


问:
Hierarchy Query
Im wondering how can I achieve a successful query for a hierarchy structure i have with my users. I had posted a similar question but the structure changed where now only Executives can have costumers assigned to them.

There are this levels of user:

Director

Manager

Executive

Example table USERS:

```<code>ID    username    privilege   parent_ID
1     Director1   1           null
2     Director2   1           null
3     Manager1    2           1
4     Manager2    2           1
5     Manager3    2           2
6     Executive1  3           3
7     Executive2  3           3
8     Executive3  3           4
9     Executive4  3           4
10    Executive5  3           5
11    Executive6  3           5
</code>```

And they will have their "costumers".

Example table COSTUMERS

```<code>ID  name  User_ID
1   c1    11
2   c2    10
3   c3    10
4   c4    9
5   c5    8
6   c6    7
7   c7    6
</code>```

My problem is into what kind of join should i make so that every user will be able to see only the costumers that they are allowed to, which the rule would be that they can only see costumers from the executives below them, and executives will be able to see their own costumers only.

For example in the diagram above, if users was to check his costumers he should see:

Director1:  C7,C6,C5,C4

Director2:  C3,C2,C1

Manager1:   C7,C6

Manager2:   C5,C4

Manager3: C3,C2,C1

and the executives only would see their own costumers.

答:
The proper way to solve this is with a recursive CTE query, which are coming in MySQL 8.0: https://dev.mysql.com/doc/refman/8.0/en/with.html

```<code>WITH RECURSIVE h AS (
  SELECT ID FROM USERS WHERE ID = ?
  UNION
  SELECT ID FROM USERS AS u JOIN h ON u.parent_ID = h.ID
)
SELECT c.*
FROM h
JOIN COSTUMERS AS c ON c.User_ID = h.ID;
</code>```

If you're still using MySQL 5.7 or older, you need to do it more awkwardly. You have one advantage, that your hierarchy has a fixed maximum depth.

```<code>SELECT c.*
FROM (
    SELECT e.ID FROM USERS AS e
    WHERE e.ID = ?
    UNION ALL
    SELECT e.ID FROM USERS AS e
    JOIN USERS AS m ON e.parent_ID = m.ID
    WHERE m.ID = ?
    UNION ALL
    SELECT e.ID FROM USERS AS e
    JOIN USERS AS m ON e.parent_ID = m.ID
    JOIN USERS AS d ON m.parent_ID = d.ID
    WHERE d.ID = ?
) AS h
JOIN COSTUMERS AS c ON c.User_ID = h.ID;
</code>```

I'm assuming that restructuring your hierarchy into another design like Closure Table isn't a possibility. But if you're interested in other designs, see my answer to What is the most efficient/elegant way to parse a flat table into a tree?

Or my presentation https://www.slideshare.net/billkarwin/models-for-hierarchical-data

Or my book SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.

Title: Hierarchy Query

Body:
Im wondering how can I achieve a successful query for a hierarchy structure i have with my users. I had posted a similar question but the structure changed where now only Executives can have costumers assigned to them.

There are this levels of user:

Director

Manager

Executive

Example table USERS:

ID    username    privilege   parent_ID
1     Director1   1           null
2     Director2   1           null
3     Manager1    2           1
4     Manager2    2           1
5     Manager3    2           2
6     Executive1  3           3
7     Executive2  3           3
8     Executive3  3           4
9     Executive4  3           4
10    Executive5  3           5
11    Executive6  3           5

And they will have their "costumers".

Example table COSTUMERS

ID  name  User_ID
1   c1    11
2   c2    10
3   c3    10
4   c4    9
5   c5    8
6   c6    7
7   c7    6

My problem is into what kind of join should i make so that every user will be able to see only the costumers that they are allowed to, which the rule would be that they can only see costumers from the executives below them, and executives will be able to see their own costumers only.

For example in the diagram above, if users was to check his costumers he should see:

Director1:  C7,C6,C5,C4

Director2:  C3,C2,C1

Manager1:   C7,C6

Manager2:   C5,C4

Manager3: C3,C2,C1

and the executives only would see their own costumers.

Body:
The proper way to solve this is with a recursive CTE query, which are coming in MySQL 8.0: https://dev.mysql.com/doc/refman/8.0/en/with.html

WITH RECURSIVE h AS (
  SELECT ID FROM USERS WHERE ID = ?
  UNION
  SELECT ID FROM USERS AS u JOIN h ON u.parent_ID = h.ID
)
SELECT c.*
FROM h
JOIN COSTUMERS AS c ON c.User_ID = h.ID;

If you're still using MySQL 5.7 or older, you need to do it more awkwardly. You have one advantage, that your hierarchy has a fixed maximum depth.

SELECT c.*
FROM (
    SELECT e.ID FROM USERS AS e
    WHERE e.ID = ?
    UNION ALL
    SELECT e.ID FROM USERS AS e
    JOIN USERS AS m ON e.parent_ID = m.ID
    WHERE m.ID = ?
    UNION ALL
    SELECT e.ID FROM USERS AS e
    JOIN USERS AS m ON e.parent_ID = m.ID
    JOIN USERS AS d ON m.parent_ID = d.ID
    WHERE d.ID = ?
) AS h
JOIN COSTUMERS AS c ON c.User_ID = h.ID;

I'm assuming that restructuring your hierarchy into another design like Closure Table isn't a possibility. But if you're interested in other designs, see my answer to What is the most efficient/elegant way to parse a flat table into a tree?

Or my presentation https://www.slideshare.net/billkarwin/models-for-hierarchical-data

Or my book SQL Antipatterns Volume 1: Avoiding the Pitfalls of Database Programming.


问:
SQL: Replace Some Strings with other String Values in One Column and Write to Temp Table
UPDATE: Followed syntax provided by forum answers ... hit errors

```<code>SELECT * INTO #df_ERA4_a_temp
            CASE WHEN [REQMNT] = 'A' THEN 'ANT'
                 WHEN [REQMNT] = 'A-12' THEN 'A12'
                 WHEN [REQMNT] = 'ADS-B' THEN 'ADSB'
                 ELSE [REQMNT]
            END
    FROM #df_ERA4_a
</code>```

Error: Msg 156, Level 15, State 1, Line 129
Incorrect syntax near the keyword 'CASE'.

I'm trying to clean up text data in one column of my temp table.  Afterwards, I want to write the table into another temp table.

Below is the code I used ... but I'm getting an error.

```<code>SELECT * INTO #test_b
        CASE WHEN [COL] = 'A-12' THEN 'Ant'
             WHEN [COL] = 'A-9' THEN 'Alpha'
             WHEN [COL] = 'AD' THEN 'Aging'
             ELSE WHEN [COL] = 'Art' THEN 'Artwork'
    FROM #test_a
</code>```

The error I received was: Incorrect syntax near the keyword 'CASE'

答:
EDIT: If I understand the problem correctly you want to insert values from test a to test b. If so something like this would be better! You can look at this for help : SELECT INTO TABLE

```<code>INSERT INTO #test_b [test_b.columns]
    SELECT [test_a.columns],
    CASE WHEN [COL] = 'A-12' THEN 'Ant'
        WHEN [COL] = 'A-9' THEN 'Alpha'
        WHEN [COL] = 'AD' THEN 'Aging'
        WHEN [COL] = 'Art' THEN 'Artwork'
        ELSE 'something'
    END
FROM #test_a
</code>```

The ELSE can't precede a WHEN, you just need the ELSE , and you need to close the CASE with a END. You can refer to : SQL CASE

```<code>SELECT * INTO #test_b
    CASE WHEN [COL] = 'A-12' THEN 'Ant'
        WHEN [COL] = 'A-9' THEN 'Alpha'
        WHEN [COL] = 'AD' THEN 'Aging'
        WHEN [COL] = 'Art' THEN 'Artwork'
        ELSE 'something'
    END
    FROM #test_a
</code>```

Body:
UPDATE: Followed syntax provided by forum answers ... hit errors

SELECT * INTO #df_ERA4_a_temp
            CASE WHEN [REQMNT] = 'A' THEN 'ANT'
                 WHEN [REQMNT] = 'A-12' THEN 'A12'
                 WHEN [REQMNT] = 'ADS-B' THEN 'ADSB'
                 ELSE [REQMNT]
            END
    FROM #df_ERA4_a

Error: Msg 156, Level 15, State 1, Line 129
Incorrect syntax near the keyword 'CASE'.

I'm trying to clean up text data in one column of my temp table.  Afterwards, I want to write the table into another temp table.

Below is the code I used ... but I'm getting an error.

SELECT * INTO #test_b
        CASE WHEN [COL] = 'A-12' THEN 'Ant'
             WHEN [COL] = 'A-9' THEN 'Alpha'
             WHEN [COL] = 'AD' THEN 'Aging'
             ELSE WHEN [COL] = 'Art' THEN 'Artwork'
    FROM #test_a

The error I received was: Incorrect syntax near the keyword 'CASE'

Body:
EDIT: If I understand the problem correctly you want to insert values from test a to test b. If so something like this would be better! You can look at this for help : SELECT INTO TABLE

INSERT INTO #test_b [test_b.columns]
    SELECT [test_a.columns],
    CASE WHEN [COL] = 'A-12' THEN 'Ant'
        WHEN [COL] = 'A-9' THEN 'Alpha'
        WHEN [COL] = 'AD' THEN 'Aging'
        WHEN [COL] = 'Art' THEN 'Artwork'
        ELSE 'something'
    END
FROM #test_a

The ELSE can't precede a WHEN, you just need the ELSE , and you need to close the CASE with a END. You can refer to : SQL CASE

SELECT * INTO #test_b
    CASE WHEN [COL] = 'A-12' THEN 'Ant'
        WHEN [COL] = 'A-9' THEN 'Alpha'
        WHEN [COL] = 'AD' THEN 'Aging'
        WHEN [COL] = 'Art' THEN 'Artwork'
        ELSE 'something'
    END
    FROM #test_a


问:
Linking against a local `extern` variable
I reckon this has been probably answered before. Please mark as a duplicate if it has!

I'm having trouble understanding what extern means for local variables (or local functions!). I can't seem to see how it is functionally different from a static local variable... For instance:

```<code>int foo(void) {
   extern int i;
   return i++;
}

int bar(void) {
   static int i;
   return i++;
}
</code>```

AFAICT, foo and bar are the same. The difference according to the C99 spec is that i in foo should have external linkage compared to the i in bar. That said, I can't think of any way to exploit that external linkage - since it is a local variable, it isn't accessible outside of foo, let alone outside of the file.

I'm sure I'm missing something here - what is it?

EDIT

Thank you to everyone who pointed out that I'm missing a type on extern and static. You are quite correct. As a frequent answerer on SO, I now understand the frustration of the barrage of down votes that follow this sort of oversight.

答:
For starters this function definition and the variable declaration

```<code>int foo() {
       ^^^
   extern i;
   ^^^^^^^^^
   return i++;
}
</code>```

are invalid because there is absent a parameter list and a type specifier for the variable i.

It should be written like

```<code>int foo( void ) {
         ^^^^
   extern int i;
   ^^^^^^^^^
   return i++;
}
</code>```

According to the C Standard (6.2.2 Linkages of identifiers)

4 For an identifier declared with the storage-class specifier extern
  in a scope in which a prior declaration of that identifier is
  visible,31) if the prior declaration specifies internal or external
  linkage, the linkage of the identifier at the later declaration is the
  same as the linkage specified at the prior declaration. If no prior
  declaration is visible, or if the prior declaration specifies no
  linkage, then the identifier has external linkage.

So it is not necessary that the variable i declared in the function has external linkage. For example in this demonstrative program the variable i declared within the function has internal linkage.

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

static int i;

int foo( void )
{
    extern int i;
    return i++;
}

int main(void)
{
    printf( "f() = %d\n", foo() );
    printf( "i = %d\n", i );

    return 0;
}
</code>```

In the function bar that should be defined like

```<code>int bar( void ) {
   static int i;
   return i++;
}
</code>```

the variable i does not have a linkage but it has the static storage duration.

Body:
I reckon this has been probably answered before. Please mark as a duplicate if it has!

I'm having trouble understanding what extern means for local variables (or local functions!). I can't seem to see how it is functionally different from a static local variable... For instance:

int foo(void) {
   extern int i;
   return i++;
}

int bar(void) {
   static int i;
   return i++;
}

AFAICT, foo and bar are the same. The difference according to the C99 spec is that i in foo should have external linkage compared to the i in bar. That said, I can't think of any way to exploit that external linkage - since it is a local variable, it isn't accessible outside of foo, let alone outside of the file.

I'm sure I'm missing something here - what is it?

EDIT

Thank you to everyone who pointed out that I'm missing a type on extern and static. You are quite correct. As a frequent answerer on SO, I now understand the frustration of the barrage of down votes that follow this sort of oversight.

Body:
For starters this function definition and the variable declaration

int foo() {
       ^^^
   extern i;
   ^^^^^^^^^
   return i++;
}

are invalid because there is absent a parameter list and a type specifier for the variable i.

It should be written like

int foo( void ) {
         ^^^^
   extern int i;
   ^^^^^^^^^
   return i++;
}

According to the C Standard (6.2.2 Linkages of identifiers)

4 For an identifier declared with the storage-class specifier extern
  in a scope in which a prior declaration of that identifier is
  visible,31) if the prior declaration specifies internal or external
  linkage, the linkage of the identifier at the later declaration is the
  same as the linkage specified at the prior declaration. If no prior
  declaration is visible, or if the prior declaration specifies no
  linkage, then the identifier has external linkage.

So it is not necessary that the variable i declared in the function has external linkage. For example in this demonstrative program the variable i declared within the function has internal linkage.

#include <stdio.h>

static int i;

int foo( void )
{
    extern int i;
    return i++;
}

int main(void)
{
    printf( "f() = %d\n", foo() );
    printf( "i = %d\n", i );

    return 0;
}

In the function bar that should be defined like

int bar( void ) {
   static int i;
   return i++;
}

the variable i does not have a linkage but it has the static storage duration.


问:
Merge multiple variables in R
I have a dataset such that the same variable is contained in difference columns for each subject. I want to merge them to the same columns.

E.g.:, I have this dataframe, and there are three DVs, but they are in different columns (A,B,C) for different subjects.

```<code>data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"))
</code>```

How can I merge them to just two columns? so the result is:

```<code>data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"), DV_1 = c(1,4,5), DV_2 = c(3,3,5))
</code>```

答:
This will work, though not a very elegant solution when you could use the coalesce function already mentioned:</p>

```<code>library(dplyr)
test <- df %>% group_by(ID) %>% summarise(DV1 = ifelse(!is.na(DV1_A),paste(DV1_A),ifelse(!is.na(DV1_B),paste(DV1_B),ifelse(!is.na(DV1_C),paste(DV1_C),""))), DV2 = ifelse(!is.na(DV2_A),paste(DV2_A),ifelse(!is.na(DV2_B),paste(DV2_B),ifelse(!is.na(DV2_C),paste(DV2_C),""))))
</code>```

Title: Merge multiple variables in R

Body:
I have a dataset such that the same variable is contained in difference columns for each subject. I want to merge them to the same columns.

E.g.:, I have this dataframe, and there are three DVs, but they are in different columns (A,B,C) for different subjects.

data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"))

How can I merge them to just two columns? so the result is:

data.frame(ID = c(1,2,3), DV1_A=c(1,NA,NA), DV1_B= c(NA,4,NA), DV1_C = c(NA,NA,5), DV2_A=c(3,NA,NA), DV2_B=c(NA,3,NA), DV2_C=c(NA,NA,5), FACT = c("A","B","C"), DV_1 = c(1,4,5), DV_2 = c(3,3,5))

Body:
This will work, though not a very elegant solution when you could use the coalesce function already mentioned:

library(dplyr)
test <- df %>% group_by(ID) %>% summarise(DV1 = ifelse(!is.na(DV1_A),paste(DV1_A),ifelse(!is.na(DV1_B),paste(DV1_B),ifelse(!is.na(DV1_C),paste(DV1_C),""))), DV2 = ifelse(!is.na(DV2_A),paste(DV2_A),ifelse(!is.na(DV2_B),paste(DV2_B),ifelse(!is.na(DV2_C),paste(DV2_C),""))))


问:
How to add Google Maps Autocomplete search box?
I am trying to add a Google autocomplete search box to a website so that users can search for an address as easily as possible.

My problem is, I have looked a numerous questions on here as well as the Google Maps Javascript API v3 regarding this and some tutorials yet they all bundle together the autocomplete functionality with mapping it on an embedded Google map.

I don't need to map the location visually, I just need the autocomplete box for now, unfortunately I cannot work out which parts of the API are relevant to this and every example I have looked at includes plenty of JS for mapping.

How can I ONLY add the autocomplete input functionality?

答:
I am using jQuery here to get the entered text and wrapping all code in $(document).ready(). Make sure you have your API key ready for Google Places API Web service. Replace it in the below script file.

```<code><input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>
</code>```

Use script file to load the autocomplete class. Your scripts.js file will look something like this.

```<code>    // scripts.js custom js file
$(document).ready(function () {
   google.maps.event.addDomListener(window, 'load', initialize);
});

function initialize() {
    var input = document.getElementById('location');
    var autocomplete = new google.maps.places.Autocomplete(input);
}
</code>```

Body:
I am using jQuery here to get the entered text and wrapping all code in $(document).ready(). Make sure you have your API key ready for Google Places API Web service. Replace it in the below script file.

<input type="text" id="location">
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=[YOUR_KEY_HERE]&libraries=places"></script>
<script src="javascripts/scripts.js"></scripts>

Use script file to load the autocomplete class. Your scripts.js file will look something like this.

    // scripts.js custom js file
$(document).ready(function () {
   google.maps.event.addDomListener(window, 'load', initialize);
});

function initialize() {
    var input = document.getElementById('location');
    var autocomplete = new google.maps.places.Autocomplete(input);
}


问:
Memory leaks caused due to CoreFoundation Framework
I am developing an iPhone application which mainly makes use of the Address Book and database. After fetching about 3000 contacts from the address book, I am attaching string tags to the contacts (5 for each). I am saving my tags in the database.

For Load testing purpose i have added 10,000 tags to the App. But during the load testing of my application, I observed some memory leaks which were not related to the Application code but represents a set of Instruction sets. Also Instruments showed Foundation as the  responsible library for the Leak (Extensive use of NSString,NSDictionary,NSArray which belongs to the Foundation framework). My application crashes after 10 - 15 mins of usage.The Crash report mentions, application crashed due to low memory.

Memory profiling using CLANG shows zero leaks. How do i solve these memory leaks?
Are these leaks the real culprit behind the crash? Are there any other tools available to check memory leaks?

答:
clang is not a leak checker. It only detects a small subset of issues.

For memory leak debugging you should focus on Instruments, specifically the Object Allocation and Leaks instruments. Be sure to understand the difference between leaks and other source of high memory usage though.

Once you've determined that objects are leaking, use Instruments to examine their allocation stack trace (so you can tell what object it is), and their retain/release history.

If it's not a leak, then I suggest investigating the instructions here:http://www.friday.com/bbum/2010/10/17/when-is-a-leak-not-a-leak-using-heapshot-analysis-to-find-undesirable-memory-growth/


问:
Processing files with ImageIO from a ZipFile
I got an error trying to read image files from a zipfile using imageio:

```<code>import zipfile
import glob
import imageio
from os.path import splitext

    for database in glob.iglob('Datasets/*.zip'):
        print(database)
        zf = zipfile.ZipFile(database, 'r')
        for file in zf.namelist():
            basename,extension = splitext(file)
            if extension == '.png':
                img = imageio.imread(file)
                print(img.shape, end='')
</code>```

Here is the traceback:

```<code>Datasets/first.zip
Traceback (most recent call last):
  File "testZip.py", line 12, in <module>
    img = imageio.imread(file)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/functions.py", line 200, in imread
    reader = read(uri, format, 'i', **kwargs)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/functions.py", line 117, in get_reader
    request = Request(uri, 'r' + mode, **kwargs)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/request.py", line 120, in __init__
    self._parse_uri(uri)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/request.py", line 252, in _parse_uri
    raise IOError("No such file: '%s'" % fn)
OSError: No such file: 'first/image_7395.png'
[Finished in 0.2s with exit code 1]
</code>```

答:
You're trying to open the image from the ZIP by name. imageio doesn't know how to do that. It assumes you gave it a real file path. You need to give it a file object by first opening the file in the zip. You can also extract it first like @randomdude999 suggested.

```<code>for file in zf.namelist():
    basename,extension = splitext(file)
    if extension == '.png':
        img = imageio.imread(zf.open(file))
        print(img.shape, end='')
</code>```

Body:
I got an error trying to read image files from a zipfile using imageio:

import zipfile
import glob
import imageio
from os.path import splitext

    for database in glob.iglob('Datasets/*.zip'):
        print(database)
        zf = zipfile.ZipFile(database, 'r')
        for file in zf.namelist():
            basename,extension = splitext(file)
            if extension == '.png':
                img = imageio.imread(file)
                print(img.shape, end='')

Here is the traceback:

Datasets/first.zip
Traceback (most recent call last):
  File "testZip.py", line 12, in <module>
    img = imageio.imread(file)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/functions.py", line 200, in imread
    reader = read(uri, format, 'i', **kwargs)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/functions.py", line 117, in get_reader
    request = Request(uri, 'r' + mode, **kwargs)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/request.py", line 120, in __init__
    self._parse_uri(uri)
  File "/usr/local/anaconda3/lib/python3.6/site-packages/imageio/core/request.py", line 252, in _parse_uri
    raise IOError("No such file: '%s'" % fn)
OSError: No such file: 'first/image_7395.png'
[Finished in 0.2s with exit code 1]

Body:
You're trying to open the image from the ZIP by name. imageio doesn't know how to do that. It assumes you gave it a real file path. You need to give it a file object by first opening the file in the zip. You can also extract it first like @randomdude999 suggested.

for file in zf.namelist():
    basename,extension = splitext(file)
    if extension == '.png':
        img = imageio.imread(zf.open(file))
        print(img.shape, end='')


问:
Filter an aggregate by string length
I have performed the following query:

```<code>db.Indiv2.aggregate(
{$unwind: '$conso'},
{$group: {_id: {conso:'$conso.nom_commercial', region:"$region"}, sum:
{$sum: 1}}},
{$sort : {sum : -1}},
{$group: {
_id: "$_id.region",
"conso": {
    $first: "$_id.conso"
},
"sum": {
    $first: "$sum"
},
}},
{$sort : {_id : 1}}
);
</code>```

which returns the highest consumed food by region in the following format:

```<code>    {
        "_id" : {
            "conso" : "x",
            "region" : 1
        },
        "sum" : 73226.0
    },
    {
        "_id" : {
            "conso" : "x",
            "region" : 8
        },
        "sum" : 25683.0
    },
    {
        "_id" : {
            "conso" : "grandlait demi �cr�m� uht",
            "region" : 1
        },
        "sum" : 251.0
    }
</code>```

However, a lot of foods do not have names. Such items are named "x" (example above). I would like to filter my query to exclude such items. I am looking for an equivalent of a filter which can either filter strings which length are below 2 characters or filter the string "x".

答:
You could just capture the conso length and filter.   Given the or condition described above, we end up with this:

```<code>// previous pipeline here, then:
{$addFields: {slen: {$strLenBytes: "$_id.conso"}}}
,{$match: {$or: [ {"_id.conso": {$ne: "x"}}, {slen: {$gt: 1}} ] }}
</code>```

Title: Filter an aggregate by string length

Body:
I have performed the following query:

db.Indiv2.aggregate(
{$unwind: '$conso'},
{$group: {_id: {conso:'$conso.nom_commercial', region:"$region"}, sum:
{$sum: 1}}},
{$sort : {sum : -1}},
{$group: {
_id: "$_id.region",
"conso": {
    $first: "$_id.conso"
},
"sum": {
    $first: "$sum"
},
}},
{$sort : {_id : 1}}
);

which returns the highest consumed food by region in the following format:

    {
        "_id" : {
            "conso" : "x",
            "region" : 1
        },
        "sum" : 73226.0
    },
    {
        "_id" : {
            "conso" : "x",
            "region" : 8
        },
        "sum" : 25683.0
    },
    {
        "_id" : {
            "conso" : "grandlait demi �cr�m� uht",
            "region" : 1
        },
        "sum" : 251.0
    }

However, a lot of foods do not have names. Such items are named "x" (example above). I would like to filter my query to exclude such items. I am looking for an equivalent of a filter which can either filter strings which length are below 2 characters or filter the string "x".

Body:
You could just capture the conso length and filter.   Given the or condition described above, we end up with this:

// previous pipeline here, then:
{$addFields: {slen: {$strLenBytes: "$_id.conso"}}}
,{$match: {$or: [ {"_id.conso": {$ne: "x"}}, {slen: {$gt: 1}} ] }}


问:
Print to console from application extension
I've been playing around with the new custom keyboard application extension API in iOS 8, using Swift as my language of choice. One thing I've noticed, however, is that println doesn't seem to ever print any output to the console, presumably because those statements are being executed in an application extension rather than the containing app. Has anyone found a way to print statements to the console from within an application extension?

答:
As of iOS 10, extensions don't log to console by default. To enable console logging for your extension:

Select your extension target in the Xcode target popup

Select Product menu > Scheme > Edit Scheme (or Cmd <)

In the Run phase under environment variables, add name:OS_ACTIVITY_MODE value: disable


问:
angular watch not fired
There is 1 angular app, with 1 parent controller, and a child controller.
In the child, there is 1 $watch WATCH-CHILD for OBJ-CHILD, which triggers an $emit.
In the parent, there is a listener for the $emit, we'll call it ON-LISTENER, and a $watch WATCH-PARENT for OBJ-PARENT (which uses true as the 3rd argument).

When the child's OBJ-CHILD is changed, it triggers WATCH-CHILD, which triggers the $emit.
The parent listener ON-LISTENER is fired, and changes OBJ-PARENT. It also sets some $location properties.
The $watch WATCH-PARENT for OBJ-PARENT is never fired (even though the value has changed), as well as the properties set on $location not changed in the browser URL (I know they are indeed changed inside the JavaScript, cause I print them).

In order to make sure that ON-LISTENER is called within a $digest, I tried to call $digest at the end of ON-LISTENER, and got the expected exception.

Any idea if I'm doing something wrong? I expect the changes that occur in ON-LISTENER to trigger WATCH-PARENT and browser URL change.

I will try to reproduce on jsfiddle and edit this post if successful.

The code looks like:

CHILD:

```<code>$scope.$watch('vars.model', function(newValue, oldValue) {
  console.log('model changed');
  $scope.$emit('highlightChange', newValue);
}, true);
</code>```

PARENT:

```<code>$scope.$watch('vars.model.highlight', function(newValue, oldValue) {
  console.log('highlight changed');
}, true);

$scope.$on('highlightChange', function(event, value) {
  console.log('listener', $scope.vars.model.highlight.categoryId, value.categoryId);
  $location.search('category-id', value.categoryId);
  $scope.vars.model.highlight.categoryId = value.categoryId;
}
</code>```

答:
Thanks for the help. I found out that my event originated from a manual call to $scope.$digest() due to the originating event being triggered from a daterangepicker 'apply.daterangepicker' event.
When I changed that to $scope.$apply, the problem seemed to go away.
I can assume from that, that $apply() is the one in charge of keep calling $watch as long as there are changes, and that $digest() doesn't do so.

For future reference, I placed the problem here:
https://plnkr.co/edit/ItkALhw16Aqukk3EFrRz?p=preview

```<code>$scope.digest();
</code>```

should become

```<code>$scope.apply();
</code>```

Title: angular watch not fired

Body:
There is 1 angular app, with 1 parent controller, and a child controller.
In the child, there is 1 $watch WATCH-CHILD for OBJ-CHILD, which triggers an $emit.
In the parent, there is a listener for the $emit, we'll call it ON-LISTENER, and a $watch WATCH-PARENT for OBJ-PARENT (which uses true as the 3rd argument).

When the child's OBJ-CHILD is changed, it triggers WATCH-CHILD, which triggers the $emit.
The parent listener ON-LISTENER is fired, and changes OBJ-PARENT. It also sets some $location properties.
The $watch WATCH-PARENT for OBJ-PARENT is never fired (even though the value has changed), as well as the properties set on $location not changed in the browser URL (I know they are indeed changed inside the JavaScript, cause I print them).

In order to make sure that ON-LISTENER is called within a $digest, I tried to call $digest at the end of ON-LISTENER, and got the expected exception.

Any idea if I'm doing something wrong? I expect the changes that occur in ON-LISTENER to trigger WATCH-PARENT and browser URL change.

I will try to reproduce on jsfiddle and edit this post if successful.

The code looks like:

CHILD:

$scope.$watch('vars.model', function(newValue, oldValue) {
  console.log('model changed');
  $scope.$emit('highlightChange', newValue);
}, true);

PARENT:

$scope.$watch('vars.model.highlight', function(newValue, oldValue) {
  console.log('highlight changed');
}, true);

$scope.$on('highlightChange', function(event, value) {
  console.log('listener', $scope.vars.model.highlight.categoryId, value.categoryId);
  $location.search('category-id', value.categoryId);
  $scope.vars.model.highlight.categoryId = value.categoryId;
}

Body:
Thanks for the help. I found out that my event originated from a manual call to $scope.$digest() due to the originating event being triggered from a daterangepicker 'apply.daterangepicker' event.
When I changed that to $scope.$apply, the problem seemed to go away.
I can assume from that, that $apply() is the one in charge of keep calling $watch as long as there are changes, and that $digest() doesn't do so.

For future reference, I placed the problem here:
https://plnkr.co/edit/ItkALhw16Aqukk3EFrRz?p=preview

$scope.digest();

should become

$scope.apply();


问:
How do you reset state when keys are not known? (i.e. dynamic forms)
I'm using es6 syntax setState({[name]: value}) to track dynamically added inputs in form and everything is working fine. I'm wondering about clearing state after form submit. I'll submit my solution but I'd be interested in hearing opinions on a better way of clearing the state, or maybe managing dynamic state shape in general.

According to @DavidL.Walsh (see link below) adding fields to state that were not defined in initial state is wrong. But what about dynamic forms in which you don't know the number of inputs or their names.
https://stackoverflow.com/a/34845925/4634544

答:
This is what I am currently using. All the items I'm tracking are strings, which is nice. </p>

```<code>Object.keys(this.state).forEach(key => {
    this.setState({[key]: ''})
})
</code>```

Body:
This is what I am currently using. All the items I'm tracking are strings, which is nice.

Object.keys(this.state).forEach(key => {
    this.setState({[key]: ''})
})


问:
text-overflow ellipsis is not working properly
I recently changed my news ticker to a CSS version.  My problem is the I am trying to use the "text-overflow: ellipsis" and it just is not working.  I have tried placing the styles everywhere without success.  Can anyone help me?  I have created a basic codepen.  The class in GREEN is my problem.

https://codepen.io/lepew/pen/pdwNaL

body {
  background-color: black;
}

#page_Wrap {
  /* Flexbox setup */
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  xflex-flow: column nowrap;
  -webkit-flex-flow: column;
  -moz-flex-flow: column;
  -ms-flex-flow: column;
  flex-flow: column;
  /* Basic styling */
  width: 94%;
  margin: 0 auto;
  max-width: 1280px;
  border: 1px solid red;
}

header {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-flex: 0;
  -moz-box-flex: 0;
  -ms-flex: 0;
  -webkit-flex: 0;
  flex: 0;
  min-height: 100px;
}

#head_Logo,
#head_Note {
  -webkit-box-flex: 0;
  -ms-flex: 0 0 77px;
  flex: 0 0 77px;
  width: 77px;
  height: 90px;
  border: 1px solid yellow;
}

#head_Area {
  -webkit-box-flex: 2;
  -ms-flex: 2;
  flex: 2;
  -webkit-flex-flow: column nowrap;
  -moz-flex-flow: column nowrap;
  -ms-flex-flow: column nowrap;
  flex-flow: column nowrap;
  min-width: 0;
}

.wrap_News {
  height: 45px;
  border: 1px solid lime;
}

.news_Area {
  color: #0FF;
  position: absolute;
  overflow: hidden;
  xmargin-right: 115px;
  xright: 0;
  xleft: 116px;
  opacity: 0;
  -moz-opacity: 0;
  filter: alpha(opacity=0);
}

.news_Text {
  padding: 0 5px;
  font: bold 18px Arial, Helvetica, sans-serif;
  height: 45px;
  overflow: hidden;
  line-height: 45px;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.wrap_News:hover .news_Area {
  -webkit-animation-play-state: paused;
  -moz-animation-play-state: paused;
  -o-animation-play-state: paused;
  animation-play-state: paused;
}

.news_Area:nth-child(1) {
  -webkit-animation: cycle 15s 0s infinite linear;
  -moz-animation: cycle 15s 0s infinite linear;
  -o-animation: cycle 15s 0s infinite linear;
  animation: cycle 15s 0s infinite linear;
}

.news_Area:nth-child(2) {
  -webkit-animation: cycle 15s 5s infinite linear;
  -moz-animation: cycle 15s 5s infinite linear;
  -o-animation: cycle 15s 5s infinite linear;
  animation: cycle 15s 5s infinite linear;
}

.news_Area:nth-child(3) {
  -webkit-animation: cycle 15s 10s infinite linear;
  -moz-animation: cycle 15s 10s infinite linear;
  -o-animation: cycle 15s 10s infinite linear;
  animation: cycle 15s 10s infinite linear;
}

@keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-moz-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-webkit-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-ms-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-o-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page_Wrap">

  <header>
    <div id="head_Logo">
    </div>
    <!-- end of #head_Logo -->

    <div id="head_Area">

      <div class="wrap_News">
        <div class="news_Area">
          <div class="news_Text">This is top secret.  Read more</div>
        </div>
        <!-- end of #news_Area -->
        <div class="news_Area">
          <div class="news_Text">
            This is to see what happens if a lot of text is placed here and is just blah blah blah blah blah blah.
          </div>
          <!-- end of #wrap_News -->
        </div>
        <!-- end of #news_Area -->
        <div class="news_Area">
          <div class="news_Text">Part 3 here</div>
        </div>
        <!-- end of #news_Area -->
      </div>
      <!-- end of #wrap_News -->

    </div>
    <!-- end of #head_Area -->
    <div id="head_Note">
      <!--  HERE  -->
    </div>
    <!-- end of #head_Note -->
  </header>
  <!-- end of #header -->

</div>
<!-- end of #page_Wrap --></code>```

答:
You need to give the bounding box a size, otherwise it will just expand (and thus never have an overflow), see the change to .news_Text {} (added an illustrative dashed orange border).

body {
  background-color: black;
}

#page_Wrap {
  /* Flexbox setup */
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  xflex-flow: column nowrap;
  -webkit-flex-flow: column;
  -moz-flex-flow: column;
  -ms-flex-flow: column;
  flex-flow: column;
  /* Basic styling */
  width: 94%;
  margin: 0 auto;
  max-width: 1280px;
  border: 1px solid red;
}

header {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-flex: 0;
  -moz-box-flex: 0;
  -ms-flex: 0;
  -webkit-flex: 0;
  flex: 0;
  min-height: 100px;
}

#head_Logo,
#head_Note {
  -webkit-box-flex: 0;
  -ms-flex: 0 0 77px;
  flex: 0 0 77px;
  width: 77px;
  height: 90px;
  border: 1px solid yellow;
}

#head_Area {
  -webkit-box-flex: 2;
  -ms-flex: 2;
  flex: 2;
  -webkit-flex-flow: column nowrap;
  -moz-flex-flow: column nowrap;
  -ms-flex-flow: column nowrap;
  flex-flow: column nowrap;
  min-width: 0;
}

.wrap_News {
  height: 45px;
  border: 1px solid lime;
}

.news_Area {
  color: #0FF;
  position: absolute;
  overflow: hidden;
  xmargin-right: 115px;
  xright: 0;
  xleft: 116px;
  opacity: 0;
  -moz-opacity: 0;
  filter: alpha(opacity=0);
}

.news_Text {
  padding: 0 5px;
  font: bold 18px Arial, Helvetica, sans-serif;
  height: 45px;
  overflow: hidden;
  line-height: 45px;
  white-space: nowrap;

  border: 1px dashed orange;
  text-overflow: ellipsis;
  width: 345px;
}

.wrap_News:hover .news_Area {
  -webkit-animation-play-state: paused;
  -moz-animation-play-state: paused;
  -o-animation-play-state: paused;
  animation-play-state: paused;
}

.news_Area:nth-child(1) {
  -webkit-animation: cycle 15s 0s infinite linear;
  -moz-animation: cycle 15s 0s infinite linear;
  -o-animation: cycle 15s 0s infinite linear;
  animation: cycle 15s 0s infinite linear;
}

.news_Area:nth-child(2) {
  -webkit-animation: cycle 15s 5s infinite linear;
  -moz-animation: cycle 15s 5s infinite linear;
  -o-animation: cycle 15s 5s infinite linear;
  animation: cycle 15s 5s infinite linear;
}

.news_Area:nth-child(3) {
  -webkit-animation: cycle 15s 10s infinite linear;
  -moz-animation: cycle 15s 10s infinite linear;
  -o-animation: cycle 15s 10s infinite linear;
  animation: cycle 15s 10s infinite linear;
}

@keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-moz-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-webkit-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-ms-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-o-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="page_Wrap">

  <header>
    <div id="head_Logo">
    </div>
    <!-- end of #head_Logo -->

    <div id="head_Area">

      <div class="wrap_News">
        <div class="news_Area">
          <div class="news_Text">This is top secret.  Read more</div>
        </div>
        <!-- end of #news_Area -->
        <div class="news_Area">
          <div class="news_Text">
            This is to see what happens if a lot of text is placed here and is just blah blah blah blah blah blah.
          </div>
          <!-- end of #wrap_News -->
        </div>
        <!-- end of #news_Area -->
        <div class="news_Area">
          <div class="news_Text">Part 3 here</div>
        </div>
        <!-- end of #news_Area -->
      </div>
      <!-- end of #wrap_News -->

    </div>
    <!-- end of #head_Area -->
    <div id="head_Note">
      <!--  HERE  -->
    </div>
    <!-- end of #head_Note -->
  </header>
  <!-- end of #header -->

</div>
<!-- end of #page_Wrap --></code>```

Body:
I recently changed my news ticker to a CSS version.  My problem is the I am trying to use the "text-overflow: ellipsis" and it just is not working.  I have tried placing the styles everywhere without success.  Can anyone help me?  I have created a basic codepen.  The class in GREEN is my problem.

https://codepen.io/lepew/pen/pdwNaL

body {
  background-color: black;
}

#page_Wrap {
  /* Flexbox setup */
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  xflex-flow: column nowrap;
  -webkit-flex-flow: column;
  -moz-flex-flow: column;
  -ms-flex-flow: column;
  flex-flow: column;
  /* Basic styling */
  width: 94%;
  margin: 0 auto;
  max-width: 1280px;
  border: 1px solid red;
}

header {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-flex: 0;
  -moz-box-flex: 0;
  -ms-flex: 0;
  -webkit-flex: 0;
  flex: 0;
  min-height: 100px;
}

#head_Logo,
#head_Note {
  -webkit-box-flex: 0;
  -ms-flex: 0 0 77px;
  flex: 0 0 77px;
  width: 77px;
  height: 90px;
  border: 1px solid yellow;
}

#head_Area {
  -webkit-box-flex: 2;
  -ms-flex: 2;
  flex: 2;
  -webkit-flex-flow: column nowrap;
  -moz-flex-flow: column nowrap;
  -ms-flex-flow: column nowrap;
  flex-flow: column nowrap;
  min-width: 0;
}

.wrap_News {
  height: 45px;
  border: 1px solid lime;
}

.news_Area {
  color: #0FF;
  position: absolute;
  overflow: hidden;
  xmargin-right: 115px;
  xright: 0;
  xleft: 116px;
  opacity: 0;
  -moz-opacity: 0;
  filter: alpha(opacity=0);
}

.news_Text {
  padding: 0 5px;
  font: bold 18px Arial, Helvetica, sans-serif;
  height: 45px;
  overflow: hidden;
  line-height: 45px;
  white-space: nowrap;
  text-overflow: ellipsis;
}

.wrap_News:hover .news_Area {
  -webkit-animation-play-state: paused;
  -moz-animation-play-state: paused;
  -o-animation-play-state: paused;
  animation-play-state: paused;
}

.news_Area:nth-child(1) {
  -webkit-animation: cycle 15s 0s infinite linear;
  -moz-animation: cycle 15s 0s infinite linear;
  -o-animation: cycle 15s 0s infinite linear;
  animation: cycle 15s 0s infinite linear;
}

.news_Area:nth-child(2) {
  -webkit-animation: cycle 15s 5s infinite linear;
  -moz-animation: cycle 15s 5s infinite linear;
  -o-animation: cycle 15s 5s infinite linear;
  animation: cycle 15s 5s infinite linear;
}

.news_Area:nth-child(3) {
  -webkit-animation: cycle 15s 10s infinite linear;
  -moz-animation: cycle 15s 10s infinite linear;
  -o-animation: cycle 15s 10s infinite linear;
  animation: cycle 15s 10s infinite linear;
}

@keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-moz-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-webkit-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-ms-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-o-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

This is top secret.  Read more

            This is to see what happens if a lot of text is placed here and is just blah blah blah blah blah blah.

Part 3 here

Body:
You need to give the bounding box a size, otherwise it will just expand (and thus never have an overflow), see the change to .news_Text {} (added an illustrative dashed orange border).

body {
  background-color: black;
}

#page_Wrap {
  /* Flexbox setup */
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  xflex-flow: column nowrap;
  -webkit-flex-flow: column;
  -moz-flex-flow: column;
  -ms-flex-flow: column;
  flex-flow: column;
  /* Basic styling */
  width: 94%;
  margin: 0 auto;
  max-width: 1280px;
  border: 1px solid red;
}

header {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  -webkit-box-flex: 0;
  -moz-box-flex: 0;
  -ms-flex: 0;
  -webkit-flex: 0;
  flex: 0;
  min-height: 100px;
}

#head_Logo,
#head_Note {
  -webkit-box-flex: 0;
  -ms-flex: 0 0 77px;
  flex: 0 0 77px;
  width: 77px;
  height: 90px;
  border: 1px solid yellow;
}

#head_Area {
  -webkit-box-flex: 2;
  -ms-flex: 2;
  flex: 2;
  -webkit-flex-flow: column nowrap;
  -moz-flex-flow: column nowrap;
  -ms-flex-flow: column nowrap;
  flex-flow: column nowrap;
  min-width: 0;
}

.wrap_News {
  height: 45px;
  border: 1px solid lime;
}

.news_Area {
  color: #0FF;
  position: absolute;
  overflow: hidden;
  xmargin-right: 115px;
  xright: 0;
  xleft: 116px;
  opacity: 0;
  -moz-opacity: 0;
  filter: alpha(opacity=0);
}

.news_Text {
  padding: 0 5px;
  font: bold 18px Arial, Helvetica, sans-serif;
  height: 45px;
  overflow: hidden;
  line-height: 45px;
  white-space: nowrap;

  border: 1px dashed orange;
  text-overflow: ellipsis;
  width: 345px;
}

.wrap_News:hover .news_Area {
  -webkit-animation-play-state: paused;
  -moz-animation-play-state: paused;
  -o-animation-play-state: paused;
  animation-play-state: paused;
}

.news_Area:nth-child(1) {
  -webkit-animation: cycle 15s 0s infinite linear;
  -moz-animation: cycle 15s 0s infinite linear;
  -o-animation: cycle 15s 0s infinite linear;
  animation: cycle 15s 0s infinite linear;
}

.news_Area:nth-child(2) {
  -webkit-animation: cycle 15s 5s infinite linear;
  -moz-animation: cycle 15s 5s infinite linear;
  -o-animation: cycle 15s 5s infinite linear;
  animation: cycle 15s 5s infinite linear;
}

.news_Area:nth-child(3) {
  -webkit-animation: cycle 15s 10s infinite linear;
  -moz-animation: cycle 15s 10s infinite linear;
  -o-animation: cycle 15s 10s infinite linear;
  animation: cycle 15s 10s infinite linear;
}

@keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-moz-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-webkit-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-ms-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

@-o-keyframes cycle {
  0% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  2% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  31% {
    filter: alpha(opacity=100);
    opacity: 1;
  }
  33% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
  100% {
    filter: alpha(opacity=0);
    opacity: 0;
  }
}

<div id="page_Wrap">

  <header>
    <div id="head_Logo">
    </div>
    <!-- end of #head_Logo -->

    <div id="head_Area">

      <div class="wrap_News">
        <div class="news_Area">
          <div class="news_Text">This is top secret.&nbsp;&nbsp;<a href="#">Read more</a></div>
        </div>
        <!-- end of #news_Area -->
        <div class="news_Area">
          <div class="news_Text">
            This is to see what happens if a lot of text is placed here and is just blah blah blah blah blah blah.
          </div>
          <!-- end of #wrap_News -->
        </div>
        <!-- end of #news_Area -->
        <div class="news_Area">
          <div class="news_Text">Part 3 here</div>
        </div>
        <!-- end of #news_Area -->
      </div>
      <!-- end of #wrap_News -->

    </div>
    <!-- end of #head_Area -->
    <div id="head_Note">
      <!--  HERE  -->
    </div>
    <!-- end of #head_Note -->
  </header>
  <!-- end of #header -->

</div>
<!-- end of #page_Wrap -->


问:
JavaScript Replace() special characters and populate within form
Form1 is to add text, and Form2 should populate the same text as Form1, but convert it using the replace method. I am having trouble populating the text in Form2..</p>

```<code><form id="form1">
<input type="text" name="input" value="">
<button type="submit" name="submit" value="submit">Submit</button>
</header>
<div>
    <label>Plain Text:</label>
    <form id="form2">
    <input type="text" name="input" value="" onchange="convertMarkdown()">
</div>
</div>
<script>
    function convertMarkdown() {

        const form = document.getElementById("form1");
        const input = form.querySelector("input");
        const form2 = document.getElementById("form2");
        const convertedMarkdown = input.replace(/[(\*)(\>)(\#)(\[)(\))]/g, "").replace(/[(\]\()]/g, " ");

        form.addEventListener('submit', (e) => {
            // prevent browser default
            e.preventDefault();

            // contain text content
            const text = input.value;

            // print text content in form1
            form1.textContent = text.text
        });

        form2.addEventListener('onchange', (e) => {
        // prevent browser default
        e.preventDefault();

        // contain text content
        const text = input.value;

        // print converted text in form2
        form2.textContent = input.replace(/[(\*)(\>)(\#)(\[)(\))]/g, "").replace(/[(\]\()]/g, " ");
    };
</script>
</code>```

答:
This below js code will give your expected output.

const submit = document.getElementById("submit");
const input = document.getElementById("ip1");

submit.addEventListener('click', (e) => {
  // prevent browser default
  e.preventDefault();
  const convertedMarkdown = input.value.replace(/[(\*)(\>)(\#)(\[)(\))]/g, "").replace(/[(\]\()]/g, " ");
  // contain text content
  const text = input.value;

  // print text content in form1
  document.forms["form2"]["input2"].value = convertedMarkdown;
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="form1">
  <input id="ip1" type="text" name="input" value="">
  <button id="submit" type="submit" name="submit" value="submit">Submit</button>
</form>
<div>
  <label>Plain Text:</label>
  <form name="form2">
    <input type="text" name="input2" value="">
  </form>
</div></code>```

Body:
Form1 is to add text, and Form2 should populate the same text as Form1, but convert it using the replace method. I am having trouble populating the text in Form2..

<form id="form1">
<input type="text" name="input" value="">
<button type="submit" name="submit" value="submit">Submit</button>

    Plain Text:
    <form id="form2">
    <input type="text" name="input" value="" onchange="convertMarkdown()">

Body:
This below js code will give your expected output.

const submit = document.getElementById("submit");
const input = document.getElementById("ip1");

submit.addEventListener('click', (e) => {
  // prevent browser default
  e.preventDefault();
  const convertedMarkdown = input.value.replace(/[(\*)(\>)(\#)(\[)(\))]/g, "").replace(/[(\]\()]/g, " ");
  // contain text content
  const text = input.value;

  // print text content in form1
  document.forms["form2"]["input2"].value = convertedMarkdown;
});

<form name="form1">
  <input id="ip1" type="text" name="input" value="">
  <button id="submit" type="submit" name="submit" value="submit">Submit</button>
</form>
<div>
  <label>Plain Text:</label>
  <form name="form2">
    <input type="text" name="input2" value="">
  </form>
</div>