问:
TypeError: Cannot read property "price" from undefined in <eval> at line number
someone wrote this JS for me and it worked earlier but now it does not; I cannot get hold of that person so I am reaching out for assistance. I had spent numerous hours trying to correct this but I am not experienced enough with JS .

I am receiving this error:

TypeError: Cannot read property "price" from undefined in  at line number 67

```<code>// Create input variables
var orderItems = [];
var rowsArray = ${rows([]);object(of=json)};
var auxObj = {
'Lip Balm - Orange Coconut': ${lipBalmOrangeCoconut(0)},
'Lip Balm - Raspberry Vanilla': ${lipBalmRaspberryVanilla(0)},
'Bath Bomb - Assorted - 50 mg THC': ${bathBombAssorted50MgThc(0)},
'Buddha Buddha - 200 mg THC': ${buddhaBuddha200MgThc(0)},
'Top Lemon Balm Salve': ${topLemonBalmSalve(0)},
'Buddha Bar - 300 mg THC': ${buddhaBar300MgThc(0)},
'BC Skunk - Hybrid': ${bcSkunkHybrid(0)},
'Blue King - Hybrid': ${blueKingHybrid(0)},
'CBD Treat - Hybrid': ${cbdTreatHybrid(0)},
'Dr. Krippling - Indica': ${drKripplingIndica(0)},
"God's Blue Cough - Hybrid": ${godsBlueCoughHybrid(0)},
'Island Sweet Skunk - Sativa': ${islandSweetSkunkSativa(0)},
'Lemon Sour Diesel - Hybrid': ${lemonSourDieselHybrid(0)},
'MI-O - Sativa': ${mioSativa(0)},
'OG Kush - Hybrid': ${ogKushHybrid(0)},
'Strawberry Skunk - Hybrid': ${strawberrySkunkHybrid(0)},
'Bubble Hash ': ${bubbleHash(0)},
'CBD - 2 capsules per package': ${cbd2CapsulesPerPackage(0)},
'CBD - 30 capsules per bottle': ${cbd30CapsulesPerBottle(0)},
'CBD Phoenix Tears ': ${cbdPhoenixTears(0)},
'THC Phoenix Tears ': ${thcPhoenixTears(0)},
'THC grape seed oil (indica) 900 mg / 30 ml':
${thcGrapeSeedOilindica900Mg30Ml(0)},
'THC grape seed oil (sativa) 900 mg / 30 ml':
${thcGrapeSeedOilsativa900Mg30Ml(0)},
'1:1 THC:CBD grape seed oil 200 mg / 30 ml':
${11ThccbdGrapeSeedOil200Mg30Ml(0)},
'CBD grape seed oil 150 mg / 30 ml': ${cbdGrapeSeedOil150Mg30Ml(0)},
'Chocolate Chip Cookie - 15 mg THC': ${chocolateChipCookie15MgThc(0)},
'Ginger Chew Cookie - 30 mg THC': ${gingerChewCookie30MgThc(0)},
'Red Licorice Bites - 125 mg THC': ${redLicoriceBites125MgThc(0)},
'Double Dose Peanut Butter Cup - 200 mg THC':
${doubleDosePeanutButterCup200MgThc(0)},
'Cherry - 125 mg THC (hybrid)': ${cherry125MgThchybrid(0)},
'Rootbeer - 125 mg THC (sativa)': ${rootbeer125MgThcsativa(0)},
'Watermelon - 125 mg THC (hybrid)': ${watermelon125MgThchybrid(0)},
'Cherry - 120 mg (indica)': ${cherry120Mgindica(0)},
'Blue Raspberry - 120 mg (indica)': ${blueRaspberry120Mgindica(0)},
'Peach  - 120 mg (sativa)': ${peach120Mgsativa(0)},
'Strawberry Banana - 120 mg (sativa)': ${strawberryBanana120Mgsativa(0)},
'Lollipops - Assorted Flavors - 150 mg THC':
${lollipopsAssortedFlavors150MgThc(0)},
'Cotton Candy - Original - 180 mg THC': ${cottonCandyOriginal180MgThc(0)},
'Cotton Candy - Tutti Fruitti - 180 mg THC':
${cottonCandyTuttiFruitti180MgThc(0)},
'Cranberry Ice Tea Apothecary - 60 mg THC':
${cranberryIceTeaApothecary60MgThc(0)},
'Lemon Ice Tea Apothecary - 60 mg THC': ${lemonIceTeaApothecary60MgThc(0)},
'Mango Ice Tea Apothecary - 60 mg THC': ${mangoIceTeaApothecary60MgThc(0)},
'Peach Ice Tea Apothecary - 60 mg THC': ${peachIceTeaApothecary60MgThc(0)},
'Coconut Oil - 500 mg THC': ${coconutOil500MgThc(0)},
'Olive Oil - 400 mg THC': ${oliveOil400MgThc(0)},
'House Strain - Hybrid': ${houseStrainHybrid(0)},
};

// Create a "lookup table" for stock nr. and price
var lookup = {};
for (var i = 0, len = rowsArray.length; i < len; i++) {
lookup[rowsArray[i].formName] = rowsArray[i];
}

var amount = 0,
subtotal = 0,
tax = 0,
shipping = 20,
total = 0;

for (var key in auxObj) {
if (auxObj[key] !== 0) {
    amount = auxObj[key] * lookup[key].price;
    orderItems.push({
        'value': auxObj[key],
        'name': key,
        'stock': lookup[key].stock,
        'price': lookup[key].price,
        'amount': amount
    });
    subtotal += amount;
}
}
tax = subtotal * 0.05;
total = subtotal + tax + shipping;

// Return output variables
var result = {
'orderItems' : orderItems,
'subtotal': subtotal,
'tax': tax,
'total': total
};
result;
</code>```

Line 67 'price' has the error.
I don't know if this amount of code is enough, if you need the full code then please ask.
I don't know why the error is happening (keep in mind I'm not exp. w/JS) and how to fix it to run.

答:
Your problem is being caused because lookup does not have a property named key, therefore lookup[key] is undefined. Whenever a property does not exist in an object (e.g. lookup[key] or lookup.mykey) it will be undefined in JavaScript.

As you haven't suggested how to handle non-existent items in your lookup object I would suggest something similar to the following to fix your issue:

```<code>    var lookupItem = lookup[key];

    orderItems.push({
        'value': auxObj[key],
        'name': key,
        'stock': lookupItem ? lookupItem.stock : 0,
        // If the lookup item exists return the stock value, otherwise return 0. In JavaScript, all objects are truthy in an boolean expression if they are defined and not null, otherwise falsy.
        'price': lookupItem ? lookupItem.price : 0,
        'amount': amount
    });
</code>```

Body:
someone wrote this JS for me and it worked earlier but now it does not; I cannot get hold of that person so I am reaching out for assistance. I had spent numerous hours trying to correct this but I am not experienced enough with JS .

I am receiving this error:

TypeError: Cannot read property "price" from undefined in  at line number 67

// Create input variables
var orderItems = [];
var rowsArray = ${rows([]);object(of=json)};
var auxObj = {
'Lip Balm - Orange Coconut': ${lipBalmOrangeCoconut(0)},
'Lip Balm - Raspberry Vanilla': ${lipBalmRaspberryVanilla(0)},
'Bath Bomb - Assorted - 50 mg THC': ${bathBombAssorted50MgThc(0)},
'Buddha Buddha - 200 mg THC': ${buddhaBuddha200MgThc(0)},
'Top Lemon Balm Salve': ${topLemonBalmSalve(0)},
'Buddha Bar - 300 mg THC': ${buddhaBar300MgThc(0)},
'BC Skunk - Hybrid': ${bcSkunkHybrid(0)},
'Blue King - Hybrid': ${blueKingHybrid(0)},
'CBD Treat - Hybrid': ${cbdTreatHybrid(0)},
'Dr. Krippling - Indica': ${drKripplingIndica(0)},
"God's Blue Cough - Hybrid": ${godsBlueCoughHybrid(0)},
'Island Sweet Skunk - Sativa': ${islandSweetSkunkSativa(0)},
'Lemon Sour Diesel - Hybrid': ${lemonSourDieselHybrid(0)},
'MI-O - Sativa': ${mioSativa(0)},
'OG Kush - Hybrid': ${ogKushHybrid(0)},
'Strawberry Skunk - Hybrid': ${strawberrySkunkHybrid(0)},
'Bubble Hash ': ${bubbleHash(0)},
'CBD - 2 capsules per package': ${cbd2CapsulesPerPackage(0)},
'CBD - 30 capsules per bottle': ${cbd30CapsulesPerBottle(0)},
'CBD Phoenix Tears ': ${cbdPhoenixTears(0)},
'THC Phoenix Tears ': ${thcPhoenixTears(0)},
'THC grape seed oil (indica) 900 mg / 30 ml':
${thcGrapeSeedOilindica900Mg30Ml(0)},
'THC grape seed oil (sativa) 900 mg / 30 ml':
${thcGrapeSeedOilsativa900Mg30Ml(0)},
'1:1 THC:CBD grape seed oil 200 mg / 30 ml':
${11ThccbdGrapeSeedOil200Mg30Ml(0)},
'CBD grape seed oil 150 mg / 30 ml': ${cbdGrapeSeedOil150Mg30Ml(0)},
'Chocolate Chip Cookie - 15 mg THC': ${chocolateChipCookie15MgThc(0)},
'Ginger Chew Cookie - 30 mg THC': ${gingerChewCookie30MgThc(0)},
'Red Licorice Bites - 125 mg THC': ${redLicoriceBites125MgThc(0)},
'Double Dose Peanut Butter Cup - 200 mg THC':
${doubleDosePeanutButterCup200MgThc(0)},
'Cherry - 125 mg THC (hybrid)': ${cherry125MgThchybrid(0)},
'Rootbeer - 125 mg THC (sativa)': ${rootbeer125MgThcsativa(0)},
'Watermelon - 125 mg THC (hybrid)': ${watermelon125MgThchybrid(0)},
'Cherry - 120 mg (indica)': ${cherry120Mgindica(0)},
'Blue Raspberry - 120 mg (indica)': ${blueRaspberry120Mgindica(0)},
'Peach  - 120 mg (sativa)': ${peach120Mgsativa(0)},
'Strawberry Banana - 120 mg (sativa)': ${strawberryBanana120Mgsativa(0)},
'Lollipops - Assorted Flavors - 150 mg THC':
${lollipopsAssortedFlavors150MgThc(0)},
'Cotton Candy - Original - 180 mg THC': ${cottonCandyOriginal180MgThc(0)},
'Cotton Candy - Tutti Fruitti - 180 mg THC':
${cottonCandyTuttiFruitti180MgThc(0)},
'Cranberry Ice Tea Apothecary - 60 mg THC':
${cranberryIceTeaApothecary60MgThc(0)},
'Lemon Ice Tea Apothecary - 60 mg THC': ${lemonIceTeaApothecary60MgThc(0)},
'Mango Ice Tea Apothecary - 60 mg THC': ${mangoIceTeaApothecary60MgThc(0)},
'Peach Ice Tea Apothecary - 60 mg THC': ${peachIceTeaApothecary60MgThc(0)},
'Coconut Oil - 500 mg THC': ${coconutOil500MgThc(0)},
'Olive Oil - 400 mg THC': ${oliveOil400MgThc(0)},
'House Strain - Hybrid': ${houseStrainHybrid(0)},
};

// Create a "lookup table" for stock nr. and price
var lookup = {};
for (var i = 0, len = rowsArray.length; i < len; i++) {
lookup[rowsArray[i].formName] = rowsArray[i];
}

var amount = 0,
subtotal = 0,
tax = 0,
shipping = 20,
total = 0;

for (var key in auxObj) {
if (auxObj[key] !== 0) {
    amount = auxObj[key] * lookup[key].price;
    orderItems.push({
        'value': auxObj[key],
        'name': key,
        'stock': lookup[key].stock,
        'price': lookup[key].price,
        'amount': amount
    });
    subtotal += amount;
}
}
tax = subtotal * 0.05;
total = subtotal + tax + shipping;

// Return output variables
var result = {
'orderItems' : orderItems,
'subtotal': subtotal,
'tax': tax,
'total': total
};
result;

Line 67 'price' has the error.
I don't know if this amount of code is enough, if you need the full code then please ask.
I don't know why the error is happening (keep in mind I'm not exp. w/JS) and how to fix it to run.

Body:
Your problem is being caused because lookup does not have a property named key, therefore lookup[key] is undefined. Whenever a property does not exist in an object (e.g. lookup[key] or lookup.mykey) it will be undefined in JavaScript.

As you haven't suggested how to handle non-existent items in your lookup object I would suggest something similar to the following to fix your issue:

    var lookupItem = lookup[key];

    orderItems.push({
        'value': auxObj[key],
        'name': key,
        'stock': lookupItem ? lookupItem.stock : 0,
        // If the lookup item exists return the stock value, otherwise return 0. In JavaScript, all objects are truthy in an boolean expression if they are defined and not null, otherwise falsy.
        'price': lookupItem ? lookupItem.price : 0,
        'amount': amount
    });


来源: stackexchange

问:
Query Across DBs
I'm trying to run a query across multiple databases. Each database is a different customer but I'm querying the same tables across all of them. I want to loop through all the databases (about 100) and put all the results in a table. I've tried a few different ways but I can't quite seem to get it working and it seems like it might be a syntax thing. Below is my code:

```<code>IF OBJECT_ID('KW.dbo.Result') IS NOT NULL DROP TABLE KW.dbo.Result;

SELECT name as DBName, ROW_NUMBER() OVER(PARTITION BY 1 ORDER BY name) AS RNo
INTO #DBName
FROM sys.databases
WHERE name LIKE 'Customer%'
ORDER BY name;

SELECT * FROM #DBName

DECLARE @sql varchar;

SET @sql = N'SELECT bh.ID,
b.LINE AS Line#,
c.State,
bh.ZIP,
REPLACE(p.Phone, '-', '') AS Phone,
cc.COMPANY_NAME,
b.Amount
INTO KW.dbo.Result
FROM dbo.Customer c
     LEFT JOIN dbo.Change ch ON ch.CIDNo = c.CIDNo
     LEFT JOIN dbo.Provider p ON p.PIDNo = ch.PIDNo
     LEFT JOIN dbo.BossHead bh ON bh.CHIDNo = ch.CHIDNo
     LEFT JOIN dbo.Bills b ON b.BIDNo = bh.BIDNo
     LEFT JOIN dbo.PartnerTerms pt ON pt.BIdNO = b.BIdNo
     LEFT JOIN dbo.CompanyCode cc ON cc.CompanyCode = pt.CompanyCode
WHERE REPLACE(p.Phone, '-', '') IN
(
    SELECT *
    FROM KW.dbo.PhoneNumbers
)
      AND bh.CreateDate BETWEEN "09-01-2016" AND "10-01-2017"
      AND pt.CompanyCode IS NOT NULL
ORDER BY 1';

DECLARE @DB varchar;

DECLARE @i int;

BEGIN TRANSACTION;

SET @i = 1;

    WHILE @i <= (SELECT MAX(RNo) FROM #DBName)

        BEGIN

           SET @DB = (SELECT DBName FROM #DBName WHERE RNo = @i)

           USE @DB;

           EXECUTE sp_executesql @sql

           SET @i = @i + 1

        END

COMMIT TRANSACTION;

GO
</code>```

Error Message: "Msg 102, Level 15, State 1, Line 55
Incorrect syntax near '@DB'."

Any help will be greatly appreciated, thank you!

答:
You can't use a variable to switch tables.  What you can do is create a dynamic query that uses the fully qualified database and table name to go across all of the databases at the same time.

Create a query that creates your query:

```<code>Use master

Select top(1) case when Row_Number() over (order by d.name) = 1 then '' else
'union ' end + 'select c.name from ' + quotename(d.name) +'.' +'.[dbo].[Customer]'
From sys.databases d
Order by d.name
</code>```

Work with that until the query does what you want, then remove the top 1 and run the whole query against all of your databases.

ContentLicense: CC BY-SA 3.0

Title: Query Across DBs

Body:
I'm trying to run a query across multiple databases. Each database is a different customer but I'm querying the same tables across all of them. I want to loop through all the databases (about 100) and put all the results in a table. I've tried a few different ways but I can't quite seem to get it working and it seems like it might be a syntax thing. Below is my code:

IF OBJECT_ID('KW.dbo.Result') IS NOT NULL DROP TABLE KW.dbo.Result;

SELECT name as DBName, ROW_NUMBER() OVER(PARTITION BY 1 ORDER BY name) AS RNo
INTO #DBName
FROM sys.databases
WHERE name LIKE 'Customer%'
ORDER BY name;

SELECT * FROM #DBName

DECLARE @sql varchar;

SET @sql = N'SELECT bh.ID,
b.LINE AS Line#,
c.State,
bh.ZIP,
REPLACE(p.Phone, '-', '') AS Phone,
cc.COMPANY_NAME,
b.Amount
INTO KW.dbo.Result
FROM dbo.Customer c
     LEFT JOIN dbo.Change ch ON ch.CIDNo = c.CIDNo
     LEFT JOIN dbo.Provider p ON p.PIDNo = ch.PIDNo
     LEFT JOIN dbo.BossHead bh ON bh.CHIDNo = ch.CHIDNo
     LEFT JOIN dbo.Bills b ON b.BIDNo = bh.BIDNo
     LEFT JOIN dbo.PartnerTerms pt ON pt.BIdNO = b.BIdNo
     LEFT JOIN dbo.CompanyCode cc ON cc.CompanyCode = pt.CompanyCode
WHERE REPLACE(p.Phone, '-', '') IN
(
    SELECT *
    FROM KW.dbo.PhoneNumbers
)
      AND bh.CreateDate BETWEEN "09-01-2016" AND "10-01-2017"
      AND pt.CompanyCode IS NOT NULL
ORDER BY 1';

DECLARE @DB varchar;

DECLARE @i int;

BEGIN TRANSACTION;

SET @i = 1;

    WHILE @i <= (SELECT MAX(RNo) FROM #DBName)

        BEGIN

           SET @DB = (SELECT DBName FROM #DBName WHERE RNo = @i)

           USE @DB;

           EXECUTE sp_executesql @sql

           SET @i = @i + 1

        END

COMMIT TRANSACTION;

GO

Error Message: "Msg 102, Level 15, State 1, Line 55
Incorrect syntax near '@DB'."

Any help will be greatly appreciated, thank you!

Body:
You can't use a variable to switch tables.  What you can do is create a dynamic query that uses the fully qualified database and table name to go across all of the databases at the same time.

Create a query that creates your query:

Use master

Select top(1) case when Row_Number() over (order by d.name) = 1 then '' else
'union ' end + 'select c.name from ' + quotename(d.name) +'.' +'.[dbo].[Customer]'
From sys.databases d
Order by d.name

Work with that until the query does what you want, then remove the top 1 and run the whole query against all of your databases.


问:
Doctrine ORM default value with quotes
how can i set a default value with different quotes?

```<code>     /**
     * @ORM\Column(type="string", options={"default" = "<link href="https://fonts.googleapis.com/css?family=Nunito+Sans" rel="stylesheet">"})
     */
</code>```

THX for help

答:
regarding your question, to escape a quotation you need to double it. Here's a working version of your annotation.</p>

```<code>@ORM\Column(type="string", options={"default": "<link href=""https://fonts.googleapis.com/css?family=Nunito+Sans"" rel=""stylesheet"">"})
</code>```

Title: Doctrine ORM default value with quotes

Body:
how can i set a default value with different quotes?

     /**
     * @ORM\Column(type="string", options={"default" = "<link href="https://fonts.googleapis.com/css?family=Nunito+Sans" rel="stylesheet">"})
     */

THX for help

Body:
regarding your question, to escape a quotation you need to double it. Here's a working version of your annotation.

@ORM\Column(type="string", options={"default": "<link href=""https://fonts.googleapis.com/css?family=Nunito+Sans"" rel=""stylesheet"">"})


问:
Retrieve the minimum value of a column from the max value of another column
I have a hive table t1 that looks like this:

```
ID   Score1    score2
1     4         11
1     5         12
1     5         13
2     3         14
2     3         15
2     2         12
2     2         11
3     6         10
3     6         11
3     6         12
```

I want for each ID, to select the max value of score1, and if the max value exists more than once, then from the rows that contain max(score1) I want to get min(score2).

So, I want the minimum score2 of the maximum score1 rows, the results should be something like this

```
ID    Score1    score2
1     5         12
2     3         14
3     6         10
```

Most of the ideas I have turn this to be a very complicated query, and I think there is a simple solution for it that I am not able to find yet.

Any ideas?

答:
You can do this with window functions:

SELECT ID, score1, MIN(score2) AS score2
FROM (
  SELECT score1, score2, ID
  FROM (
    SELECT score1, score2, ID
    FROM MyTable
    QUALIFY RANK OVER(PARTITION BY ID ORDER BY score1 DESC) > 1
  ) src
  QUALIFY  COUNT() OVER(PARTITION BY ID) > 1
) src
GROUP BY 1,2

Sorry, writing this from my phone...can't format it well, there may be syntax errors too.

Body:
I have a hive table t1 that looks like this:

ID   Score1    score2
1     4         11
1     5         12
1     5         13
2     3         14
2     3         15
2     2         12
2     2         11
3     6         10
3     6         11
3     6         12

I want for each ID, to select the max value of score1, and if the max value exists more than once, then from the rows that contain max(score1) I want to get min(score2).

So, I want the minimum score2 of the maximum score1 rows, the results should be something like this

ID    Score1    score2
1     5         12
2     3         14
3     6         10

Most of the ideas I have turn this to be a very complicated query, and I think there is a simple solution for it that I am not able to find yet.

Any ideas?


问:
Allow no whitespace in required form field
I have a register form which allows users to create usernames and passwords. It requires the username field not be empty, but I need to require that it allow no whitespace at all.

I looked into preg_match() but I can't seem to get that to cooperate with my current code.

```<code>if ($_SERVER["REQUEST_METHOD"] == "POST") {
    /* Validate Username */
    if (empty(trim($_POST["username"]))) {
        $username_err = "Username Required";
    }
</code>```

答:
Before calling any function on $_POST() I recommend calling isset() on the element to avoid receiving a Notice.

Using isset() will allow for the valid but unlikely username of 0.

Calling trim() on a not-set element will cause a Notice.

I don't see any advantage in checking from the back of the string for spaces with strrpos() so I'll simply call strpos().

If this is a simple pass/fail task (not trying to isolate the cause of the failure), use this:

Code: (Demo)

```<code>$_POST['username']="0";

if(isset($_POST['username']) && strlen($_POST['username']) && strpos($_POST['username'],' ')===false){
    echo 'pass';
}else{
    echo 'fail';
}
</code>```

Output:

```<code>pass
</code>```

The beauty in this one-liner conditional, is that as soon as one of the conditions fails, the rest are ignored and the fail message will be displayed.

If you want to get a little crazy with micro-optimization, you can remove the strlen() call and just check for the existence of a first character (see if the first "offset" isset).

```<code>if(isset($_POST['username'][0]) && strpos($_POST['username'],' ')===false){
    echo 'pass';
}else{
    echo 'fail';
}
</code>```

And if we are putting tin-foil hats on, then a check to see that $_POST['username'] is not an array should be included before strpos() is called (in any of the solutions on this page).

```<code>if(isset($_POST['username'][0]) && !is_array($_POST['username']) && strpos($_POST['username'],' ')===false){
</code>```

Body:
I have a register form which allows users to create usernames and passwords. It requires the username field not be empty, but I need to require that it allow no whitespace at all.

I looked into preg_match() but I can't seem to get that to cooperate with my current code.

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    /* Validate Username */
    if (empty(trim($_POST["username"]))) {
        $username_err = "Username Required";
    }

Body:
Before calling any function on $_POST() I recommend calling isset() on the element to avoid receiving a Notice.

Using isset() will allow for the valid but unlikely username of 0.

Calling trim() on a not-set element will cause a Notice.

I don't see any advantage in checking from the back of the string for spaces with strrpos() so I'll simply call strpos().

If this is a simple pass/fail task (not trying to isolate the cause of the failure), use this:

Code: (Demo)

$_POST['username']="0";

if(isset($_POST['username']) && strlen($_POST['username']) && strpos($_POST['username'],' ')===false){
    echo 'pass';
}else{
    echo 'fail';
}

Output:

pass

The beauty in this one-liner conditional, is that as soon as one of the conditions fails, the rest are ignored and the fail message will be displayed.

If you want to get a little crazy with micro-optimization, you can remove the strlen() call and just check for the existence of a first character (see if the first "offset" isset).

if(isset($_POST['username'][0]) && strpos($_POST['username'],' ')===false){
    echo 'pass';
}else{
    echo 'fail';
}

And if we are putting tin-foil hats on, then a check to see that $_POST['username'] is not an array should be included before strpos() is called (in any of the solutions on this page).

if(isset($_POST['username'][0]) && !is_array($_POST['username']) && strpos($_POST['username'],' ')===false){


问:
Difference between a class and object in Kotlin
I'm new to Kotlin and have recently converted a simple file from java to Kotlin. I am wondering why the Android converter changed my java class to a Kotlin object.

Java:

```<code>public class MyClass {
    static public int GenerateChecksumCrc16(byte bytes[]) {

        int crc = 0xFFFF;
        int temp;
        int crc_byte;

        for (byte aByte : bytes) {

            crc_byte = aByte;

            for (int bit_index = 0; bit_index < 8; bit_index++) {

                temp = ((crc >> 15)) ^ ((crc_byte >> 7));

                crc <<= 1;
                crc &= 0xFFFF;

                if (temp > 0) {
                    crc ^= 0x1021;
                    crc &= 0xFFFF;
                }

                crc_byte <<= 1;
                crc_byte &= 0xFF;

            }
        }

        return crc;
    }
}
</code>```

Converted Kotlin:

```<code>object MyClass {
    fun GenerateChecksumCrc16(bytes: ByteArray): Int {

        var crc = 0xFFFF
        var temp: Int
        var crc_byte: Int

        for (aByte in bytes) {

            crc_byte = aByte.toInt()

            for (bit_index in 0..7) {

                temp = crc shr 15 xor (crc_byte shr 7)

                crc = crc shl 1
                crc = crc and 0xFFFF

                if (temp > 0) {
                    crc = crc xor 0x1021
                    crc = crc and 0xFFFF
                }

                crc_byte = crc_byte shl 1
                crc_byte = crc_byte and 0xFF

            }
        }

        return crc
    }
}
</code>```

Why wasn't it:

```<code>class MyClass {
    ... etc ...
}
</code>```

Any help would be greatly appreciated thanks.

答:
Kotlin's documentation on this is pretty good, so feel free to read that.

The chosen answer for this question has some poor phraseology in its explanation, and could easily mislead people. For instance, an object is not "a static class per se", but rather it is a static instance of a class that there is only one of, otherwise known as a singleton.

Perhaps the best way to show the difference is to look at the decompiled Kotlin code in Java form.

Kotlin object and class:

```<code>object ExampleObject {
  fun example() {
  }
}

class ExampleClass {
  fun example() {
  }
}
</code>```

In order to use the ExampleClass, you need to create an instance of it: ExampleClass().example(), but with an object, Kotlin creates a single instance of it for you, and you don't ever call it's constructor, instead you just access it's static instance by using the name: ExampleObject.example().

Equivalent Java code Kotlin would generate:

Kotlin compiles to Java byte code, but if we reverse compile the above compiled Kotlin code to Java code this is what we get:

```<code>public final class ExampleObject {
   public static final ExampleObject INSTANCE = new ExampleObject();

   private ExampleObject() { }

   public final void example() {
   }
}

public final class ExampleClass {
   public final void example() {
   }
}
</code>```

You would use the object in Kotlin the following way:

```<code>ExampleObject.example()
</code>```

Which would compile down to the equivalent Java byte code for:

```<code>ExampleObject.INSTANCE.example()
</code>```

Why does Kotlin introduce objects?

The primary use case of object in Kotlin is because Kotlin tries to do away with static, and primitives, leaving us with a purely object oriented language. Kotlin still uses static and primitives underneath the hood, but it discourages devs to use those concepts any more. Instead, now Kotlin replaces static with singleton object instances. Where you would previously use static field in Java, in Kotlin you will now create an object, and put that field in the object.

Interoperability with Java:

Because Kotlin is 100% interoperable with Java, sometimes you will want to expose certain APIs or fields in a way that is nicer for Java to read. To do this, you can use the @JvmStatic annotation. By annotating a field or a function in an object with @JvmStatic, it will compile down to static fields which Java can use easier.

Companion Objects:

One last thing that's worth mentioning is companion objects. In Java, you typically have classes that have some static content, but also some non-static / instance content. Kotlin allows you to do something similar with companion objects, which are objects tied to a class, meaning a class can access it's companion object's private functions and properties:

```<code>class ExampleClass {
  companion object {
    // Things that would be static in Java would go here in Kotlin
    private const val str = "asdf"
  }

  fun example() {
    // I can access private variables in my companion object
    println(str)
  }
}
</code>```

Body:
I'm new to Kotlin and have recently converted a simple file from java to Kotlin. I am wondering why the Android converter changed my java class to a Kotlin object.

Java:

public class MyClass {
    static public int GenerateChecksumCrc16(byte bytes[]) {

        int crc = 0xFFFF;
        int temp;
        int crc_byte;

        for (byte aByte : bytes) {

            crc_byte = aByte;

            for (int bit_index = 0; bit_index < 8; bit_index++) {

                temp = ((crc >> 15)) ^ ((crc_byte >> 7));

                crc <<= 1;
                crc &= 0xFFFF;

                if (temp > 0) {
                    crc ^= 0x1021;
                    crc &= 0xFFFF;
                }

                crc_byte <<= 1;
                crc_byte &= 0xFF;

            }
        }

        return crc;
    }
}

Converted Kotlin:

object MyClass {
    fun GenerateChecksumCrc16(bytes: ByteArray): Int {

        var crc = 0xFFFF
        var temp: Int
        var crc_byte: Int

        for (aByte in bytes) {

            crc_byte = aByte.toInt()

            for (bit_index in 0..7) {

                temp = crc shr 15 xor (crc_byte shr 7)

                crc = crc shl 1
                crc = crc and 0xFFFF

                if (temp > 0) {
                    crc = crc xor 0x1021
                    crc = crc and 0xFFFF
                }

                crc_byte = crc_byte shl 1
                crc_byte = crc_byte and 0xFF

            }
        }

        return crc
    }
}

Why wasn't it:

class MyClass {
    ... etc ...
}

Any help would be greatly appreciated thanks.

Body:
Kotlin's documentation on this is pretty good, so feel free to read that.

The chosen answer for this question has some poor phraseology in its explanation, and could easily mislead people. For instance, an object is not "a static class per se", but rather it is a static instance of a class that there is only one of, otherwise known as a singleton.

Perhaps the best way to show the difference is to look at the decompiled Kotlin code in Java form.

Kotlin object and class:

object ExampleObject {
  fun example() {
  }
}

class ExampleClass {
  fun example() {
  }
}

In order to use the ExampleClass, you need to create an instance of it: ExampleClass().example(), but with an object, Kotlin creates a single instance of it for you, and you don't ever call it's constructor, instead you just access it's static instance by using the name: ExampleObject.example().

Equivalent Java code Kotlin would generate:

Kotlin compiles to Java byte code, but if we reverse compile the above compiled Kotlin code to Java code this is what we get:

public final class ExampleObject {
   public static final ExampleObject INSTANCE = new ExampleObject();

   private ExampleObject() { }

   public final void example() {
   }
}

public final class ExampleClass {
   public final void example() {
   }
}

You would use the object in Kotlin the following way:

ExampleObject.example()

Which would compile down to the equivalent Java byte code for:

ExampleObject.INSTANCE.example()

Why does Kotlin introduce objects?

The primary use case of object in Kotlin is because Kotlin tries to do away with static, and primitives, leaving us with a purely object oriented language. Kotlin still uses static and primitives underneath the hood, but it discourages devs to use those concepts any more. Instead, now Kotlin replaces static with singleton object instances. Where you would previously use static field in Java, in Kotlin you will now create an object, and put that field in the object.

Interoperability with Java:

Because Kotlin is 100% interoperable with Java, sometimes you will want to expose certain APIs or fields in a way that is nicer for Java to read. To do this, you can use the @JvmStatic annotation. By annotating a field or a function in an object with @JvmStatic, it will compile down to static fields which Java can use easier.

Companion Objects:

One last thing that's worth mentioning is companion objects. In Java, you typically have classes that have some static content, but also some non-static / instance content. Kotlin allows you to do something similar with companion objects, which are objects tied to a class, meaning a class can access it's companion object's private functions and properties:

class ExampleClass {
  companion object {
    // Things that would be static in Java would go here in Kotlin
    private const val str = "asdf"
  }

  fun example() {
    // I can access private variables in my companion object
    println(str)
  }
}

ContentLicense: CC BY-SA 4.0


问:
How can I open a pdf with a relative path using the default application in a Qt program
I am trying to open a pdf manual for some hardware from within my application.  It will be triggered from the help menu.  I can't seem to get my application to open a file from a relative path using the OS default application.  I found

```<code>QDesktopServices::openUrl(QUrl("file:///home/folder/Manual.pdf"));
</code>```

referenced on the Qt forums and this works for me except I am going to install my software on another computer and the absolute path won't be the same.  I'd like to install the manual next to my application and open it with something like

```<code>QDesktopServices::openUrl(QUrl("file:///Manual.pdf"));
</code>```

but this fails to open with

```<code>ShellExecute 'file:///Manual.pdf' failed (error 2).
</code>```

Has anyone done this before?

答:
You can retrieve the absolute path with

```<code>QString a = QFileInfo("Manual.pdf").absoluteFilePath();
</code>```

then pass it to QUrl, this way:

```<code>QUrl url = QUrl::fromLocalFile(a);
</code>```

Body:
I am trying to open a pdf manual for some hardware from within my application.  It will be triggered from the help menu.  I can't seem to get my application to open a file from a relative path using the OS default application.  I found

QDesktopServices::openUrl(QUrl("file:///home/folder/Manual.pdf"));

referenced on the Qt forums and this works for me except I am going to install my software on another computer and the absolute path won't be the same.  I'd like to install the manual next to my application and open it with something like

QDesktopServices::openUrl(QUrl("file:///Manual.pdf"));

but this fails to open with

ShellExecute 'file:///Manual.pdf' failed (error 2).

Has anyone done this before?

Body:
You can retrieve the absolute path with

QString a = QFileInfo("Manual.pdf").absoluteFilePath();

then pass it to QUrl, this way:

QUrl url = QUrl::fromLocalFile(a);


问:
minishell malloc error with EXC_BAD_ACCESS
Hi I've recently started learning unix system programming.

I'm trying to create a minishell in c but when I run my code,

I always get:

EXC_BAD_ACCESS (code=EXC_I386_GPFLT

Don't really know what's wrong here. Searched online they say it's something wrong with malloc, but I don't see what's wrong.

Can someone help me with this problem?

```<code>#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
#include "minishell.h"

char promptString[] = "mysh>";

struct command_t command;
int enviromentlength;
int commandlength;
char *pathv[MAX_PATHS];
//to display the prompt in the front of every line
void printPrompt()
{
    printf("%s", promptString);
}

//get the user's command
void readCommand(char *buffer)
{
    gets(buffer);
}

//get the environment variable and store in a pathEnvVar
int parsePath( char* dirs[] )
{
    char* pathEnvVar;
    char* thePath;
    int i;

    for(i = 0; i < MAX_ARGS; i++)
    {
        dirs[i] = NULL;
    }
        i = 0;
    //use system call to get the environment variable
    pathEnvVar = (char*) getenv("PATH");

//printf("%s\n", pathEnvVar);
thePath = (char*) malloc(strlen(pathEnvVar) + 1);
strcpy(thePath, pathEnvVar);

//splict the variable and store in the pathv
char *temp = strtok(thePath, ":");
dirs[i] = temp;
while(temp != NULL)
{
    i++;
    temp = strtok(NULL, ":");
    if(temp == NULL)
    {
        break;
    }
    else
    {
        dirs[i] = temp;
    }
}
    dirs[i+1] = NULL;
    return i;
}

//get the user's command and parameters
int parseCommand(char * commandline)
{

int i = 0;

char* temp;
temp = strtok(commandline, " ");
while(temp != NULL)
{
    command.argv[i] = temp;
    i++;
    temp = strtok(NULL, " ");
}
command.argv[i] = NULL;
return i;
}

//input the user's command to
//fix the absolute path of the command
char* lookupPath(char* dir[], char* command[])
{
char* result = NULL;

int i;
//printf("%c\n", *command.argv[0]);

//if the command is already an absolute path
if(*command[0] == '/')
{
    result = command[0];
    //printf("test\n");
    if( access(result, X_OK) == 0)
    {
        return result;
    }
    else
    {
        fprintf(stderr, "%s: command not found\n", result);
        return NULL;
    }
}

//if the command is not an absolute path
else
{
    for(i = 0; i < enviromentlength; i++)
    {

        char *temp = (char *) malloc (30);
        strcpy(temp, dir[i]);
        strcat(temp, "/");

        strcat(temp, command[0]);
        result = temp;

        if( access(result, X_OK) == 0)
        {
            return result;
        }

    }

    fprintf(stderr, "%s: command not found\n", result);
    return NULL;

}

}

//to change the directory and
//display the absolute path of the current directory
void do_cd(char* dir[])
{
char currentdirectory[MAX_PATHS];

if(dir[1] == NULL || (strcmp(dir[1], ".") == 0))
{
    printf("director does not change\n");
    //printf("The current directory is:%s", currentdirectory);
}
    else
    {
        if(chdir(dir[1]) < 0)
        {
            printf("change director error\n");
        }
        else
        {
            printf("change director success\n");
        }

    }
    getcwd(currentdirectory, MAX_PATHS);
    printf("The current directory is:%s\n", currentdirectory);
}

//redirection the result to file
void redirection(char* command, char* commandcontent[], int position,         pid_t thisChPID)
{
    char* content[commandlength - 1];
    char* filename = (char *) malloc(MAX_PATH_LEN);
    FILE* fid;
    int i = 0;
    int stat;
    strcpy(filename, commandcontent[position + 1]);
    //printf("%s\n", commandcontent[position + 1]);
    for(i = 0; i < position; i++)
    {
        content[i] = commandcontent[i];
        //printf("content: %s\n", content[i]);
    }
    content[i + 1] = NULL;
    for(i = 0; i< position + 1; i++)
    {
        printf("%s\n", content[i]);
    }
        printf("%s\n", command);
    if((thisChPID=fork()) < 0)
    {
        fprintf(stderr, "fork failed\n");
}
else if(thisChPID == 0)
{

    fid = open(filename, O_WRONLY || O_CREAT);
    close(1);
    dup(fid);
    close(fid);
    execve(command, content, pathv);

}
else
{
    wait(&stat);

}

}

//use pipe to run the program
void piperun(char* command, char* commandcontent[], int position, pid_t thisChPID)
{
printf("%s\n%d\n", command, position);
char* firstcommand[position+1];

char* secondcommand[commandlength-position];
char* result = (char *) malloc(MAX_PATH_LEN);
pid_t child;

//the pipe name
int pipeID[2];
int j;

for(j = 0; j< position; j++)
{
    firstcommand[j] = commandcontent[j];
    printf("%s\n", firstcommand[j]);
}
firstcommand[j] = NULL;
printf("length: %d\n", commandlength-position);
for(j = 0; j < (commandlength-position); j++)
{
    secondcommand[j] = commandcontent[position + 1 + j];
    printf("second:%s\n",secondcommand[j]);
}

//secondcommand[j+1] = NULL;
result = lookupPath(pathv, secondcommand);
//printf("%s\n", secondcommand[0]);
printf("%s\n", result);

//create pipe "pipeID"
if(pipe(pipeID)==-1)
{
    printf("Fail to creat pipe.\n");

}
if((thisChPID=fork())==-1)
{
    printf("Fail to creat child process.\n");

}

if(thisChPID==0)
{
    printf("in the child\n");
    close(1);
    dup(pipeID[1]);
    close(pipeID[0]);
    close(pipeID[1]);
    if(execve(command, firstcommand, pathv)==-1)
    {
        printf("Child process can't exec command %s.\n",firstcommand[0]);

    }

}
else
{
    child = fork();
    if((child=fork())==-1)
    {
        printf("Fail to creat child process.\n");

    }
    if(child==0)
    {
        close(0);
        dup(pipeID[0]);
        close(pipeID[1]);
        close(pipeID[0]);
            if(execve(result, secondcommand, pathv)==-1)
        {
                printf("Child process can't exec command     %s.\n",secondcommand[0]);

        }

        }
        else
        {
            wait(NULL);

        }

    }

}

int main()
{
char commandLine[LINE_LEN];

int child_pid;  //child process id
int stat;    //used by parent wait
pid_t thisChPID;
char *arg[MAX_ARGS];

//the flag of redirection, piping and background running
int redirectionsituation = 0;
int pipesituation = 0;
int background = 0;

char * tempchar;

//Command initialization
int i;
for(i = 0; i < MAX_ARGS; i++ )
{
    command.argv[i] = (char *) malloc(MAX_ARG_LEN);
}

//get all directories from PATH env var
enviromentlength = parsePath(pathv);

//Main loop
while(TRUE)
{
    redirectionsituation = 0;
    pipesituation = 0;
    background = 0;
    //Read the command line
    printPrompt();
    readCommand(commandLine);

    //input nothing
    if(commandLine[0] == '\0')
    {

        continue;
    }

    //quit the shell?
    if((strcmp(commandLine, "exit") == 0) || (strcmp(commandLine, "quit") == 0))
    {
        break;
    }

    //if it is background running
    if(commandLine[strlen(commandLine) - 1] == '&')
    {
        printf("backgrond\n");
        tempchar = strtok (commandLine, "&");
        //strcpy(commandLine, tempchar);
        printf("%s\n", tempchar);
        background = 1;

    }

    //Parse the command line
    commandlength = parseCommand(commandLine);

    //if the command is "cd"
    if(strcmp(command.argv[0], "cd") == 0)
    {
        do_cd(command.argv);
        continue;
    }

    //Get the full path name
    command.name = lookupPath(pathv, command.argv);
    printf("command name %s\n", command.name);

    //report error
    if( command.name == NULL)
    {

        continue;  //non-fatal
    }

    //if redirection is required
    for(i = 0; i < commandlength; i++)
    {
        if(strcmp(command.argv[i], ">") == 0)
        {
            redirectionsituation = 1;
            break;
        }

    }
    if(redirectionsituation == 1)
    {
        redirection(command.name, command.argv, i, thisChPID);
        continue;
    }

    //if pipe is required
    for(i = 0; i < commandlength; i++)
    {
        if(strcmp(command.argv[i], "|") == 0)
        {
            pipesituation = 1;
            break;
        }

    }
    if(pipesituation == 1)
    {    //run pipe
        piperun(command.name, command.argv, i, thisChPID);

        continue;
    }

    //normal running
    if((thisChPID=fork()) < 0)
    {
        fprintf(stderr, "fork failed\n");
    }
        else if(thisChPID == 0)
        {
            //printf("run again\n");
            execve(command.name, command.argv, pathv);

        }
        else
        {
            //do not put the process in the background, wait until the     child process terminates
            if(background == 0)
            {
            wait(&stat);
            }

        }
    }
    return 0;
}
</code>```

答: Run it in a debugger and see where you are dereferencing a null.</p>

Body:
Hi I've recently started learning unix system programming.

I'm trying to create a minishell in c but when I run my code,

I always get:

EXC_BAD_ACCESS (code=EXC_I386_GPFLT

Don't really know what's wrong here. Searched online they say it's something wrong with malloc, but I don't see what's wrong.

Can someone help me with this problem?

#include <stdlib.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <string.h>
#include <unistd.h>
#include "minishell.h"

char promptString[] = "mysh>";

struct command_t command;
int enviromentlength;
int commandlength;
char *pathv[MAX_PATHS];
//to display the prompt in the front of every line
void printPrompt()
{
    printf("%s", promptString);
}

//get the user's command
void readCommand(char *buffer)
{
    gets(buffer);
}

//get the environment variable and store in a pathEnvVar
int parsePath( char* dirs[] )
{
    char* pathEnvVar;
    char* thePath;
    int i;

    for(i = 0; i < MAX_ARGS; i++)
    {
        dirs[i] = NULL;
    }
        i = 0;
    //use system call to get the environment variable
    pathEnvVar = (char*) getenv("PATH");

//printf("%s\n", pathEnvVar);
thePath = (char*) malloc(strlen(pathEnvVar) + 1);
strcpy(thePath, pathEnvVar);

//splict the variable and store in the pathv
char *temp = strtok(thePath, ":");
dirs[i] = temp;
while(temp != NULL)
{
    i++;
    temp = strtok(NULL, ":");
    if(temp == NULL)
    {
        break;
    }
    else
    {
        dirs[i] = temp;
    }
}
    dirs[i+1] = NULL;
    return i;
}

//get the user's command and parameters
int parseCommand(char * commandline)
{

int i = 0;

char* temp;
temp = strtok(commandline, " ");
while(temp != NULL)
{
    command.argv[i] = temp;
    i++;
    temp = strtok(NULL, " ");
}
command.argv[i] = NULL;
return i;
}

//input the user's command to
//fix the absolute path of the command
char* lookupPath(char* dir[], char* command[])
{
char* result = NULL;

int i;
//printf("%c\n", *command.argv[0]);

//if the command is already an absolute path
if(*command[0] == '/')
{
    result = command[0];
    //printf("test\n");
    if( access(result, X_OK) == 0)
    {
        return result;
    }
    else
    {
        fprintf(stderr, "%s: command not found\n", result);
        return NULL;
    }
}

//if the command is not an absolute path
else
{
    for(i = 0; i < enviromentlength; i++)
    {

        char *temp = (char *) malloc (30);
        strcpy(temp, dir[i]);
        strcat(temp, "/");

        strcat(temp, command[0]);
        result = temp;

        if( access(result, X_OK) == 0)
        {
            return result;
        }

    }

    fprintf(stderr, "%s: command not found\n", result);
    return NULL;

}

}

//to change the directory and
//display the absolute path of the current directory
void do_cd(char* dir[])
{
char currentdirectory[MAX_PATHS];

if(dir[1] == NULL || (strcmp(dir[1], ".") == 0))
{
    printf("director does not change\n");
    //printf("The current directory is:%s", currentdirectory);
}
    else
    {
        if(chdir(dir[1]) < 0)
        {
            printf("change director error\n");
        }
        else
        {
            printf("change director success\n");
        }

    }
    getcwd(currentdirectory, MAX_PATHS);
    printf("The current directory is:%s\n", currentdirectory);
}

//redirection the result to file
void redirection(char* command, char* commandcontent[], int position,         pid_t thisChPID)
{
    char* content[commandlength - 1];
    char* filename = (char *) malloc(MAX_PATH_LEN);
    FILE* fid;
    int i = 0;
    int stat;
    strcpy(filename, commandcontent[position + 1]);
    //printf("%s\n", commandcontent[position + 1]);
    for(i = 0; i < position; i++)
    {
        content[i] = commandcontent[i];
        //printf("content: %s\n", content[i]);
    }
    content[i + 1] = NULL;
    for(i = 0; i< position + 1; i++)
    {
        printf("%s\n", content[i]);
    }
        printf("%s\n", command);
    if((thisChPID=fork()) < 0)
    {
        fprintf(stderr, "fork failed\n");
}
else if(thisChPID == 0)
{

    fid = open(filename, O_WRONLY || O_CREAT);
    close(1);
    dup(fid);
    close(fid);
    execve(command, content, pathv);

}
else
{
    wait(&stat);

}

}

//use pipe to run the program
void piperun(char* command, char* commandcontent[], int position, pid_t thisChPID)
{
printf("%s\n%d\n", command, position);
char* firstcommand[position+1];

char* secondcommand[commandlength-position];
char* result = (char *) malloc(MAX_PATH_LEN);
pid_t child;

//the pipe name
int pipeID[2];
int j;

for(j = 0; j< position; j++)
{
    firstcommand[j] = commandcontent[j];
    printf("%s\n", firstcommand[j]);
}
firstcommand[j] = NULL;
printf("length: %d\n", commandlength-position);
for(j = 0; j < (commandlength-position); j++)
{
    secondcommand[j] = commandcontent[position + 1 + j];
    printf("second:%s\n",secondcommand[j]);
}

//secondcommand[j+1] = NULL;
result = lookupPath(pathv, secondcommand);
//printf("%s\n", secondcommand[0]);
printf("%s\n", result);

//create pipe "pipeID"
if(pipe(pipeID)==-1)
{
    printf("Fail to creat pipe.\n");

}
if((thisChPID=fork())==-1)
{
    printf("Fail to creat child process.\n");

}

if(thisChPID==0)
{
    printf("in the child\n");
    close(1);
    dup(pipeID[1]);
    close(pipeID[0]);
    close(pipeID[1]);
    if(execve(command, firstcommand, pathv)==-1)
    {
        printf("Child process can't exec command %s.\n",firstcommand[0]);

    }

}
else
{
    child = fork();
    if((child=fork())==-1)
    {
        printf("Fail to creat child process.\n");

    }
    if(child==0)
    {
        close(0);
        dup(pipeID[0]);
        close(pipeID[1]);
        close(pipeID[0]);
            if(execve(result, secondcommand, pathv)==-1)
        {
                printf("Child process can't exec command     %s.\n",secondcommand[0]);

        }

        }
        else
        {
            wait(NULL);

        }

    }

}

int main()
{
char commandLine[LINE_LEN];

int child_pid;  //child process id
int stat;    //used by parent wait
pid_t thisChPID;
char *arg[MAX_ARGS];

//the flag of redirection, piping and background running
int redirectionsituation = 0;
int pipesituation = 0;
int background = 0;

char * tempchar;

//Command initialization
int i;
for(i = 0; i < MAX_ARGS; i++ )
{
    command.argv[i] = (char *) malloc(MAX_ARG_LEN);
}

//get all directories from PATH env var
enviromentlength = parsePath(pathv);

//Main loop
while(TRUE)
{
    redirectionsituation = 0;
    pipesituation = 0;
    background = 0;
    //Read the command line
    printPrompt();
    readCommand(commandLine);

    //input nothing
    if(commandLine[0] == '\0')
    {

        continue;
    }

    //quit the shell?
    if((strcmp(commandLine, "exit") == 0) || (strcmp(commandLine, "quit") == 0))
    {
        break;
    }

    //if it is background running
    if(commandLine[strlen(commandLine) - 1] == '&')
    {
        printf("backgrond\n");
        tempchar = strtok (commandLine, "&");
        //strcpy(commandLine, tempchar);
        printf("%s\n", tempchar);
        background = 1;

    }

    //Parse the command line
    commandlength = parseCommand(commandLine);

    //if the command is "cd"
    if(strcmp(command.argv[0], "cd") == 0)
    {
        do_cd(command.argv);
        continue;
    }

    //Get the full path name
    command.name = lookupPath(pathv, command.argv);
    printf("command name %s\n", command.name);

    //report error
    if( command.name == NULL)
    {

        continue;  //non-fatal
    }

    //if redirection is required
    for(i = 0; i < commandlength; i++)
    {
        if(strcmp(command.argv[i], ">") == 0)
        {
            redirectionsituation = 1;
            break;
        }

    }
    if(redirectionsituation == 1)
    {
        redirection(command.name, command.argv, i, thisChPID);
        continue;
    }

    //if pipe is required
    for(i = 0; i < commandlength; i++)
    {
        if(strcmp(command.argv[i], "|") == 0)
        {
            pipesituation = 1;
            break;
        }

    }
    if(pipesituation == 1)
    {    //run pipe
        piperun(command.name, command.argv, i, thisChPID);

        continue;
    }

    //normal running
    if((thisChPID=fork()) < 0)
    {
        fprintf(stderr, "fork failed\n");
    }
        else if(thisChPID == 0)
        {
            //printf("run again\n");
            execve(command.name, command.argv, pathv);

        }
        else
        {
            //do not put the process in the background, wait until the     child process terminates
            if(background == 0)
            {
            wait(&stat);
            }

        }
    }
    return 0;
}


问:
Complex query combining
First of all, thank you for reading my problem. I am very thankful for the people in the community helping others learn more about coding. As this SQL and PHP is part of my hobby, I am limited by Google and fora where I can find answers to my questions. Unfortunately, I can't find a good answer for a problem encountered.

What am I trying to do?

I run a website where you can note your kilometers and liters you filled your car and see your statistics. I want to do a big search in MySQL with a query. I know how to get the results in multiple queries (3 to be exact), but I need it to be in one single query.

What does my table look look like?

For an example I am using this table to make the problem more visual, it's named 'fillings' for now.

```<code>+---------+---------+------------+--------+--------+------------+
| tank_id | user_id | kilometers | liters | car_id | date       |
+---------+---------+------------+--------+--------+------------+
| 1       | 2       | 450        | 20     | 2      | 2017-11-01 |
+---------+---------+------------+--------+--------+------------+
| 2       | 1       | 500        | 30     | 1      | 2017-12-15 |
+---------+---------+------------+--------+--------+------------+
| 3       | 2       | 490        | 25     | 2      | 2017-11-05 |
+---------+---------+------------+--------+--------+------------+
| 4       | 3       | 260        | 19     | 3      | 2017-11-07 |
+---------+---------+------------+--------+--------+------------+
| 5       | 3       | 610        | 30     | 3      | 2017-12-03 |
+---------+---------+------------+--------+--------+------------+
| 6       | 3       | 100        | 4      | 3      | 2017-12-07 |
+---------+---------+------------+--------+--------+------------+
</code>```

This is a basic idea of my main table where all the fill-ups are being registrated. In reality someone can have multiple cars, but for now let's asume that a user only has one car.

What are the SQL queries?

The query that I want to make should have this result:

```<code>+---------+----------------------+---------------------+
| user_id | consumption november | consumption overall |
+---------+----------------------+---------------------+
| 2       | 20,9                 | 20,9                |
+---------+----------------------+---------------------+
| 1       |                      | 16,7                |
+---------+----------------------+---------------------+
| 3       | 13,7                 | 18,3                |
+---------+----------------------+---------------------+
</code>```

As you can see, the fillings of november are taking and a consumption is being calculated. Also, an overall consumption is being calculated of all fillings from a certain type of user. I know how to make this result, devided in two queries. That's:

```<code>SELECT user_id, SUM(kilometers) / SUM(liters) as consumption overall
FROM fillings
GROUP BY user_id
</code>```

And also the query:

```<code>SELECT user_id, SUM(kilometers) / SUM(liters) as consumption november
FROM fillings
WHERE 'date'
BETWEEN '2017-11-01' AND '2017-11-31'
GROUP BY user_id
</code>```

So right now I want to combine the queries into one, so that I can get the result that I want. Note that in the example, someone can have a null consumption in a month, because hé or she did not fill up their car in that month.

I've looked into the options of UNION and JOIN but I can't seem to find a way to make this working.

I hope everything is clear, and if not, don't hesitate to ask and I will explain in further detail.

Thanks in advance.

答:
Just use conditional aggregation:</p>

```<code>SELECT user_id,
       (SUM(CASE WHEN date >= '2017-11-01' AND date < '2017-12-01'
                 THEN kilometers ELSE 0
            END) /
        SUM(CASE WHEN date >= '2017-11-01' AND date < '2017-12-01'
                 THEN liters
            END)
       ) as consumption_november,
       SUM(kilometers) / SUM(liters) as consumption_overall
FROM fillings
GROUP BY user_id
</code>```

Title: Complex query combining

Body:
First of all, thank you for reading my problem. I am very thankful for the people in the community helping others learn more about coding. As this SQL and PHP is part of my hobby, I am limited by Google and fora where I can find answers to my questions. Unfortunately, I can't find a good answer for a problem encountered.

What am I trying to do?

I run a website where you can note your kilometers and liters you filled your car and see your statistics. I want to do a big search in MySQL with a query. I know how to get the results in multiple queries (3 to be exact), but I need it to be in one single query.

What does my table look look like?

For an example I am using this table to make the problem more visual, it's named 'fillings' for now.

+---------+---------+------------+--------+--------+------------+
| tank_id | user_id | kilometers | liters | car_id | date       |
+---------+---------+------------+--------+--------+------------+
| 1       | 2       | 450        | 20     | 2      | 2017-11-01 |
+---------+---------+------------+--------+--------+------------+
| 2       | 1       | 500        | 30     | 1      | 2017-12-15 |
+---------+---------+------------+--------+--------+------------+
| 3       | 2       | 490        | 25     | 2      | 2017-11-05 |
+---------+---------+------------+--------+--------+------------+
| 4       | 3       | 260        | 19     | 3      | 2017-11-07 |
+---------+---------+------------+--------+--------+------------+
| 5       | 3       | 610        | 30     | 3      | 2017-12-03 |
+---------+---------+------------+--------+--------+------------+
| 6       | 3       | 100        | 4      | 3      | 2017-12-07 |
+---------+---------+------------+--------+--------+------------+

This is a basic idea of my main table where all the fill-ups are being registrated. In reality someone can have multiple cars, but for now let's asume that a user only has one car.

What are the SQL queries?

The query that I want to make should have this result:

+---------+----------------------+---------------------+
| user_id | consumption november | consumption overall |
+---------+----------------------+---------------------+
| 2       | 20,9                 | 20,9                |
+---------+----------------------+---------------------+
| 1       |                      | 16,7                |
+---------+----------------------+---------------------+
| 3       | 13,7                 | 18,3                |
+---------+----------------------+---------------------+

As you can see, the fillings of november are taking and a consumption is being calculated. Also, an overall consumption is being calculated of all fillings from a certain type of user. I know how to make this result, devided in two queries. That's:

SELECT user_id, SUM(kilometers) / SUM(liters) as consumption overall
FROM fillings
GROUP BY user_id

And also the query:

SELECT user_id, SUM(kilometers) / SUM(liters) as consumption november
FROM fillings
WHERE 'date'
BETWEEN '2017-11-01' AND '2017-11-31'
GROUP BY user_id

So right now I want to combine the queries into one, so that I can get the result that I want. Note that in the example, someone can have a null consumption in a month, because hé or she did not fill up their car in that month.

I've looked into the options of UNION and JOIN but I can't seem to find a way to make this working.

I hope everything is clear, and if not, don't hesitate to ask and I will explain in further detail.

Thanks in advance.

Body:
Just use conditional aggregation:

SELECT user_id,
       (SUM(CASE WHEN date >= '2017-11-01' AND date < '2017-12-01'
                 THEN kilometers ELSE 0
            END) /
        SUM(CASE WHEN date >= '2017-11-01' AND date < '2017-12-01'
                 THEN liters
            END)
       ) as consumption_november,
       SUM(kilometers) / SUM(liters) as consumption_overall
FROM fillings
GROUP BY user_id


问:
TypeError: Cannot read property 'setAutocompactionInterval' of undefined
My database has several duplicates (same _id), even after restarting and using autoload: true. This is strange, but I decided to solve it by using the setAutocompactionInterval as is suggested in the guide in the repository, and the result was simply TypeError: Cannot read property 'setAutocompactionInterval' of undefined.

```<code>const Db = require('nedb-promise')
    , curry = new Db({
        filename: 'curry'
        , autoload: true
        , onload: (e) => e && console.err(e)
    })

curry.persistence.setAutocompactionInterval(3600000)
// TypeError: Cannot read property 'setAutocompactionInterval' of undefined
Db.persistence.setAutocompactionInterval(3600000)
// TypeError: Cannot read property 'setAutocompactionInterval' of undefined
Db.curry.persistence.setAutocompactionInterval(3600000)
// TypeError: Cannot read property 'persistence' of undefined
</code>```

I don't know what causes this error. I think I will make a Github issue on nedb-promise, but is this because of a misuse? Am I misunderstanding the way it should work? Nobody seems to have this error, according to my Google searches.

答:
This question was already answered in https://github.com/jrop/nedb-promise/issues/6

nedb-promise doesn't have persistence and thus it is undefined, so this problem should be solved by using nedb directly.

Body:
My database has several duplicates (same _id), even after restarting and using autoload: true. This is strange, but I decided to solve it by using the setAutocompactionInterval as is suggested in the guide in the repository, and the result was simply TypeError: Cannot read property 'setAutocompactionInterval' of undefined.

const Db = require('nedb-promise')
    , curry = new Db({
        filename: 'curry'
        , autoload: true
        , onload: (e) => e && console.err(e)
    })

curry.persistence.setAutocompactionInterval(3600000)
// TypeError: Cannot read property 'setAutocompactionInterval' of undefined
Db.persistence.setAutocompactionInterval(3600000)
// TypeError: Cannot read property 'setAutocompactionInterval' of undefined
Db.curry.persistence.setAutocompactionInterval(3600000)
// TypeError: Cannot read property 'persistence' of undefined

I don't know what causes this error. I think I will make a Github issue on nedb-promise, but is this because of a misuse? Am I misunderstanding the way it should work? Nobody seems to have this error, according to my Google searches.


答:
If Manual.pdf is in the folder of the executable, use:

```<code>QDesktopServices::openUrl(QUrl("file:///" + QApplication::applicationDirPath() + "/Manual.pdf"));
</code>```

If you later decide to put the pdf in a dedicated sub-folder, e.g. doc, in the code above replace /Manual.pdf with /doc/Manual.pdf.

Title: How can I open a pdf with a relative path using the default application in a Qt program

Body:
If Manual.pdf is in the folder of the executable, use:

QDesktopServices::openUrl(QUrl("file:///" + QApplication::applicationDirPath() + "/Manual.pdf"));

If you later decide to put the pdf in a dedicated sub-folder, e.g. doc, in the code above replace /Manual.pdf with /doc/Manual.pdf.


问:
How to go from Try to Catch in specific condition in Try
I have a specific condition in try want it to be in catch if happened

```<code>string x;
try {
    if(x==null)
        //send to catch
}
catch {
    //Show messagebox
}
</code>```

I tried throw new Exception but found most of answers here recommend not to use and i have more than 1 condition i want to send each separated to handle in different catch
so is this possible or I should just spam if else ?

what I realy trying to do is that

I have 2 TextBox want to make sure they not empty and 2 DateTime Picker want to make sure 1always before the other (start date and end date)

答:
you can use throwing an exception into try to go straight to catch.

see below code: SOME_System_Exception can be any system exceptions

```<code>string x;
try {
    if(x==null)
        throw new SOME_System_Exception();
}
catch {
    //Show messagebox
}
</code>```

Body:
I have a specific condition in try want it to be in catch if happened

string x;
try {
    if(x==null)
        //send to catch
}
catch {
    //Show messagebox
}

I tried throw new Exception but found most of answers here recommend not to use and i have more than 1 condition i want to send each separated to handle in different catch
so is this possible or I should just spam if else ?

what I realy trying to do is that

I have 2 TextBox want to make sure they not empty and 2 DateTime Picker want to make sure 1always before the other (start date and end date)

Body:
you can use throwing an exception into try to go straight to catch.

see below code: SOME_System_Exception can be any system exceptions

string x;
try {
    if(x==null)
        throw new SOME_System_Exception();
}
catch {
    //Show messagebox
}


问:
How to plot keys and values from dictionary in histogram
I need to plot a histogram with the following dictionary

```<code>x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405}
</code>```

I need first keys be ordered from 1 to 9. Then the values will be plotted in the histogram, showing a maximum probability of 1.0. I have tried the following (plus other stuff).

```<code>import matplotlib.pyplot as plt
import numpy as np

plt.hist(x.keys(), x.values(), color='g', label = "Real distribution")
plt.show()
</code>```

Or

```<code>plt.hist (x, bins = np.arange(9), color = 'g', label = "Real distribution")
plt.show()
</code>```

Or

```<code>fsn_count_ = sorted(fsn_count)

plt.hist (fsn_count_, bins = np.arange(9), color = 'b', label = "Real distribution")
plt.plot ([0] + bf, color = 'g', label = "Benford Model")
plt.xlabel ('Significant number')
plt.ylabel ('Percentage')
plt.xlim (1,9)
plt.ylim (0,1)
plt.legend (bbox_to_anchor = (1, 1), loc="upper right", borderaxespad=0.)
plt.savefig (country_ + '.png')
plt.show ()
plt.clf ()

distribution_sum = sum(bf)
print('The sum of percentage distribution is:', distribution_sum)
</code>```

答:
I'm sorry in advance for how terribly un-pythonic and weird my code is. I'm not too strong with mathplot or with numpy.

If you used the_keys = list(set(dict.keys())) to get a set of the keys (ordered, because it was a set. Like I said in comments, I'm doing some pretty ugly hacking here.) you can then do the_values = [x[i] for i in the_keys] to get a list representation of the dictionary ordered by keys. Then plot it with

```<code>plt.hist(the_keys, the_values, color='g', label = "Real distribution")
plt.show()
</code>```

Body:
I need to plot a histogram with the following dictionary

x = {5:289, 8:341, 1:1565, 4:655, 2:1337, 9:226, 7:399, 3:967, 6:405}

I need first keys be ordered from 1 to 9. Then the values will be plotted in the histogram, showing a maximum probability of 1.0. I have tried the following (plus other stuff).

import matplotlib.pyplot as plt
import numpy as np

plt.hist(x.keys(), x.values(), color='g', label = "Real distribution")
plt.show()

Or

plt.hist (x, bins = np.arange(9), color = 'g', label = "Real distribution")
plt.show()

Or

fsn_count_ = sorted(fsn_count)

plt.hist (fsn_count_, bins = np.arange(9), color = 'b', label = "Real distribution")
plt.plot ([0] + bf, color = 'g', label = "Benford Model")
plt.xlabel ('Significant number')
plt.ylabel ('Percentage')
plt.xlim (1,9)
plt.ylim (0,1)
plt.legend (bbox_to_anchor = (1, 1), loc="upper right", borderaxespad=0.)
plt.savefig (country_ + '.png')
plt.show ()
plt.clf ()

distribution_sum = sum(bf)
print('The sum of percentage distribution is:', distribution_sum)

Body:
I'm sorry in advance for how terribly un-pythonic and weird my code is. I'm not too strong with mathplot or with numpy.

If you used the_keys = list(set(dict.keys())) to get a set of the keys (ordered, because it was a set. Like I said in comments, I'm doing some pretty ugly hacking here.) you can then do the_values = [x[i] for i in the_keys] to get a list representation of the dictionary ordered by keys. Then plot it with

plt.hist(the_keys, the_values, color='g', label = "Real distribution")
plt.show()


问:
Removing the contents of /dev/mapper/vg_ volume when 100%
On a CentOS Linux box, when I run the following:

```<code>df-h
</code>```

I get that vg_name-1v_root is at 100%.

```<code>Filesystem                      Size  Used Avail Use% Mounted on
/dev/mapper/vg_name-lv_root     12G   12G     0 100% /
</code>```

When I drill down to /dev/mapper it looks like this vg_name-1v_root is a soft link to ../dm-0.

However i'm not able to get into vg_name-1v_root or the ../dm-0 directories.

I am able to run lsblk, vgs and lvs to view the volume, but cannot enter it or view the contents.

I've spent some time googling and searching Stack Overflow. How can I delete or even view what's in the directory /dev/mapper/vg_name-1v_root?

Many thanks in advance.

答:
You're looking at the wrong column in the df output. That's a device, not a directory. In the Mounted on column, you see that the device is mounted on /, the root directory. It contains all of the files that aren't under any other mount point - your /bin, your /etc, your /lib, and depending on your setup, maybe your /usr, /tmp, /home... anything at the top level that you don't see listed separately in the output of df or mount.

To find out what's taking up space on that filesystem, you can run du from the root directory, using the -x option to prevent it from crossing into other filesystems.

```<code>cd /
du -x
</code>```

Body:
On a CentOS Linux box, when I run the following:

df-h

I get that vg_name-1v_root is at 100%.

Filesystem                      Size  Used Avail Use% Mounted on
/dev/mapper/vg_name-lv_root     12G   12G     0 100% /

When I drill down to /dev/mapper it looks like this vg_name-1v_root is a soft link to ../dm-0.

However i'm not able to get into vg_name-1v_root or the ../dm-0 directories.

I am able to run lsblk, vgs and lvs to view the volume, but cannot enter it or view the contents.

I've spent some time googling and searching Stack Overflow. How can I delete or even view what's in the directory /dev/mapper/vg_name-1v_root?

Many thanks in advance.

Body:
You're looking at the wrong column in the df output. That's a device, not a directory. In the Mounted on column, you see that the device is mounted on /, the root directory. It contains all of the files that aren't under any other mount point - your /bin, your /etc, your /lib, and depending on your setup, maybe your /usr, /tmp, /home... anything at the top level that you don't see listed separately in the output of df or mount.

To find out what's taking up space on that filesystem, you can run du from the root directory, using the -x option to prevent it from crossing into other filesystems.

cd /
du -x


答:
Use window functions:</p>

```<code>select t.*
from (select t.*,
             row_number() over (partition by id order by score1 asc, score2 desc) as seqnum
      from t
     ) t
where seqnum = 1;
</code>```

Title: Retrieve the minimum value of a column from the max value of another column

Body:
I have a hive table t1 that looks like this:

ID   Score1    score2
1     4         11
1     5         12
1     5         13
2     3         14
2     3         15
2     2         12
2     2         11
3     6         10
3     6         11
3     6         12

I want for each ID, to select the max value of score1, and if the max value exists more than once, then from the rows that contain max(score1) I want to get min(score2).

So, I want the minimum score2 of the maximum score1 rows, the results should be something like this

ID    Score1    score2
1     5         12
2     3         14
3     6         10

Most of the ideas I have turn this to be a very complicated query, and I think there is a simple solution for it that I am not able to find yet.

Any ideas?

Body:
Use window functions:

select t.*
from (select t.*,
             row_number() over (partition by id order by score1 asc, score2 desc) as seqnum
      from t
     ) t
where seqnum = 1;


问:
Find the first record according to a chain of JOIN rules in SQL
I need to find a "best fit" record by using a multi-field relation.
I need to JOIN based on 3 fields, if this fails use 2 fileds, and if this fails use 1-filed condition, etc.
Such chain can be long, fields can vary, etc.
How to achieve this.

Below I present some ideas but somehow feel this could be done better.

First way (I don't like the UNION because I guess the engine will execute them all regardless of the LIMIT 1 clause which could work as "stop on first found":

```<code>SELECT A1, A2, A3, B4 FROM A
LEFT OUTER JOIN (SELECT B4 FROM
      ((SELECT B4, 1 AS ORD FROM B
            WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3)
      UNION ALL
      (SELECT B4, 2 AS ORD FROM B
            WHERE B.B1 = A.A1 AND B.B2 = A.B2)
      UNION ALL
      (SELECT B4, 3 AS ORD FROM B
            WHERE B.B1 = A.A1)) ORDER BY ORD ASC LIMIT 1);
</code>```

Second way (here I don't like the repeated SELECT IN WHEN and again in THEN section, also it is only good when a single field is returned

```<code>SELECT A1, A2, A3,
    CASE
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3)
            THEN
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3 LIMIT 1)
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2)
            THEN
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 LIMIT 1)
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1)
            THEN (SELECT B4 FROM B WHERE B.B1 = A.A1 LIMIT 1)
        ELSE NULL
    END AS B4
FROM A;
</code>```

I use postgreSQL 9.6 but the questions should be treated as standard SQL question.

Code to test:

```<code>CREATE TABLE A (A1 INT, A2 INT, A3 INT);
CREATE TABLE B (B1 INT, B2 INT, B3 INT, B4 VARCHAR(2));

INSERT INTO A VALUES
    (10, 20, 30),
    (11, 21, 31),
    (12, 22, 32),
    (13, 23, 33),
    (14, 24, 34);

INSERT INTO B VALUES
    (10, 20,    30, 'A1'),
    (11, 21,    0,  'B'),
    (12, 0,     0,  'C'),
    (10, 23,    30, 'A2'),
    (14, 0,     34, 'D');

/*
EXPECTED RESULT
10, 20, 30, A1
11, 21, 31, B
12, 22, 32, C
*/
</code>```

答:
Quick Example:

```<code>SELECT * FROM (
    SELECT
    CONCAT(B1,"-",B2,"-",B3) AS B_CONDITION1,
    CONCAT(B1,"-",B2) AS B_CONDITION2,
    B1 AS B_CONDITION3,
    b.*
    FROM b
) AS b_tmp
INNER JOIN
(
    SELECT
    CONCAT(A1,"-",A2,"-",A3) AS A_CONDITION1,
    CONCAT(A1,"-",A2) AS A_CONDITION2,
    A1 AS A_CONDITION3
    FROM a
) AS a_tmp ON
(a_tmp.A_CONDITION1 = b_tmp.B_CONDITION1 OR a_tmp.A_CONDITION2 = b_tmp.B_CONDITION2 OR a_tmp.A_CONDITION3 = b_tmp.B_CONDITION3)
</code>```

You must to see with big data it behaviour.. Sorry my english, Good Work!

Body:
I need to find a "best fit" record by using a multi-field relation.
I need to JOIN based on 3 fields, if this fails use 2 fileds, and if this fails use 1-filed condition, etc.
Such chain can be long, fields can vary, etc.
How to achieve this.

Below I present some ideas but somehow feel this could be done better.

First way (I don't like the UNION because I guess the engine will execute them all regardless of the LIMIT 1 clause which could work as "stop on first found":

SELECT A1, A2, A3, B4 FROM A
LEFT OUTER JOIN (SELECT B4 FROM
      ((SELECT B4, 1 AS ORD FROM B
            WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3)
      UNION ALL
      (SELECT B4, 2 AS ORD FROM B
            WHERE B.B1 = A.A1 AND B.B2 = A.B2)
      UNION ALL
      (SELECT B4, 3 AS ORD FROM B
            WHERE B.B1 = A.A1)) ORDER BY ORD ASC LIMIT 1);

Second way (here I don't like the repeated SELECT IN WHEN and again in THEN section, also it is only good when a single field is returned

SELECT A1, A2, A3,
    CASE
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3)
            THEN
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 AND B.B3 = A.A3 LIMIT 1)
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2)
            THEN
            (SELECT B4 FROM B WHERE B.B1 = A.A1 AND B.B2 = A.B2 LIMIT 1)
        WHEN EXISTS
            (SELECT B4 FROM B WHERE B.B1 = A.A1)
            THEN (SELECT B4 FROM B WHERE B.B1 = A.A1 LIMIT 1)
        ELSE NULL
    END AS B4
FROM A;

I use postgreSQL 9.6 but the questions should be treated as standard SQL question.

Code to test:

CREATE TABLE A (A1 INT, A2 INT, A3 INT);
CREATE TABLE B (B1 INT, B2 INT, B3 INT, B4 VARCHAR(2));

INSERT INTO A VALUES
    (10, 20, 30),
    (11, 21, 31),
    (12, 22, 32),
    (13, 23, 33),
    (14, 24, 34);

INSERT INTO B VALUES
    (10, 20,    30, 'A1'),
    (11, 21,    0,  'B'),
    (12, 0,     0,  'C'),
    (10, 23,    30, 'A2'),
    (14, 0,     34, 'D');

/*
EXPECTED RESULT
10, 20, 30, A1
11, 21, 31, B
12, 22, 32, C
*/

Body:
Quick Example:

SELECT * FROM (
    SELECT
    CONCAT(B1,"-",B2,"-",B3) AS B_CONDITION1,
    CONCAT(B1,"-",B2) AS B_CONDITION2,
    B1 AS B_CONDITION3,
    b.*
    FROM b
) AS b_tmp
INNER JOIN
(
    SELECT
    CONCAT(A1,"-",A2,"-",A3) AS A_CONDITION1,
    CONCAT(A1,"-",A2) AS A_CONDITION2,
    A1 AS A_CONDITION3
    FROM a
) AS a_tmp ON
(a_tmp.A_CONDITION1 = b_tmp.B_CONDITION1 OR a_tmp.A_CONDITION2 = b_tmp.B_CONDITION2 OR a_tmp.A_CONDITION3 = b_tmp.B_CONDITION3)

You must to see with big data it behaviour.. Sorry my english, Good Work!


问:
react-stripe-elements getting "Cannot read property 'props' of undefined"
Following react-stripe-elements sample in readme file. I can set up the stripe form properly but I get below error on pressing pay button.

```<code>Uncaught TypeError: Cannot read property 'props' of undefined
    at handleSubmit (paymentForm.jsx?9f51:10)
    at HTMLUnknownElement.callCallback (react-dom.development.js?cada:540)
    at Object.invokeGuardedCallbackDev (react-dom.development.js?cada:579)
    at Object.invokeGuardedCallback (react-dom.development.js?cada:436)
....
</code>```

My paymentForm.jsx is like this:

import React from 'react';
import {injectStripe} from 'react-stripe-elements';

import PaymentCard from './paymentCard'

```<code>class PaymentForm extends React.Component {

  handleSubmit(ev) {
    ev.preventDefault();
    this.props.stripe.createToken({name: 'Jenny Rosen'}).then(({token}) => {
      console.log('Received Stripe token:', token);
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <PaymentCard />
        <button>Pay</button>
      </form>
    )
  }

}
export default injectStripe(PaymentForm);
</code>```

答:
Ok problem is solved by binding the the function to the class</p>

```<code>  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this)
  }
</code>```

Body:
Following react-stripe-elements sample in readme file. I can set up the stripe form properly but I get below error on pressing pay button.

Uncaught TypeError: Cannot read property 'props' of undefined
    at handleSubmit (paymentForm.jsx?9f51:10)
    at HTMLUnknownElement.callCallback (react-dom.development.js?cada:540)
    at Object.invokeGuardedCallbackDev (react-dom.development.js?cada:579)
    at Object.invokeGuardedCallback (react-dom.development.js?cada:436)
....

My paymentForm.jsx is like this:

import React from 'react';
import {injectStripe} from 'react-stripe-elements';

import PaymentCard from './paymentCard'

class PaymentForm extends React.Component {

  handleSubmit(ev) {
    ev.preventDefault();
    this.props.stripe.createToken({name: 'Jenny Rosen'}).then(({token}) => {
      console.log('Received Stripe token:', token);
    });
  }

  render() {
    return (
      <form onSubmit={this.handleSubmit}>
        <PaymentCard />
        <button>Pay</button>
      </form>
    )
  }

}
export default injectStripe(PaymentForm);

Body:
Ok problem is solved by binding the the function to the class

  constructor(props) {
    super(props);
    this.handleSubmit = this.handleSubmit.bind(this)
  }


问:
Make and Expression available to be used within a Linq to EntityFramework Expression
I have the following LINQ Expression that I need to be able to use within a LINQ to Entities query.

There is currently a property like this:

```<code>[NotMapped]
public Clinic CurrentClinic
{
  get { return AdmissionRoot.CurrentFacility.Compile()(this); }
}
</code>```

Which called the following:

```<code>public static Expression<Func<Admission, Clinic>> CurrentFacility =
         a => a.Person.PersonLocations.Any(p => p.Clinic.FacilityType != (int)Clinic.FacilityTypes.CommunityServices)
                ? a.Person.PersonLocations.Where(p => p.Clinic.FacilityType != (int)Clinic.FacilityTypes.CommunityServices)
                   .OrderByDescending(l => l.TransferDate)
                   .ThenByDescending(l => l.LocationId)
                   .FirstOrDefault().Clinic
                : a.Clinic;
</code>```

The issue is that I cannot use CurrentClinic within a LINQ to Entities statement because it will give the following error:

"The specified type member 'CurrentClinic' is not supported in LINQ to
  Entities"

I am new to LINQ to Entities expressions and was hoping someone would be able to refactor this so it can be used within a LINQ to Entities statement something like this:

```<code>Db.Admissions.Where(
       a =>
            (a.CurrentClinic != null
              && !a.CurrentClinic.Company.IsHomeCompany
              && a.ReferralClinicId == clinicid
            )
          ||
            (a.CurrentClinic.Company.IsHomeCompany
              && a.CurrentClinic.ClinicId == clinicid
            )
        );
</code>```

If it can't be done in an Expression that I can "add" other criteria onto the end then is there another way/suggestion that would work without compromising speed too much?

答:
The issue here is because you're using CurrentClinic in your query which is not something that Entity framework can turn into an expression. A possible alternate way to run your query could be

```<code>Db.Admissions
    .Select(a => new
    {
        CurrentClinic = CurrentFacility(a),
        Admission = a
    })
    .Where(a =>
        (a.CurrentClinic != null && !a.CurrentClinic.Company.IsHomeCompany && a.Admission.ReferralClinicId == clinicid) ||
        (a.CurrentClinic.Company.IsHomeCompany && a.CurrentClinic.ClinicId == clinicid));
</code>```

Note: this is untested but should still work.

Body:
I have the following LINQ Expression that I need to be able to use within a LINQ to Entities query.

There is currently a property like this:

[NotMapped]
public Clinic CurrentClinic
{
  get { return AdmissionRoot.CurrentFacility.Compile()(this); }
}

Which called the following:

public static Expression<Func<Admission, Clinic>> CurrentFacility =
         a => a.Person.PersonLocations.Any(p => p.Clinic.FacilityType != (int)Clinic.FacilityTypes.CommunityServices)
                ? a.Person.PersonLocations.Where(p => p.Clinic.FacilityType != (int)Clinic.FacilityTypes.CommunityServices)
                   .OrderByDescending(l => l.TransferDate)
                   .ThenByDescending(l => l.LocationId)
                   .FirstOrDefault().Clinic
                : a.Clinic;

The issue is that I cannot use CurrentClinic within a LINQ to Entities statement because it will give the following error:

"The specified type member 'CurrentClinic' is not supported in LINQ to
  Entities"

I am new to LINQ to Entities expressions and was hoping someone would be able to refactor this so it can be used within a LINQ to Entities statement something like this:

Db.Admissions.Where(
       a =>
            (a.CurrentClinic != null
              && !a.CurrentClinic.Company.IsHomeCompany
              && a.ReferralClinicId == clinicid
            )
          ||
            (a.CurrentClinic.Company.IsHomeCompany
              && a.CurrentClinic.ClinicId == clinicid
            )
        );

If it can't be done in an Expression that I can "add" other criteria onto the end then is there another way/suggestion that would work without compromising speed too much?

Body:
The issue here is because you're using CurrentClinic in your query which is not something that Entity framework can turn into an expression. A possible alternate way to run your query could be

Db.Admissions
    .Select(a => new
    {
        CurrentClinic = CurrentFacility(a),
        Admission = a
    })
    .Where(a =>
        (a.CurrentClinic != null && !a.CurrentClinic.Company.IsHomeCompany && a.Admission.ReferralClinicId == clinicid) ||
        (a.CurrentClinic.Company.IsHomeCompany && a.CurrentClinic.ClinicId == clinicid));

Note: this is untested but should still work.


问:
jquery callback not using global variable
I have a small script that gets the location from geoplugin... i want to store the returned co-ords in a variable i have declared globally... but for some reason the callback wont read it. How do i make the callback use the global variable?

```<code>if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        myLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
    }, function() {
        noLocation();
    },{timeout: 20});
}
else if (google.gears) {
    var geo = google.gears.factory.create('beta.geolocation');
    geo.getCurrentPosition(function(position) {
        myLocation = new google.maps.LatLng(position.latitude,position.longitude);
    }, function() {
        noLocation();
    });
}
else {
    noLocation();
}
function noLocation() {
$.getJSON("http://www.geoplugin.net/json.gp?id=117.201.92.17&jsoncallback=?",
    function(data) {
        if (data != "" && data.geoplugin_latitude != "")
            myLocation =  new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude)
        else
            myLocation = new google.maps.LatLng()
    });
</code>```

}

For some reason i think its because of the asynchronous call... Can i get over the issue some how?

答:
It looks like it is storing it in the global variable "myLocation". However, it's likely that you are attempting to read the value before it has actually been set. The way an asynchronous call works is that it returns immediately, then sometime in the future, it will call the callback function if and when the request gets a response. The rest of your code will continue to run in the meantime.

Try an "alert" after the assignment to myLocation to see if it is being populated:

```<code>myLocation =  new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude)
alert(myLocation)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a small script that gets the location from geoplugin... i want to store the returned co-ords in a variable i have declared globally... but for some reason the callback wont read it. How do i make the callback use the global variable?

if(navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
        myLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
    }, function() {
        noLocation();
    },{timeout: 20});
}
else if (google.gears) {
    var geo = google.gears.factory.create('beta.geolocation');
    geo.getCurrentPosition(function(position) {
        myLocation = new google.maps.LatLng(position.latitude,position.longitude);
    }, function() {
        noLocation();
    });
}
else {
    noLocation();
}
function noLocation() {
$.getJSON("http://www.geoplugin.net/json.gp?id=117.201.92.17&jsoncallback=?",
    function(data) {
        if (data != "" && data.geoplugin_latitude != "")
            myLocation =  new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude)
        else
            myLocation = new google.maps.LatLng()
    });

}

For some reason i think its because of the asynchronous call... Can i get over the issue some how?

Body:
It looks like it is storing it in the global variable "myLocation". However, it's likely that you are attempting to read the value before it has actually been set. The way an asynchronous call works is that it returns immediately, then sometime in the future, it will call the callback function if and when the request gets a response. The rest of your code will continue to run in the meantime.

Try an "alert" after the assignment to myLocation to see if it is being populated:

myLocation =  new google.maps.LatLng(data.geoplugin_latitude, data.geoplugin_longitude)
alert(myLocation)


问:
Nested Jinja2 for loops
I'm passing 2 variables (3 including a simple one) to some Jinja from a python script.

On certain runs I want to generate a list with links.

```<code><html>
<body>
    <h1>{{ title }}</h1>
    <table>

        {% if packageURLs is defined %}
            {% for x in packageURLs: %}
                <a href="{{ x }}">
            {% endfor %}

            {% for i in packagesList: %}
                <tr><td>{{ i }}</td></tr>

            {% endfor %}

        {" else "}

            {% for i in packagesList: %}
                <tr><td>{{ i }}</td></tr>

            {% endfor %}
        {% endif %}

        </a>
    </table>
</body>
</code>```

for each 'packageURLs' I want to add a  tag then some table tags for 'packages' List. What's happening though is its generating HTML but completing each individual for loop first. So I end up with half a page full of links then another with table rows. How can I have it iterate through both initially?

答:
I found a solution:

```<code><html>
<body>
    <h1>{{ title }}</h1>
    <table>

        {% if packageURLs is defined %}
            {% for i,x in packagesList  %}
                <a href="{{ x }}">
                    <tr><td>{{ i }}</td></tr>
                </a>
            {% endfor %}

        {" else "}

            {% for i in packagesList: %}
                <tr><td>{{ i }}</td></tr>

            {% endfor %}
        {% endif %}

    </table>
</body>
</code>```

Which is populated using zip() in the python script:

```<code>f = t.render(title=dataType,packagesList=zip(Info,packageURLs),packageURLs=packageURLs)
</code>```

I kept the last variable out of laziness as a check since I still want to only execute those different chunks sometimes.

Title: Nested Jinja2 for loops

Body:
I'm passing 2 variables (3 including a simple one) to some Jinja from a python script.

On certain runs I want to generate a list with links.

{{ title }}

        {% if packageURLs is defined %}
            {% for x in packageURLs: %}

            {% endfor %}

            {% for i in packagesList: %}

{{ i }}

            {% endfor %}

        {" else "}

            {% for i in packagesList: %}

{{ i }}

            {% endfor %}
        {% endif %}

for each 'packageURLs' I want to add a  tag then some table tags for 'packages' List. What's happening though is its generating HTML but completing each individual for loop first. So I end up with half a page full of links then another with table rows. How can I have it iterate through both initially?

Body:
I found a solution:

<html>
<body>
    <h1>{{ title }}</h1>
    <table>

        {% if packageURLs is defined %}
            {% for i,x in packagesList  %}
                <a href="{{ x }}">
                    <tr><td>{{ i }}</td></tr>
                </a>
            {% endfor %}

        {" else "}

            {% for i in packagesList: %}
                <tr><td>{{ i }}</td></tr>

            {% endfor %}
        {% endif %}

    </table>
</body>

Which is populated using zip() in the python script:

f = t.render(title=dataType,packagesList=zip(Info,packageURLs),packageURLs=packageURLs)

I kept the last variable out of laziness as a check since I still want to only execute those different chunks sometimes.


问:
Separate decode/encode interfaces or in one interface
I'm creating an implementation that performs conversion from one form to another.

The design problem I am facing now is whether the Encoder and Decoder API should be in one interface or in separate ones. e.g. Apache MINA uses separate interfaces

I am currently doing something like this:

```<code>interface Convertor
{
    A encode( B b );

    B decode( A a );
}
</code>```

The rationale for putting them in one interface is that you can centralize the implementations and fix any protocol changes in one place. Any thoughts on this ?

答:
Making them separate is a lot more flexible.  If you write separate interfaces you can always combine them into a third interface that you use whenever you need both encode and decode functions.

The reverse is not true.  If you write one interface from the start, you lose the flexibility to choose to include only encode or decode functions.

Body:
I'm creating an implementation that performs conversion from one form to another.

The design problem I am facing now is whether the Encoder and Decoder API should be in one interface or in separate ones. e.g. Apache MINA uses separate interfaces

I am currently doing something like this:

interface Convertor
{
    A encode( B b );

    B decode( A a );
}

The rationale for putting them in one interface is that you can centralize the implementations and fix any protocol changes in one place. Any thoughts on this ?

OwnerDisplayName: Bill the Lizard


问:
LINQ to Entities does not recognize the method
I am following this article on MSDN. I ported it to EF Code First.

```<code>public interface IUnitOfWork
{
    IRepository<Employee> Employees { get; }
    IRepository<TimeCard> TimeCards { get; }
    void Commit();
}
</code>```

```<code>public class HrContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<TimeCard> TimeCards { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>()
                    .HasMany(e => e.TimeCards)
                    .WithOptional(tc => tc.Employee);
     }
}
</code>```

```<code>public class SqlRepository<T> : IRepository<T>
    where T : class
{
    private readonly DbSet<T> entitySet;
    public SqlRepository(DbContext context)
    {
        this.entitySet = context.Set<T>();
    }
    public void Add(T newEntity)
    {
        this.entitySet.Add(newEntity);
    }
    public IQueryable<T> FindAll()
    {
        return this.entitySet;
    }
    public T FindById(params object[] keys)
    {
        return this.entitySet.Find(keys);
    }
    public IQueryable<T> FindWhere(Expression<Func<T, bool>> predicate)
    {
        return this.entitySet.Where(predicate);
    }
    public void Remove(T entity)
    {
        this.entitySet.Remove(entity);
    }
}
</code>```

```<code>public class SqlUnitOfWork : IUnitOfWork, IDisposable
{
    private readonly HrContext context;
    private IRepository<Employee> employees;
    private IRepository<TimeCard> timeCards;
    public SqlUnitOfWork()
    {
        this.context = new HrContext();
    }
    public IRepository<Employee> Employees
    {
        get
        {
            return new SqlRepository<Employee>(context);
        }
    }
    public IRepository<TimeCard> TimeCards
    {
        get
        {
            return new SqlRepository<TimeCard>(context);
        }
    }
    public void Commit()
    {
        this.context.SaveChanges();
    }
    public void Dispose()
    {
        context.Dispose();
    }
}
</code>```

```<code>var query = from e in unitOfWork.Employees.FindAll()
            from tc in unitOfWork.TimeCards.FindAll()
            where tc.Employee.Id == e.Id && e.Name.StartsWith("C")
            select tc;
var timeCards = query.ToList();
</code>```

This model is great as it gives me testability. However, running queries like the one above throws this

```<code>LINQ to Entities does not recognize the method
 'System.Linq.IQueryable`1[DomainModel.Models.TimeCard] FindAll()'
  method, and this method cannot be translated into a store expression.
</code>```

I understand the error but is there any way to avoid it but still keep the repositories for testability?

答:
Your select statement cannot be translated due to the nature of how IQueryable<T> and the query providers work: see this thread for more info What is the difference between IQueryable<T> and IEnumerable<T>?

You can 'help' the linq provider by dividing your expression into separate statements like this:

```<code>var ems = unitOfWork.Employees.FindAll();
var tcs = unitOfWork.TimeCards.FindAll();

var query = from e in ems
            from tc in tcs
            where tc.Employee.Id == e.Id && e.Name.StartsWith("C")
            select tc;
</code>```

Or you can let FindAll() return IEnumerable<T> instead of IQueryable<T> and then your original expression should work.

Body:
I am following this article on MSDN. I ported it to EF Code First.

public interface IUnitOfWork
{
    IRepository<Employee> Employees { get; }
    IRepository<TimeCard> TimeCards { get; }
    void Commit();
}

public class HrContext : DbContext
{
    public DbSet<Employee> Employees { get; set; }
    public DbSet<TimeCard> TimeCards { get; set; }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Employee>()
                    .HasMany(e => e.TimeCards)
                    .WithOptional(tc => tc.Employee);
     }
}

public class SqlRepository<T> : IRepository<T>
    where T : class
{
    private readonly DbSet<T> entitySet;
    public SqlRepository(DbContext context)
    {
        this.entitySet = context.Set<T>();
    }
    public void Add(T newEntity)
    {
        this.entitySet.Add(newEntity);
    }
    public IQueryable<T> FindAll()
    {
        return this.entitySet;
    }
    public T FindById(params object[] keys)
    {
        return this.entitySet.Find(keys);
    }
    public IQueryable<T> FindWhere(Expression<Func<T, bool>> predicate)
    {
        return this.entitySet.Where(predicate);
    }
    public void Remove(T entity)
    {
        this.entitySet.Remove(entity);
    }
}

public class SqlUnitOfWork : IUnitOfWork, IDisposable
{
    private readonly HrContext context;
    private IRepository<Employee> employees;
    private IRepository<TimeCard> timeCards;
    public SqlUnitOfWork()
    {
        this.context = new HrContext();
    }
    public IRepository<Employee> Employees
    {
        get
        {
            return new SqlRepository<Employee>(context);
        }
    }
    public IRepository<TimeCard> TimeCards
    {
        get
        {
            return new SqlRepository<TimeCard>(context);
        }
    }
    public void Commit()
    {
        this.context.SaveChanges();
    }
    public void Dispose()
    {
        context.Dispose();
    }
}

var query = from e in unitOfWork.Employees.FindAll()
            from tc in unitOfWork.TimeCards.FindAll()
            where tc.Employee.Id == e.Id && e.Name.StartsWith("C")
            select tc;
var timeCards = query.ToList();

This model is great as it gives me testability. However, running queries like the one above throws this

LINQ to Entities does not recognize the method
 'System.Linq.IQueryable`1[DomainModel.Models.TimeCard] FindAll()'
  method, and this method cannot be translated into a store expression.

I understand the error but is there any way to avoid it but still keep the repositories for testability?

Body:
Your select statement cannot be translated due to the nature of how IQueryable<T> and the query providers work: see this thread for more info What is the difference between IQueryable<T> and IEnumerable<T>?

You can 'help' the linq provider by dividing your expression into separate statements like this:

var ems = unitOfWork.Employees.FindAll();
var tcs = unitOfWork.TimeCards.FindAll();

var query = from e in ems
            from tc in tcs
            where tc.Employee.Id == e.Id && e.Name.StartsWith("C")
            select tc;

Or you can let FindAll() return IEnumerable<T> instead of IQueryable<T> and then your original expression should work.