问:
Python Dataframe Groupby function not producing expected output
I have been struggling with this for several days, this is my last resort.

Here is an example of my data

```<code>| PRODUCT NAME   | PRICE | LINK      | INSTOCK | TAGS   |
|----------------|-------|-----------|---------|--------|
| the best shirt | 1.00  | www.alink | true    | cotton |
| the best shirt | 1.00  | www.alink | true    | yellow |
| the best pants | 2.00  | www.alink | true    | denim  |
</code>```

and here is what I would like

```<code>| PRODUCT NAME   | PRICE | LINK      | INSTOCK | TAGS           |
|----------------|-------|-----------|---------|----------------|
| the best shirt | 1.00  | www.alink | true    | cotton, yellow |
| the best pants | 2.00  | www.alink | true    | denim          |
</code>```

this is the code I am using

```<code>df = df.groupby(['PRODUCT NAME', 'PRICE', 'LINK', 'INSTOCK'])[['TAGS']].apply(', '.join)
</code>```

and this is what I get

```<code>| 0    |
|------|
| TAGS |
</code>```

I am completely at a loss of what could be causing this. Thanks in advance <3

答:
Looking at the output, I would assume your problem stems from having NaNs in your data .

Referring to your example, for me this approach works:

```<code>products = {'PRODUCT NAME': ['the best shirt', 'the best shirt', 'the best pants'],
            'PRICE': [1.00, 1.00, 2.00],
            'LINK': ['link', 'link', 'link'],
            'INSTOCK': [True, True, True],
            'TAGS': ['cotton', 'yellow', 'denim']}
df = pd.DataFrame(products)
df = df.groupby(['PRODUCT NAME','PRICE','LINK','INSTOCK']).TAGS.apply(lambda x: ', '.join(x)).reset_index()
df
</code>```

Your result

Body:
I have been struggling with this for several days, this is my last resort.

Here is an example of my data

| PRODUCT NAME   | PRICE | LINK      | INSTOCK | TAGS   |
|----------------|-------|-----------|---------|--------|
| the best shirt | 1.00  | www.alink | true    | cotton |
| the best shirt | 1.00  | www.alink | true    | yellow |
| the best pants | 2.00  | www.alink | true    | denim  |

and here is what I would like

| PRODUCT NAME   | PRICE | LINK      | INSTOCK | TAGS           |
|----------------|-------|-----------|---------|----------------|
| the best shirt | 1.00  | www.alink | true    | cotton, yellow |
| the best pants | 2.00  | www.alink | true    | denim          |

this is the code I am using

df = df.groupby(['PRODUCT NAME', 'PRICE', 'LINK', 'INSTOCK'])[['TAGS']].apply(', '.join)

and this is what I get

| 0    |
|------|
| TAGS |

I am completely at a loss of what could be causing this. Thanks in advance <3

Body:
Looking at the output, I would assume your problem stems from having NaNs in your data .

Referring to your example, for me this approach works:

products = {'PRODUCT NAME': ['the best shirt', 'the best shirt', 'the best pants'],
            'PRICE': [1.00, 1.00, 2.00],
            'LINK': ['link', 'link', 'link'],
            'INSTOCK': [True, True, True],
            'TAGS': ['cotton', 'yellow', 'denim']}
df = pd.DataFrame(products)
df = df.groupby(['PRODUCT NAME','PRICE','LINK','INSTOCK']).TAGS.apply(lambda x: ', '.join(x)).reset_index()
df

Your result


来源: stackexchange

问:
Check if string exists in JSON array in SQL
Trying to return rows that the JSON value contains a certain value.

```<code>Table Structure
ID     Mapping
1      {"DepartmentID":"Finishing","ShipToIDs":[],"ItemIDs":[]}
2      {"DepartmentID":"Finishing","ShipToIDs":["100"],"ItemIDs":["300-VLR1022A"]}
3      {"DepartmentID":"Finishing","ShipToIDs":["100"],"ItemIDs":[]}
</code>```

For example, passing in ShipToIDs = 100 would return rows 2-3 and passing in ItemID = 300-VLR1022A would return row 2.

答:
From SQL Server 2017+, you can use OPENJSON with a dynamic path

DECLARE @path nvarchar(max) = N'$.ShipToIDs';
DECLARE @value nvarchar(max) = N'100';

SELECT *
FROM YourTable t
WHERE EXISTS (SELECT 1
    FROM OPENJSON(t.Mapping, @path) j
    WHERE j.value = @value);
```

db<>fiddle

ContentLicense: CC BY-SA 4.0

Body:
Trying to return rows that the JSON value contains a certain value.

Table Structure
ID     Mapping
1      {"DepartmentID":"Finishing","ShipToIDs":[],"ItemIDs":[]}
2      {"DepartmentID":"Finishing","ShipToIDs":["100"],"ItemIDs":["300-VLR1022A"]}
3      {"DepartmentID":"Finishing","ShipToIDs":["100"],"ItemIDs":[]}

For example, passing in ShipToIDs = 100 would return rows 2-3 and passing in ItemID = 300-VLR1022A would return row 2.

Body:
From SQL Server 2017+, you can use OPENJSON with a dynamic path

DECLARE @path nvarchar(max) = N'$.ShipToIDs';
DECLARE @value nvarchar(max) = N'100';

SELECT *
FROM YourTable t
WHERE EXISTS (SELECT 1
    FROM OPENJSON(t.Mapping, @path) j
    WHERE j.value = @value);

db<>fiddle


问:
Groupby within groups
I have data like this:

```<code>df = pd.DataFrame({
    'a': ['milk', 'eggs', 'eggs', 'butter', 'butter',
          'milk', 'eggs', 'eggs', 'butter', 'butter'],
    'b': ['billy', 'bob', 'frank', 'frank', 'sue',
          'frank', 'sue', 'sue', 'sue', 'sue'],
    'c': ['1/30', '1/30', '1/31', '1/31', '1/31',
          '3/31', '3/31', '3/31', '5/31', '5/31'],
}, index=list('ABCDEFGHIJ'))
</code>```

I want the inverse of the counts for each distinct value of c in b. Billy and Bob each have one distinct value in c, so their counts are both equal to one. Frank has two dates, so his is 0.5, etc.

Desired output:

```<code>A    1.000000
B    1.000000
C    0.500000
D    0.500000
E    0.333333
F    0.500000
G    0.333333
H    0.333333
I    0.333333
J    0.333333
dtype: float64
</code>```

I think I need to manipulate groupby(some group).count() and/or groupby(some group).transform('count'), but I'm not sure how to manipulate them and what else I need (if anything) - or if there's a better way.

I tried variations on

```<code>df.groupby(['b', 'c'], as_index=False)['c'].transform('count').reset_index()
</code>```

(based on aggregating within a groupby), to no avail.

I could probably figure out an "ugly" way but I'd very much like to know how to do this in 1-2 lines (if possible).

Thanks!

Title: Groupby within groups

Body:
I have data like this:

df = pd.DataFrame({
    'a': ['milk', 'eggs', 'eggs', 'butter', 'butter',
          'milk', 'eggs', 'eggs', 'butter', 'butter'],
    'b': ['billy', 'bob', 'frank', 'frank', 'sue',
          'frank', 'sue', 'sue', 'sue', 'sue'],
    'c': ['1/30', '1/30', '1/31', '1/31', '1/31',
          '3/31', '3/31', '3/31', '5/31', '5/31'],
}, index=list('ABCDEFGHIJ'))

I want the inverse of the counts for each distinct value of c in b. Billy and Bob each have one distinct value in c, so their counts are both equal to one. Frank has two dates, so his is 0.5, etc.

Desired output:

A    1.000000
B    1.000000
C    0.500000
D    0.500000
E    0.333333
F    0.500000
G    0.333333
H    0.333333
I    0.333333
J    0.333333
dtype: float64

I think I need to manipulate groupby(some group).count() and/or groupby(some group).transform('count'), but I'm not sure how to manipulate them and what else I need (if anything) - or if there's a better way.

I tried variations on

df.groupby(['b', 'c'], as_index=False)['c'].transform('count').reset_index()

(based on aggregating within a groupby), to no avail.

I could probably figure out an "ugly" way but I'd very much like to know how to do this in 1-2 lines (if possible).

Thanks!

Body:
groupby.transform should suffice :

1/ df.groupby("b").c.transform("nunique")
A    1.000000
B    1.000000
C    0.500000
D    0.500000
E    0.333333
F    0.500000
G    0.333333
H    0.333333
I    0.333333
J    0.333333
Name: c, dtype: float64


问:
How to get IP address of device in Unity 2018+?
How to get IP address on C# in program which developing for android device in Unity 2018.2+?

Seems like Network.player.ipAddress is deprecated right now, so I'm looking for a new way.

答:
https://stackoverflow.com/a/67450052/18192881

In regards to the geofilter data post, according to their Terms:
"RESTRICTIONS.
General. You may not, nor may you permit others to:

ix: use the Services for the purpose of identifying or locating a specific individual or household."

So I wouldn't rely on them for this, as it is 'illegal?' or at least against thier policy.


问:
Visual Studio Asp.net Website Compilation error: Child nodes not allowed
"Child nodes not allowed" seems to be notorious compilation error on Asp.net website if you do some googling.

Environment: WinXp, VS2008 and VS2008 SP1, .NET 3.5 SP1

Behavior: create a brand new Asp.net website (not web application), then just build it, you got compilation error "Child nodes not allowed" on the Web.config on line where it says providerOption name="CompilerVersion" value="v3.5"/>

I got this problem after I re-installed vs2008.  Now, a lot of people are suggesting fixes but none worked for us.  Only one guy mentioned he successfully got rid of this problem by re-installing windows, but we don't want to go that far if we don't have to.  There is another person who opened a ticket to MS but hasn't gotten back a response yet.

If there is anyone out there who has similar environment like us and know how to get around this problem, we'd really appreciate it!!!

Edit  The weirdest part of all this is that I don't know how I got it.  It is a brand new box and brand new installation.

答:
My colleague just found a fix for this dreadful problem, it is a .NET Framework Cleanup Utility at http://cid-27e6a35d1a492af7.skydrive.live.com/self.aspx/Blog|_Tools/dotnetfx20|_cleanup|_tool.zip

Just download, run and restart your machine and re-install .NET Framework 3.5 SP1 (since the cleanup util removes all the .NET Frameworks for you)!  Really hope this could help others who have the same problem, it's been 4 days fighting with this one issue, thanks Microsoft!

Thank you guys very much for your input, I voted up for you both, appreciate it!

Ray.

ContentLicense: CC BY-SA 3.0

LastEditorDisplayName: moocha

ContentLicense: CC BY-SA 2.5


问:
Flex 3: Strange behavior when function does a simple math operation
So, in one of my modules, a variable named numDays is created by looping through some XML data and finding the maximum value of an xml field calls days.  After the numDays variable is found, I use it to find the width of a canvas by doing:

```<code>wrapper.width = numDays * parentApplication.oneDay;
</code>```

(oneDay is a value determined by dividing the width of the window by 14)

So, now that I know how wide the wrapper canvas is, I can start to fill it.  I have four items that are going into the wrapper: 1) Role description, 2) left controller, 3) name textbox (auto suggest component), 4) right controller.  The width of the role description is 30px.  The left and right controllers are 20 px each.  So in order to get the width of the name textbox, I have a function that does the following:

```<code>nameTextbox.width = wrapper.width - 70;
</code>```

for some reason when I do this, the application doesn't load fully.  It pretty much stalls out.  I have 30 "projects" with 15 "positions" within each of them.  the wrapper.width is describing the width of a position, so there are 450 name textboxes trying to be figured out.  Is this why it's messing up?

EDIT

So, from the main application, the project module is called.  From within the project module, a list is created with a datasource of "positionsAC":

```<code><mx:List id="wholePosition" dataProvider="{positionsAC}" width="100%" height="100%" paddingBottom="0" paddingLeft="0" paddingRight="0" paddingTop="0" backgroundAlpha="0" verticalScrollPolicy="off" itemRenderer="modules.position" useRollOver="false" selectable="false">
</code>```

Below is a c/p of the position module in it's entirety

```<code><?xml version="1.0" encoding="utf-8"?>
<mx:Module xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:components="com.hillelcoren.components.*" dataChange="allData = data as Array" layout="absolute" creationComplete="init();" horizontalScrollPolicy="off">
<mx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;
        import mx.controls.Alert;

        [Bindable] public var positionInfo:Array;
        [Bindable] public var wholePositionID:Number;
        [Bindable] public var allData:Array;

        [Bindable] public var positions:XML;
        [Bindable] public var startOffset:Number;
        [Bindable] public var numDays:Number;
        [Bindable] public var role:String;
        [Bindable] public var studentID:Number;
        [Bindable] public var conflict:Number;
        [Bindable] public var studentType:String;
        [Bindable] public var showInPrinciple:Number;

        [Bindable] public var positionX:Number = 0;
        [Bindable] public var positionWidth:Number = 0;
        [Bindable] public var sName:String = new String;
        [Bindable] public var asAC:ArrayCollection = new ArrayCollection;
        [Bindable] public var conflictBG:uint = 0xffffff;
        [Bindable] public var roleColor:uint = 0x000000;

        private function init():void
        {
            if (allData)
            {
                getInfo(allData);
                setBGColor();
                getPositionX();
                getPositionWidth();
                getRightStudents();
            }
        }

        private function getInfo(a:Array):void
        {
            var tempArray:Array = new Array;

            startOffset = Number(a[0]);
            numDays = Number(a[1]);
            positionWidth = parentApplication.oneDay * numDays;
            setStudentNameW();
            role = a[2];
            studentID = Number(a[3]);
            tempArray = parentApplication.studentsDBIDDict[String(studentID)] as Array;
            conflict = Number(a[4]);
            studentType = a[5];
            sName = "test";
            showInPrinciple = a[6];
        }

        private function setStudentNameW():void
        {
            if (numDays == 1)
            {
                studentName.width = 55;
                studentName.x = 37;
                contractLeft.visible = false;
                contractRight.visible = false;
            }
            else if (numDays == 2)
            {
                Alert.show("HI");
                studentName.width = 133;
            }
            else if (numDays == 3)
                studentName.width = 230;
            else if (numDays == 4)
                studentName.width = 330;

            if (numDays > 1)
            {
                studentName.x = 47;
                contractLeft.visible = true;
                contractRight.visible = true;
            }
        }

        public function setBGColor():void
        {
            if (conflict == 1)
                conflictBG = parentApplication.errorColor;
            else if (conflict == 2)
                conflictBG = parentApplication.okErrorColor;
            else
                conflictBG = 0xFFFFFF;
        }

        private function getPositionX():void
        {
            positionX = parentApplication.oneDay * startOffset - 1;
        }

        private function getPositionWidth():void
        {
            positionWidth = parentApplication.oneDay * numDays;
        }

        private function getRightStudents():void
        {
            if (studentType == "freshman")
                makeASAC(parentApplication.freshmanAC);
            else if (studentType == "bfa1")
                makeASAC(parentApplication.bfa1AC);
            else if (studentType == "bfa2")
                makeASAC(parentApplication.bfa2AC);
            else if (studentType == "bfa3")
                makeASAC(parentApplication.bfa3AC);
            else if (studentType == "mfa1")
                makeASAC(parentApplication.mfa1AC);
            else if (studentType == "mfa2")
                makeASAC(parentApplication.mfa2AC);
            else if (studentType == "mfa3")
                makeASAC(parentApplication.mfa3AC);
            else if (studentType == "mfaw1")
                makeASAC(parentApplication.mfaw1AC);
            else if (studentType == "mfaw2")
                makeASAC(parentApplication.mfaw2AC);
            else if (studentType == "mfaw3")
                makeASAC(parentApplication.mfaw3AC);
        }

        private function makeASAC(students:ArrayCollection):void
        {
            for (var i:int = 0; i < students.length; i++)
                asAC.addItem(parentApplication.getStudentName(students.getItemAt(i)));
        }

        private function posLength(whichSide:String, expandContract:String):void
        {
            if (whichSide == 'l')
            {
                if (expandContract == 'e')
                {
                    if (startOffset > 0)
                    {
                        numDays++;
                        startOffset--;
                        getPositionX();
                        getPositionWidth();
                    }
                }
                else if (expandContract == 'c')
                {
                    if (numDays > 1)
                    {
                        numDays--;
                        startOffset++;
                        getPositionX();
                        getPositionWidth();
                    }
                }
            }
            else if (whichSide == 'r')
            {
                if (expandContract == 'e')
                {
                    if (numDays + startOffset < parentDocument.projectLength)
                    {
                        numDays++;
                        getPositionX();
                        getPositionWidth();
                    }
                }
                else if (expandContract == 'c')
                {
                    if (numDays > 1)
                    {
                        numDays--;
                        getPositionX();
                        getPositionWidth();
                    }
                }
            }

            //parentApplication.conflicts();
        }
    ]]>
</mx:Script>

<mx:Canvas id="positionWrapper" width="{positionWidth}" height="25" backgroundColor="#ffffff" horizontalScrollPolicy="off" borderColor="#000000" borderStyle="solid" borderThickness="1">
    <mx:Text id="roleText" text="{role}" width="25" y="3" color="{roleColor}" fontSize="11" fontWeight="bold" click="parentApplication.getDictLen(parentApplication.studentsDBIDDict)" />
    <mx:Canvas id="leftSide" x="25" width="22" height="100%" mouseOver="expandLeft.visible = true; contractLeft.visible = true;" mouseOut="expandLeft.visible = false; contractLeft.visible = false;" backgroundColor="{conflictBG}" horizontalScrollPolicy="off">
        <mx:Image id="expandLeft" source="images/addRed.png" y="5" click="posLength('l', 'e')" mouseOver="parentApplication.switchCursor(true);" mouseOut="parentApplication.switchCursor(false);" visible="false" />
        <mx:Image id="contractLeft" source="images/minusRed.png" x="10" y="5" click="posLength('l', 'c')" mouseOver="parentApplication.switchCursor(true);" mouseOut="parentApplication.switchCursor(false);" visible="false" />
    </mx:Canvas>
    <components:AutoComplete id="studentName" textAlign="center"
        dataProvider="{asAC}"
        x="47" y="3"
    />
    <mx:Image id="showSNW" source="images/searchicon.png" x="{(studentName.width + studentName.x) - 12}" y="5" visible="false" mouseOver="parentApplication.switchCursor(true); studentName.enabled = false;" mouseOut="parentApplication.switchCursor(false); studentName.enabled = true; showSNW.visible = false;" />
    <mx:Canvas id="rightSide" x="{positionWrapper.width - 22}" width="20" height="100%" mouseOver="expandRight.visible = true; contractRight.visible = true;" mouseOut="expandRight.visible = false; contractRight.visible = false;" backgroundColor="{conflictBG}" horizontalScrollPolicy="off">
        <mx:Image id="contractRight" source="images/minusRed.png" y="5" click="posLength('r', 'c')" visible="false" mouseOver="parentApplication.switchCursor(true);" mouseOut="parentApplication.switchCursor(false);" />
        <mx:Image id="expandRight" source="images/addRed.png" x="10" y="5" click="posLength('r', 'e')" visible="false" mouseOver="parentApplication.switchCursor(true);" mouseOut="parentApplication.switchCursor(false);" />
    </mx:Canvas>
</mx:Canvas>
</code>```

答:
Best to get a debugger. Flash Builder 4 is a pretty decent one, and they even give out free standard licenses to

Students, faculty and staff of eligible educational institutions

Software developers who are affected by the current economic condition and are currently unemployed

Event attendees who receive a special promotional code at their event

Check this out

Also, get debugger versions of the latest Flash Player here

The free standard might take some time to come, but you can always use the free trial in the meanwhile.

When you debug, check that nameTextBox is not null.

Body:
So, in one of my modules, a variable named numDays is created by looping through some XML data and finding the maximum value of an xml field calls days.  After the numDays variable is found, I use it to find the width of a canvas by doing:

wrapper.width = numDays * parentApplication.oneDay;

(oneDay is a value determined by dividing the width of the window by 14)

So, now that I know how wide the wrapper canvas is, I can start to fill it.  I have four items that are going into the wrapper: 1) Role description, 2) left controller, 3) name textbox (auto suggest component), 4) right controller.  The width of the role description is 30px.  The left and right controllers are 20 px each.  So in order to get the width of the name textbox, I have a function that does the following:

nameTextbox.width = wrapper.width - 70;

for some reason when I do this, the application doesn't load fully.  It pretty much stalls out.  I have 30 "projects" with 15 "positions" within each of them.  the wrapper.width is describing the width of a position, so there are 450 name textboxes trying to be figured out.  Is this why it's messing up?

EDIT

So, from the main application, the project module is called.  From within the project module, a list is created with a datasource of "positionsAC":

<mx:List id="wholePosition" dataProvider="{positionsAC}" width="100%" height="100%" paddingBottom="0" paddingLeft="0" paddingRight="0" paddingTop="0" backgroundAlpha="0" verticalScrollPolicy="off" itemRenderer="modules.position" useRollOver="false" selectable="false">

Below is a c/p of the position module in it's entirety

<?xml version="1.0" encoding="utf-8"?>
<mx:Module xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:components="com.hillelcoren.components.*" dataChange="allData = data as Array" layout="absolute" creationComplete="init();" horizontalScrollPolicy="off">
<mx:Script>
    <![CDATA[
        import mx.collections.ArrayCollection;
        import mx.controls.Alert;

        [Bindable] public var positionInfo:Array;
        [Bindable] public var wholePositionID:Number;
        [Bindable] public var allData:Array;

        [Bindable] public var positions:XML;
        [Bindable] public var startOffset:Number;
        [Bindable] public var numDays:Number;
        [Bindable] public var role:String;
        [Bindable] public var studentID:Number;
        [Bindable] public var conflict:Number;
        [Bindable] public var studentType:String;
        [Bindable] public var showInPrinciple:Number;

        [Bindable] public var positionX:Number = 0;
        [Bindable] public var positionWidth:Number = 0;
        [Bindable] public var sName:String = new String;
        [Bindable] public var asAC:ArrayCollection = new ArrayCollection;
        [Bindable] public var conflictBG:uint = 0xffffff;
        [Bindable] public var roleColor:uint = 0x000000;

        private function init():void
        {
            if (allData)
            {
                getInfo(allData);
                setBGColor();
                getPositionX();
                getPositionWidth();
                getRightStudents();
            }
        }

        private function getInfo(a:Array):void
        {
            var tempArray:Array = new Array;

            startOffset = Number(a[0]);
            numDays = Number(a[1]);
            positionWidth = parentApplication.oneDay * numDays;
            setStudentNameW();
            role = a[2];
            studentID = Number(a[3]);
            tempArray = parentApplication.studentsDBIDDict[String(studentID)] as Array;
            conflict = Number(a[4]);
            studentType = a[5];
            sName = "test";
            showInPrinciple = a[6];
        }

        private function setStudentNameW():void
        {
            if (numDays == 1)
            {
                studentName.width = 55;
                studentName.x = 37;
                contractLeft.visible = false;
                contractRight.visible = false;
            }
            else if (numDays == 2)
            {
                Alert.show("HI");
                studentName.width = 133;
            }
            else if (numDays == 3)
                studentName.width = 230;
            else if (numDays == 4)
                studentName.width = 330;

            if (numDays > 1)
            {
                studentName.x = 47;
                contractLeft.visible = true;
                contractRight.visible = true;
            }
        }

        public function setBGColor():void
        {
            if (conflict == 1)
                conflictBG = parentApplication.errorColor;
            else if (conflict == 2)
                conflictBG = parentApplication.okErrorColor;
            else
                conflictBG = 0xFFFFFF;
        }

        private function getPositionX():void
        {
            positionX = parentApplication.oneDay * startOffset - 1;
        }

        private function getPositionWidth():void
        {
            positionWidth = parentApplication.oneDay * numDays;
        }

        private function getRightStudents():void
        {
            if (studentType == "freshman")
                makeASAC(parentApplication.freshmanAC);
            else if (studentType == "bfa1")
                makeASAC(parentApplication.bfa1AC);
            else if (studentType == "bfa2")
                makeASAC(parentApplication.bfa2AC);
            else if (studentType == "bfa3")
                makeASAC(parentApplication.bfa3AC);
            else if (studentType == "mfa1")
                makeASAC(parentApplication.mfa1AC);
            else if (studentType == "mfa2")
                makeASAC(parentApplication.mfa2AC);
            else if (studentType == "mfa3")
                makeASAC(parentApplication.mfa3AC);
            else if (studentType == "mfaw1")
                makeASAC(parentApplication.mfaw1AC);
            else if (studentType == "mfaw2")
                makeASAC(parentApplication.mfaw2AC);
            else if (studentType == "mfaw3")
                makeASAC(parentApplication.mfaw3AC);
        }

        private function makeASAC(students:ArrayCollection):void
        {
            for (var i:int = 0; i < students.length; i++)
                asAC.addItem(parentApplication.getStudentName(students.getItemAt(i)));
        }

        private function posLength(whichSide:String, expandContract:String):void
        {
            if (whichSide == 'l')
            {
                if (expandContract == 'e')
                {
                    if (startOffset > 0)
                    {
                        numDays++;
                        startOffset--;
                        getPositionX();
                        getPositionWidth();
                    }
                }
                else if (expandContract == 'c')
                {
                    if (numDays > 1)
                    {
                        numDays--;
                        startOffset++;
                        getPositionX();
                        getPositionWidth();
                    }
                }
            }
            else if (whichSide == 'r')
            {
                if (expandContract == 'e')
                {
                    if (numDays + startOffset < parentDocument.projectLength)
                    {
                        numDays++;
                        getPositionX();
                        getPositionWidth();
                    }
                }
                else if (expandContract == 'c')
                {
                    if (numDays > 1)
                    {
                        numDays--;
                        getPositionX();
                        getPositionWidth();
                    }
                }
            }

            //parentApplication.conflicts();
        }
    ]]>
</mx:Script>

<mx:Canvas id="positionWrapper" width="{positionWidth}" height="25" backgroundColor="#ffffff" horizontalScrollPolicy="off" borderColor="#000000" borderStyle="solid" borderThickness="1">
    <mx:Text id="roleText" text="{role}" width="25" y="3" color="{roleColor}" fontSize="11" fontWeight="bold" click="parentApplication.getDictLen(parentApplication.studentsDBIDDict)" />
    <mx:Canvas id="leftSide" x="25" width="22" height="100%" mouseOver="expandLeft.visible = true; contractLeft.visible = true;" mouseOut="expandLeft.visible = false; contractLeft.visible = false;" backgroundColor="{conflictBG}" horizontalScrollPolicy="off">
        <mx:Image id="expandLeft" source="images/addRed.png" y="5" click="posLength('l', 'e')" mouseOver="parentApplication.switchCursor(true);" mouseOut="parentApplication.switchCursor(false);" visible="false" />
        <mx:Image id="contractLeft" source="images/minusRed.png" x="10" y="5" click="posLength('l', 'c')" mouseOver="parentApplication.switchCursor(true);" mouseOut="parentApplication.switchCursor(false);" visible="false" />
    </mx:Canvas>
    <components:AutoComplete id="studentName" textAlign="center"
        dataProvider="{asAC}"
        x="47" y="3"
    />
    <mx:Image id="showSNW" source="images/searchicon.png" x="{(studentName.width + studentName.x) - 12}" y="5" visible="false" mouseOver="parentApplication.switchCursor(true); studentName.enabled = false;" mouseOut="parentApplication.switchCursor(false); studentName.enabled = true; showSNW.visible = false;" />
    <mx:Canvas id="rightSide" x="{positionWrapper.width - 22}" width="20" height="100%" mouseOver="expandRight.visible = true; contractRight.visible = true;" mouseOut="expandRight.visible = false; contractRight.visible = false;" backgroundColor="{conflictBG}" horizontalScrollPolicy="off">
        <mx:Image id="contractRight" source="images/minusRed.png" y="5" click="posLength('r', 'c')" visible="false" mouseOver="parentApplication.switchCursor(true);" mouseOut="parentApplication.switchCursor(false);" />
        <mx:Image id="expandRight" source="images/addRed.png" x="10" y="5" click="posLength('r', 'e')" visible="false" mouseOver="parentApplication.switchCursor(true);" mouseOut="parentApplication.switchCursor(false);" />
    </mx:Canvas>
</mx:Canvas>


问:
repairing data search code from mysql database using dropdown list
I'm trying edit a code from this tutorial: [https://www.youtube.com/watch?v=fSIg5y5QXbc&ab_channel=Webslesson][1]. The problem is a sytuation when two or more countires have the same state name (imagination only). For example, USA and Russia have the same "xyz" state, and when I select USA and state: "xyz", the program sees no difference (as if it just forgot which country we are in) and displays all the cities in the "xyz" state from both country.
Can you help me resolve this problem?

EDIT: I think i'm close, but i need to know, how to save for example: $select_country=(selected country) in fetch.php file

index.php

```<code><?php
//index.php

include('database_connection.php');

$country = '';

$query = "
 SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC
";
$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

foreach($result as $row)
{
 $country .= '<option value="'.$row["country"].'">'.$row["country"].'</option>';
}

?>
<!DOCTYPE html>
<html>
 <head>
  <title>Insert Dynamic Multi Select Box Data using Jquery Ajax PHP</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  <script src="jquery.lwMultiSelect.js"></script>
  <link rel="stylesheet" href="jquery.lwMultiSelect.css" />
 </head>
 <body>
  <br /><br />
  <div class="container" style="width:600px;">
   <h2 align="center">Insert Dynamic Multi Select Box Data using Jquery Ajax PHP</h2><br /><br />
   <form method="post" id="insert_data">
    <select name="country" id="country" class="form-control action">
     <option value="">Select Country</option>
     <?php echo $country; ?>
    </select>
    <br />
    <select name="state" id="state" class="form-control action">
     <option value="">Select State</option>
    </select>
    <br />
    <select name="city" id="city" multiple class="form-control">
    </select>
    <br />
    <input type="hidden" name="hidden_city" id="hidden_city" />
    <input type="submit" name="insert" id="action" class="btn btn-info" value="Insert" />
   </form>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){

 $('#city').lwMultiSelect();

 $('.action').change(function(){
  if($(this).val() != '')
  {
   var action = $(this).attr("id");
   var query = $(this).val();
   var result = '';
   if(action == 'country')
   {
    result = 'state';
   }
   else
   {
    result = 'city';
   }
   $.ajax({
    url:'fetch.php',
    method:"POST",
    data:{action:action, query:query},
    success:function(data)
    {
     $('#'+result).html(data);
     if(result == 'city')
     {
      $('#city').data('plugin_lwMultiSelect').updateList();
     }
    }
   })
  }
 });

 $('#insert_data').on('submit', function(event){
  event.preventDefault();
  if($('#country').val() == '')
  {
   alert("Please Select Country");
   return false;
  }
  else if($('#state').val() == '')
  {
   alert("Please Select State");
   return false;
  }
  else if($('#city').val() == '')
  {
   alert("Please Select City");
   return false;
  }
  else
  {
   $('#hidden_city').val($('#city').val());
   $('#action').attr('disabled', 'disabled');
   var form_data = $(this).serialize();
   $.ajax({
    url:"insert.php",
    method:"POST",
    data:form_data,
    success:function(data)
    {
     $('#action').attr("disabled", "disabled");
     if(data == 'done')
     {
      $('#city').html('');
      $('#city').data('plugin_lwMultiSelect').updateList();
      $('#city').data('plugin_lwMultiSelect').removeAll();
      $('#insert_data')[0].reset();
      alert('Data Inserted');
     }
    }
   });
  }
 });

});
</script>
</code>```

fetch.php

```<code><?php
//fetch.php

if(isset($_POST['action']))
{
 include('database_connection.php');

 $output = '';

 if($_POST["action"] == 'country')
 {
  $query = "
  SELECT state FROM country_state_city
  WHERE country = :country
  GROUP BY state
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    ':country'  => $_POST["query"]
   )
  );
  $result = $statement->fetchAll();
  $output .= '<option value="">Select State</option>';
  foreach($result as $row)
  {
   $output .= '<option value="'.$row["state"].'">'.$row["state"].'</option>';
  }
 }
 if($_POST["action"] == 'state')
 {
  $query = "
  SELECT city FROM country_state_city
  WHERE state = :state
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    ':state'  => $_POST["query"]
   )
  );
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $output .= '<option value="'.$row["city"].'">'.$row["city"].'</option>';
  }

 }
 echo $output;
}

?>
</code>```

I don't add "insert.php" because I don't even use it

答:
For situations like this, the countries, states and cities should all be store in separate tables.
Then you link them with the help of foreign keys.

But since all the records live in one table in your case, you can add the selected country to your queries to ensure that only records belonging to a particular country and/or state are affected.

As you can see below, var country = $('#country').val(); gets the selected country and was added to the ajax request. And then, included in the select query on the server.

index.php

```<code><?php
//index.php

include('database_connection.php');

$country = '';

$statement = $connect->prepare("
    SELECT country
    FROM country_state_city
    GROUP BY country
    ORDER BY country ASC
");

$statement->execute();

while($row=$statement->fetch()){
    $country .= '<option value="'.$row["country"].'">'.$row["country"].'</option>';
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Insert Dynamic Multi Select Box Data using Jquery Ajax PHP</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="jquery.lwMultiSelect.js"></script>
    <link rel="stylesheet" href="jquery.lwMultiSelect.css" />
</head>
<body>
    <br /><br />
    <div class="container" style="width:600px;">
        <h2 align="center">Insert Dynamic Multi Select Box Data using Jquery Ajax PHP</h2><br /><br />
        <form method="post" id="insert_data">
            <select name="country" id="country" class="form-control action">
                <option value="">Select Country</option>
                <?php echo $country; ?>
            </select>
            <br />
            <select name="state" id="state" class="form-control action">
                <option value="">Select State</option>
            </select>
            <br />
            <select name="city" id="city" multiple class="form-control">
            </select>
            <br />
            <input type="hidden" name="hidden_city" id="hidden_city" />
            <input type="submit" name="insert" id="action" class="btn btn-info" value="Insert" />
        </form>
    </div>

    <script>
        $(document).ready(function(){
            $('#city').lwMultiSelect();

            $('.action').change(function(){
                if( $(this).val() != '' ){
                    var action  = $(this).attr("id");
                    var query   = $(this).val();
                    var result  = action == 'country' ? 'state' : 'city';
                    var country = $('#country').val();

                    $.ajax({
                        url:'fetch.php',
                        method:"POST",
                        data:{action:action, query:query, country: country},
                        success:function(data){
                            $('#'+result).html(data);
                            if(result == 'city'){
                                $('#city').data('plugin_lwMultiSelect').updateList();
                            }
                        }
                    })
                }
            });
        });
    </script>
</body>
</html>
</code>```

fetch.php

```<code><?php
//fetch.php

if(isset($_POST['action'])){
    include('database_connection.php');

    $output = '';

    if($_POST["action"] == 'country'){
        $statement = $connect->prepare("
            SELECT state FROM country_state_city
            WHERE country = :country
            GROUP BY state
        ");
        $statement->execute([
            ':country' => $_POST["query"]
        ]);

        $output .= '<option value="">Select State</option>';
        while($row=$statement->fetch()){
            $output .= '<option value="'.$row["state"].'">'.$row["state"].'</option>';
        }
    }else if($_POST["action"] == 'state'){
        $statement = $connect->prepare("
            SELECT city FROM country_state_city
            WHERE state = :state
            AND country=:country
        ");
        $statement->execute([
            ':state'   => $_POST["query"],
            ':country' => $_POST["country"]
        ]);

        while($row=$statement->fetch()){
            $output .= '<option value="'.$row["city"].'">'.$row["city"].'</option>';
        }
    }

    echo $output;
}

?>
</code>```

Body:
I'm trying edit a code from this tutorial: [https://www.youtube.com/watch?v=fSIg5y5QXbc&ab_channel=Webslesson][1]. The problem is a sytuation when two or more countires have the same state name (imagination only). For example, USA and Russia have the same "xyz" state, and when I select USA and state: "xyz", the program sees no difference (as if it just forgot which country we are in) and displays all the cities in the "xyz" state from both country.
Can you help me resolve this problem?

EDIT: I think i'm close, but i need to know, how to save for example: $select_country=(selected country) in fetch.php file

index.php

<?php
//index.php

include('database_connection.php');

$country = '';

$query = "
 SELECT country FROM country_state_city GROUP BY country ORDER BY country ASC
";
$statement = $connect->prepare($query);

$statement->execute();

$result = $statement->fetchAll();

foreach($result as $row)
{
 $country .= '<option value="'.$row["country"].'">'.$row["country"].'</option>';
}

?>
<!DOCTYPE html>

  <title>Insert Dynamic Multi Select Box Data using Jquery Ajax PHP</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

  <link rel="stylesheet" href="jquery.lwMultiSelect.css" />

Insert Dynamic Multi Select Box Data using Jquery Ajax PHP

   <form method="post" id="insert_data">
    <select name="country" id="country" class="form-control action">
     <option value="">Select Country</option>
     <?php echo $country; ?>
    </select>

    <select name="state" id="state" class="form-control action">
     <option value="">Select State</option>
    </select>

    <select name="city" id="city" multiple class="form-control">
    </select>

    <input type="hidden" name="hidden_city" id="hidden_city" />
    <input type="submit" name="insert" id="action" class="btn btn-info" value="Insert" />
   </form>

fetch.php

<?php
//fetch.php

if(isset($_POST['action']))
{
 include('database_connection.php');

 $output = '';

 if($_POST["action"] == 'country')
 {
  $query = "
  SELECT state FROM country_state_city
  WHERE country = :country
  GROUP BY state
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    ':country'  => $_POST["query"]
   )
  );
  $result = $statement->fetchAll();
  $output .= '<option value="">Select State</option>';
  foreach($result as $row)
  {
   $output .= '<option value="'.$row["state"].'">'.$row["state"].'</option>';
  }
 }
 if($_POST["action"] == 'state')
 {
  $query = "
  SELECT city FROM country_state_city
  WHERE state = :state
  ";
  $statement = $connect->prepare($query);
  $statement->execute(
   array(
    ':state'  => $_POST["query"]
   )
  );
  $result = $statement->fetchAll();
  foreach($result as $row)
  {
   $output .= '<option value="'.$row["city"].'">'.$row["city"].'</option>';
  }

 }
 echo $output;
}

?>

I don't add "insert.php" because I don't even use it

Body:
For situations like this, the countries, states and cities should all be store in separate tables.
Then you link them with the help of foreign keys.

But since all the records live in one table in your case, you can add the selected country to your queries to ensure that only records belonging to a particular country and/or state are affected.

As you can see below, var country = $('#country').val(); gets the selected country and was added to the ajax request. And then, included in the select query on the server.

index.php

<?php
//index.php

include('database_connection.php');

$country = '';

$statement = $connect->prepare("
    SELECT country
    FROM country_state_city
    GROUP BY country
    ORDER BY country ASC
");

$statement->execute();

while($row=$statement->fetch()){
    $country .= '<option value="'.$row["country"].'">'.$row["country"].'</option>';
}

?>
<!DOCTYPE html>
<html>
<head>
    <title>Insert Dynamic Multi Select Box Data using Jquery Ajax PHP</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="jquery.lwMultiSelect.js"></script>
    <link rel="stylesheet" href="jquery.lwMultiSelect.css" />
</head>
<body>
    <br /><br />
    <div class="container" style="width:600px;">
        <h2 align="center">Insert Dynamic Multi Select Box Data using Jquery Ajax PHP</h2><br /><br />
        <form method="post" id="insert_data">
            <select name="country" id="country" class="form-control action">
                <option value="">Select Country</option>
                <?php echo $country; ?>
            </select>
            <br />
            <select name="state" id="state" class="form-control action">
                <option value="">Select State</option>
            </select>
            <br />
            <select name="city" id="city" multiple class="form-control">
            </select>
            <br />
            <input type="hidden" name="hidden_city" id="hidden_city" />
            <input type="submit" name="insert" id="action" class="btn btn-info" value="Insert" />
        </form>
    </div>

    <script>
        $(document).ready(function(){
            $('#city').lwMultiSelect();

            $('.action').change(function(){
                if( $(this).val() != '' ){
                    var action  = $(this).attr("id");
                    var query   = $(this).val();
                    var result  = action == 'country' ? 'state' : 'city';
                    var country = $('#country').val();

                    $.ajax({
                        url:'fetch.php',
                        method:"POST",
                        data:{action:action, query:query, country: country},
                        success:function(data){
                            $('#'+result).html(data);
                            if(result == 'city'){
                                $('#city').data('plugin_lwMultiSelect').updateList();
                            }
                        }
                    })
                }
            });
        });
    </script>
</body>
</html>

fetch.php

<?php
//fetch.php

if(isset($_POST['action'])){
    include('database_connection.php');

    $output = '';

    if($_POST["action"] == 'country'){
        $statement = $connect->prepare("
            SELECT state FROM country_state_city
            WHERE country = :country
            GROUP BY state
        ");
        $statement->execute([
            ':country' => $_POST["query"]
        ]);

        $output .= '<option value="">Select State</option>';
        while($row=$statement->fetch()){
            $output .= '<option value="'.$row["state"].'">'.$row["state"].'</option>';
        }
    }else if($_POST["action"] == 'state'){
        $statement = $connect->prepare("
            SELECT city FROM country_state_city
            WHERE state = :state
            AND country=:country
        ");
        $statement->execute([
            ':state'   => $_POST["query"],
            ':country' => $_POST["country"]
        ]);

        while($row=$statement->fetch()){
            $output .= '<option value="'.$row["city"].'">'.$row["city"].'</option>';
        }
    }

    echo $output;
}

?>


问:
Regular expression to match standard 10 digit phone number
I want to write a regular expression for a standard US type phone number that supports the following formats:

```<code>###-###-####
(###) ###-####
### ### ####
###.###.####
</code>```

where # means any number. So far I came up with the following expressions

```<code>^[1-9]\d{2}-\d{3}-\d{4}
^\(\d{3}\)\s\d{3}-\d{4}
^[1-9]\d{2}\s\d{3}\s\d{4}
^[1-9]\d{2}\.\d{3}\.\d{4}
</code>```

respectively. I am not quite sure if the last one is correct for the dotted check. I also want to know if there is any way I could write a single expression instead of the 4 different ones that cater to the different formats I mentioned. If so, I am not sure how do I do that. And also how do I modify the expression/expressions so that I can also include a condition to support the area code as optional component. Something like

```<code>+1 ### ### ####
</code>```

where +1 is the area code and it is optional.

答:
Here's a regex that matches North American numbers as well as international numbers such as for middle east.

^((\+|0{0,2})([0-9]){1,3})?[-.●\s]?\(?([0-9]{2,3})\)?[-.●\s]?([0-9]{3})[-.●\s]?([0-9]{4})$

Body:
I want to write a regular expression for a standard US type phone number that supports the following formats:

###-###-####
(###) ###-####
### ### ####
###.###.####

where # means any number. So far I came up with the following expressions

^[1-9]\d{2}-\d{3}-\d{4}
^\(\d{3}\)\s\d{3}-\d{4}
^[1-9]\d{2}\s\d{3}\s\d{4}
^[1-9]\d{2}\.\d{3}\.\d{4}

respectively. I am not quite sure if the last one is correct for the dotted check. I also want to know if there is any way I could write a single expression instead of the 4 different ones that cater to the different formats I mentioned. If so, I am not sure how do I do that. And also how do I modify the expression/expressions so that I can also include a condition to support the area code as optional component. Something like

+1 ### ### ####

where +1 is the area code and it is optional.


问:
Cannot invoke because "" because service is null
I've been trying to use a springboot project that can integrate with mysql and jasperreports. The idea is that the user can add whoever to the database and then print a report with all entities. The error is at viewReport() function on my controller. It says that this.userService is null

```<code>@Controller
public class AppController {

@Autowired
private UserRepository repo;
private UserService userService;

@GetMapping("")
public String viewHomePage() {
    return "index";
}

@GetMapping("/register")
public String showSignUpForm(Model model) {
    model.addAttribute("user", new User());

    return "signup_form";
}

@GetMapping("/report")
public String generateReport() {
    userService.viewReport();

    return "index";
}

@PostMapping("/process_register")
public String processRegistration(User user) {
    repo.save(user);

    return "register_success";
}
}
</code>```

Here is my controller. The error being the userService.viewReport();

```<code>@Service
public class UserService {

    @Autowired
    private UserRepository repo;

    public String viewReport() {
        Log.info("Preparing the pdf report via Jasper.");
        try {
            createPdfReport(repo.findAll());
            Log.info("File successfully saved at given path.");
        } catch (final Exception e) {
            Log.error("Some error has occured while preparing PDF document.");
            e.printStackTrace();
        }
        return "Done in ViewReport";
    }

    public void createPdfReport(final List<User> users) throws JRException {
        //Fetching .jrxml file from resources folder.
        final InputStream stream = this.getClass().getResourceAsStream("/report.jrxml");

        //compile report from .jrxml to .jasper
        final JasperReport report = JasperCompileManager.compileReport(stream);

        //Fetch users from the data source
        final JRBeanCollectionDataSource source = new JRBeanCollectionDataSource(users);

        //Adding the additional parameters to the pdf
        final Map<String, Object> parameters = new HashMap<>();
        parameters.put("CreatedBy", "edu.sru.Smith" );

        //filling report with data from database
        final JasperPrint print = JasperFillManager.fillReport(report, parameters, source);

        //place file in c:drive
        final String filePath = "C://CPSC-488";
        //export report to pdf file
        JasperExportManager.exportReportToPdfFile(print, filePath + "Employee_Report.pdf");

    }

} ```

That is my service class that autofills with the data from the MySQL database. I have tried adding a number of annotations and other things, but I haven't had success with anything. I'm honestly just new to this whole springboot thing and annotations overall and I have no idea where to go from here.

```

答:
@Autowired annotation should be placed on each field that needs injection.</p>
```<code>@Autowired
private UserRepository repo;

@Autowired
private UserService userService;
</code>```

Body:
I've been trying to use a springboot project that can integrate with mysql and jasperreports. The idea is that the user can add whoever to the database and then print a report with all entities. The error is at viewReport() function on my controller. It says that this.userService is null

@Controller
public class AppController {

@Autowired
private UserRepository repo;
private UserService userService;

@GetMapping("")
public String viewHomePage() {
    return "index";
}

@GetMapping("/register")
public String showSignUpForm(Model model) {
    model.addAttribute("user", new User());

    return "signup_form";
}

@GetMapping("/report")
public String generateReport() {
    userService.viewReport();

    return "index";
}

@PostMapping("/process_register")
public String processRegistration(User user) {
    repo.save(user);

    return "register_success";
}
}

Here is my controller. The error being the userService.viewReport();

@Service
public class UserService {

    @Autowired
    private UserRepository repo;

    public String viewReport() {
        Log.info("Preparing the pdf report via Jasper.");
        try {
            createPdfReport(repo.findAll());
            Log.info("File successfully saved at given path.");
        } catch (final Exception e) {
            Log.error("Some error has occured while preparing PDF document.");
            e.printStackTrace();
        }
        return "Done in ViewReport";
    }

    public void createPdfReport(final List<User> users) throws JRException {
        //Fetching .jrxml file from resources folder.
        final InputStream stream = this.getClass().getResourceAsStream("/report.jrxml");

        //compile report from .jrxml to .jasper
        final JasperReport report = JasperCompileManager.compileReport(stream);

        //Fetch users from the data source
        final JRBeanCollectionDataSource source = new JRBeanCollectionDataSource(users);

        //Adding the additional parameters to the pdf
        final Map<String, Object> parameters = new HashMap<>();
        parameters.put("CreatedBy", "edu.sru.Smith" );

        //filling report with data from database
        final JasperPrint print = JasperFillManager.fillReport(report, parameters, source);

        //place file in c:drive
        final String filePath = "C://CPSC-488";
        //export report to pdf file
        JasperExportManager.exportReportToPdfFile(print, filePath + "Employee_Report.pdf");

    }

} ```

That is my service class that autofills with the data from the MySQL database. I have tried adding a number of annotations and other things, but I haven't had success with anything. I'm honestly just new to this whole springboot thing and annotations overall and I have no idea where to go from here.

Body:
@Autowired annotation should be placed on each field that needs injection.

@Autowired
private UserRepository repo;

@Autowired
private UserService userService;


问:
JQuery doesnot support custom attribute in IE*?
In html I have on table like this:

then I user jquery to find the table

```<code>var table = $("table[for='availableTimeRanges']");
</code>```

In firefox and chrome, this works,can return the table, but in IE8, nothing return
Then i run below code in IE8, found the attribute value is empty:

```<code>$.each($("table"), function(i,n){
        alert($(n).attr("for")

});
</code>```

what's the reason

答:
You better use class names they are supported everywhere

```<code><table class="for_availableTimeRanges"></table>
</code>```

and

```<code>$('.for_availableTimeRanges')
</code>```

Body:
In html I have on table like this:

then I user jquery to find the table

var table = $("table[for='availableTimeRanges']");

In firefox and chrome, this works,can return the table, but in IE8, nothing return
Then i run below code in IE8, found the attribute value is empty:

$.each($("table"), function(i,n){
        alert($(n).attr("for")

});

what's the reason

Body:
You better use class names they are supported everywhere

<table class="for_availableTimeRanges"></table>

and

$('.for_availableTimeRanges')


问:
Angular2 wait for @Input object to be fully initialized
I have a .ts class with a variable decorated as @Input

I would like to make a copy of this object but i cant figure out the right place to do this is, my current code:

```<code>@Input() myObj: MyObj;
public copy: MyObj;

 ngOnInit() {
    this.copy = JSON.parse(JSON.stringify(myObj));
}
</code>```

The call within the ngOnInit method breaks because the ngOnInit is called before the myObj variable is fully created.

I have also tried to create the copy within the ngAfterContentInit method but that is also called before myObj variable is fully created.

I have seen other questions similar to mine, but they all wait for an observable, my object is not an observable, is simply an object passed from parent to child through the view:

```<code><child-view [myObj]="myObjInParent"/>
</code>```

答:
It depends when you have to use your copy variable in your code.

You can create a getter which does the parsing if copy is null, and if not you just return the copy value.

It may be null the first few times you call the getter, but eventually once all the datas are loaded the parsing will be done automatically.

Body:
I have a .ts class with a variable decorated as @Input

I would like to make a copy of this object but i cant figure out the right place to do this is, my current code:

@Input() myObj: MyObj;
public copy: MyObj;

 ngOnInit() {
    this.copy = JSON.parse(JSON.stringify(myObj));
}

The call within the ngOnInit method breaks because the ngOnInit is called before the myObj variable is fully created.

I have also tried to create the copy within the ngAfterContentInit method but that is also called before myObj variable is fully created.

I have seen other questions similar to mine, but they all wait for an observable, my object is not an observable, is simply an object passed from parent to child through the view:

<child-view [myObj]="myObjInParent"/>


问:
How can I change the border color of a node from it's XPath?
I have the XPath of an element (eg //html/body/div[1]/div[2]). I want to fetch the element and change it's border colour.

I can fetch the node using

```<code>document.evaluate(xPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE).singleNodeValue
</code>```

But I can't figure out what to do next...

答:
You're not too far off from it -- Since you have the node from the code provided, you just have to assign add the styling.  One way is by using JavaScript to add the in-line styles, for example:

```<code>
// Select the node
var myDiv = document.evaluate('//html/body/div[1]/div[2]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;

//Add the style in-line
myDiv.style.border = "1px solid red";

// Or you can define a CSS class and add it that way
// myDiv.classList.add("my-class-with-border");

</code>```

Working example: https://codepen.io/scarabaeus/pen/wvPqMPK

Body:
I have the XPath of an element (eg //html/body/div[1]/div[2]). I want to fetch the element and change it's border colour.

I can fetch the node using

document.evaluate(xPath, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE).singleNodeValue

But I can't figure out what to do next...

Body:
You're not too far off from it -- Since you have the node from the code provided, you just have to assign add the styling.  One way is by using JavaScript to add the in-line styles, for example:

// Select the node
var myDiv = document.evaluate('//html/body/div[1]/div[2]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue;

//Add the style in-line
myDiv.style.border = "1px solid red";

// Or you can define a CSS class and add it that way
// myDiv.classList.add("my-class-with-border");

Working example: https://codepen.io/scarabaeus/pen/wvPqMPK


问:
How to run git clone command in a pipeline step LFS enabled
I've a pipeline that is cloning another repository. Pipeline below is running on yyy repository, and it's supposed to clone xxx repository and do some work on it, then upload the results to AWS S3, I have lots of object to be worked on, so git clone step should be LFS enabled. git lfs client is configured on my base image. LFS is also enabled on my xxx repository. My deployment consumes so much time to clone repo with LFS enabled.

```<code> - step:
   name: "Pipeline"
   services:
       - docker
    caches:
       - docker
    script:
    - ...
    - ...
    - ...
    - ...
    - git clone git@bitbucket.org:xxx.git
</code>```

I've tried

```<code>clone:
    lfs: true
</code>```

option to reduce the consumed time but it seems it doesn't work with the setup above.

How can I reduce time consumption for this setup? Is there any workaround here?

Thank you.

答:
It can be a little bit weird but I came up with the solution below,

I gave

```<code>clone:
  enabled: false
</code>```

in the pipeline, and I cloned the repo in the script part. Because my repo is huge, I limited everything to consume less time.

```<code>git clone git@bitbucket.org:xxx/<repo-name>.git --depth 1 --no-tags --single-branch -b <branch> --no-checkout .
</code>```

It's working like a charm :)

Body:
I've a pipeline that is cloning another repository. Pipeline below is running on yyy repository, and it's supposed to clone xxx repository and do some work on it, then upload the results to AWS S3, I have lots of object to be worked on, so git clone step should be LFS enabled. git lfs client is configured on my base image. LFS is also enabled on my xxx repository. My deployment consumes so much time to clone repo with LFS enabled.

 - step:
   name: "Pipeline"
   services:
       - docker
    caches:
       - docker
    script:
    - ...
    - ...
    - ...
    - ...
    - git clone git@bitbucket.org:xxx.git

I've tried

clone:
    lfs: true

option to reduce the consumed time but it seems it doesn't work with the setup above.

How can I reduce time consumption for this setup? Is there any workaround here?

Thank you.

Body:
It can be a little bit weird but I came up with the solution below,

I gave

clone:
  enabled: false

in the pipeline, and I cloned the repo in the script part. Because my repo is huge, I limited everything to consume less time.

git clone git@bitbucket.org:xxx/<repo-name>.git --depth 1 --no-tags --single-branch -b <branch> --no-checkout .

It's working like a charm :)


问:
is there any other Base64 type encryption and decryption in php?
is there any other Base64 type encryption and decryption in php ?

The problem is that base 64 give a longer value and increases the size of the data whereas i'm looking for something to reduce the size of the data.

is there any ?

答:
Base64 isn't so much encrypting and encoding - anyone can return a base64 encoded file/string into the original.

If you want to reduce the data size, try compressing it using for instance http://php.net/zip. If you still need to send the the data to another system, you could then base64 encode the resulting compressed data.

Do you actually want to encrypt the content (a security measure) or just make it viable for transmission inside for instance an XML or JSON stream, or is compression your only concern?


问:
bootstrap 3.4.1 navbar link show up and work properly in mobile firefox but do not work in mobile Chrome
I'm using Visual studio and ASP.net to build a web page.

My code:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                    </button>

        ASTRO

Home

Pictures

Tonight's Sky

About

Contact

```
</div>
</div>
</p>
<p><strong>Bootstrap link I'm using:</strong></p>
<pre class="lang-html prettyprint-override"><code><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
</code>```

I've tried the latest bootstrap version 5.1.3 with no luck.

As I said in the header, Works fine in the mobile Firefox but all I get mobile Chrome browser is the Navbar and the "ASTRO" link which works the other links in the list don't show. And when I click on the 3 bars button nothing happens.

Does Chrome need some special settings?

Thanks
Nor

答:
You needed to include jQuery and Bootstrap .js files since the button uses JavaScript:

Updated code:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                    </button>

        ASTRO

Home

Pictures

Tonight's Sky

About

Contact

```

Body:
I'm using Visual studio and ASP.net to build a web page.

My code:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">

                    </button>

        ASTRO

Home

Pictures

Tonight's Sky

About

Contact

Bootstrap link I'm using:

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />

I've tried the latest bootstrap version 5.1.3 with no luck.

As I said in the header, Works fine in the mobile Firefox but all I get mobile Chrome browser is the Navbar and the "ASTRO" link which works the other links in the list don't show. And when I click on the 3 bars button nothing happens.

Does Chrome need some special settings?

Thanks
Nor

Body:
You needed to include jQuery and Bootstrap .js files since the button uses JavaScript:

Updated code:

<head>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" />
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top">
  <div class="container">
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
      <a class="navbar-brand">
        <img alt="" src="~/resources/favicon.ico"></a><a class="navbar-brand" href="/">ASTRO</a>
    </div>
    <div class="navbar-collapse collapse">
      <ul class="nav navbar-nav">
        <li><a href="~/">Home</a></li>
        <li><a href="~/img">Pictures</a></li>
        <li><a href="~/whatsup">Tonight's Sky</a></li>
        <li><a href="~/About">About</a></li>
        <li><a href="~/Contact">Contact</a></li>
      </ul>
    </div>
  </div>
</nav>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha384-nvAa0+6Qg9clwYCGGPpDQLVpLNn0fRaROjHqs13t4Ggj3Ez50XnGQqc/r8MhnRDZ" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js" integrity="sha384-aJ21OjlMXNL5UyIl/XNwTMqvzeRMZH2w8c5cRVpzpU8Y5bApTppSuUkhZXN0VxHd" crossorigin="anonymous"></script>
</body>


问:
Why is my MariaDB query not working on host but works locally?
This is my code that works fine locally, but not on Namecheap host:

```<code>//data connection pool
const pool = require('../models/database');
const bcrypt = require('bcrypt');

module.exports = async (req, res) => {
    try {
        const {user_name, password, email} = req.body;
        const hashedPassword = await bcrypt.hash(password, 10);
        console.log(hashedPassword);

        let sql = `INSERT INTO userdb (user_name, password, email)
        SELECT ?, ?, ?
        WHERE NOT EXISTS (SELECT 1 FROM userdb WHERE email = ? OR user_name = ?);
        SHOW WARNINGS;`;

        let result = await pool.query(sql, [user_name, hashedPassword, email, email, user_name]);

        console.log(result);
        console.log("the id: ", result[0].insertId);
        res.status(200).send("Success Comrad!");

        } catch (error) {
        res.status(400).send(error.message);
    }

}//module.export end
</code>```

These are my dependencies:

```<code>"dependencies": {
    "bcrypt": "^5.0.1",
    "dotenv": "^16.0.0",
    "express": "^4.17.2",
    "mariadb": "^2.5.5",
    "pug": "^3.0.2"
  }
</code>```

This is the error I'm getting:

```<code>(conn=1698954, no: 1064, SQLState: 42000) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE NOT EXISTS (SELECT 1 FROM userdb WHERE email = 'dookie@gmail.com' OR us...' at line 3 sql: INSERT INTO userdb (user_name, password, email) SELECT ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM userdb WHERE email = ? OR user_name = ?); SHOW WARNINGS; - parameters:['dookie','$2b$10$OQp5lovlqmMfKNQtuvBK9e7t4rX39nVW22XdhzDZqBnSgDKv6G0ky','d...]
</code>```

I also do have this set: multipleStatements: true
Any ideas why this may be?

答:
I solved this by approaching it differently. My main goal is to prevent duplicate entries.

I first set a unique constraint in PHPMyAdmin by doing this:

```<code>ALTER TABLE userdb
ADD CONSTRAINT UC_email UNIQUE (email)
</code>```

and then simplified my query:

```<code>let sql = `INSERT INTO userdb (user_name, password, email)
        VALUES (?,?,?)`;
</code>```

Body:
This is my code that works fine locally, but not on Namecheap host:

//data connection pool
const pool = require('../models/database');
const bcrypt = require('bcrypt');

module.exports = async (req, res) => {
    try {
        const {user_name, password, email} = req.body;
        const hashedPassword = await bcrypt.hash(password, 10);
        console.log(hashedPassword);

        let sql = `INSERT INTO userdb (user_name, password, email)
        SELECT ?, ?, ?
        WHERE NOT EXISTS (SELECT 1 FROM userdb WHERE email = ? OR user_name = ?);
        SHOW WARNINGS;`;

        let result = await pool.query(sql, [user_name, hashedPassword, email, email, user_name]);

        console.log(result);
        console.log("the id: ", result[0].insertId);
        res.status(200).send("Success Comrad!");

        } catch (error) {
        res.status(400).send(error.message);
    }

}//module.export end

These are my dependencies:

"dependencies": {
    "bcrypt": "^5.0.1",
    "dotenv": "^16.0.0",
    "express": "^4.17.2",
    "mariadb": "^2.5.5",
    "pug": "^3.0.2"
  }

This is the error I'm getting:

(conn=1698954, no: 1064, SQLState: 42000) You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'WHERE NOT EXISTS (SELECT 1 FROM userdb WHERE email = 'dookie@gmail.com' OR us...' at line 3 sql: INSERT INTO userdb (user_name, password, email) SELECT ?, ?, ? WHERE NOT EXISTS (SELECT 1 FROM userdb WHERE email = ? OR user_name = ?); SHOW WARNINGS; - parameters:['dookie','$2b$10$OQp5lovlqmMfKNQtuvBK9e7t4rX39nVW22XdhzDZqBnSgDKv6G0ky','d...]

I also do have this set: multipleStatements: true
Any ideas why this may be?

Body:
I solved this by approaching it differently. My main goal is to prevent duplicate entries.

I first set a unique constraint in PHPMyAdmin by doing this:

ALTER TABLE userdb
ADD CONSTRAINT UC_email UNIQUE (email)

and then simplified my query:

let sql = `INSERT INTO userdb (user_name, password, email)
        VALUES (?,?,?)`;


问:
Reorder HTML elements - most efficient vs practical way
I am implementing an UI list of items. It supports ordering by sort functions and custom drag and drop ordering.

It will be used for displaying hundreds of items.

I am looking for the "best" way to implement the ordering.

Sorting is always done on data model in memory and is then projected onto the UI.

First solution I know about is just reorder the DOM elements. Simple, but it feels like a little too resource heavy...

...in comparison with flexbox and css order. That is the second solution I have in mind. Assign order with increasing values and let css do its magic... hopefully with less resources used.

The problem with css order is that if I remove or add list items, it does not reindex (the order value) automatically, so there is more maintenance to keep the system working as opposed to using DOM element order.

Do you see any (dis)advantages with using either of those?
Do you agree that using css order is (significantly) faster/less expensive?
Any other options to order elements?

Edit:
Pagination is not an option. My question is only concerning the mechanisms to reorder elements.

答:
I think if you use a pagination logic with Javascript, you can reduce the rendering hundreds of items. I mean you can split items and then just render 10 items and next 10 items.

I am not sure this logic helps or not.
https://jasonwatmore.com/post/2018/08/07/javascript-pure-pagination-logic-in-vanilla-js-typescript


问:
Javascript Function - Parameter match of Object in Array within an Object Loop
```<code>var dset2 = {
"DataFile": [{
"ID": 1,
"Cat": "D School",
"Vert": "D Safety",
"Ind": "A Ind",
 },
 {
  "ID": 2,
  "Cat": "T School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 },
{
  "ID": 3,
  "Cat": "S School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 }
]}

var catValueArray = [];
var vertValueArray = [];
var indValueArray = [];
for (i = 0; i < dset2.DataFile.length; i++) {
    if (!catValueArray.includes(dset2.DataFile[i].Cat)) {
        catValueArray.push(dset2.DataFile[i].Cat);
    }
    if (!vertValueArray.includes(dset2.DataFile[i].Vert)) {
        vertValueArray.push(dset2.DataFile[i].Vert);
    }
    if (!indValueArray.includes(dset2.DataFile[i].Ind)) {
        indValueArray.push(dset2.DataFile[i].Ind);
    }
    console.log(catValueArray);
    console.log(vertValueArray);
    console.log(indValueArray);
}
</code>```

Results are

```<code>Array [ "D School", "T School", "S School" ];
Array [ "D Safety" ];
Array [ "A Ind", "B Ind" ];

</code>```

I would like to convert this into a reusable function.
IE:

```<code>var catValueArray = [];
var dsetSwitch = dset2.DataFile;

function pullUniqueValues(dataset, array, prop) {
    for (i = 0; i < dataset.length; i++) {
        if (!array.includes(dataset[i].prop)) {
            array.push(dataset[i].prop);
        }
    }
    console.log(array);
}
pullUniqueValues(dset2.DataFile, catValueArray, 'Cat');
</code>```

That doesn't work. However, if I move "Cat" inside the function, I can get a result.
IE:

```<code>var catValueArray = [];
var dsetSwitch = dset2.DataFile;
function pullUniqueValues(dataset, array, prop) {
    for (i = 0; i < dataset.length; i++) {
        if (!array.includes(dataset[i].Cat)) {
            array.push(dataset[i].Cat);
        }
    }
    console.log(array);
}
pullUniqueValues(dsetSwitch, catValueArray);
</code>```

The end result is to reuse on a a datasets that has over 10 keys that will be used as identifiers and the number of items ill need to access them is very large. Currently because I can not get the Object parameter passed into the function, I have been forced to hard code every instance where I need to access the key. IE: Anytime I need to access "Cat" key, from the Object in the Array DataFile from within the Object dset2, I have to explicerly write the loop with dset2.DataFile[i].Cat.

Additional attempts with no success passing the property parameter into the function.

```<code>var DataFile = [{
"ID": 1,
"Cat": "D School",
"Vert": "D Safety",
"Ind": "A Ind",
 },
 {
  "ID": 2,
  "Cat": "T School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 },
{
  "ID": 3,
  "Cat": "S School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 }
]

var uniqueValues = [];
function giveUniqueValues1(prop){
uniqueValues = DataFile.map(item => item.prop)
  .filter((value, index, self) => self.indexOf(value) === index);
}
function giveUniqueValues2(prop){
uniqueValues = [...new Set(DataFile.map(item => item.prop))];
}

uniqueValues = DataFile.map(item => item.Cat)
  .filter((value, index, self) => self.indexOf(value) === index); // Successs
giveUniqueValues1(Cat); //Failed Error
giveUniqueValues1('Cat'); //Failed Undefined result for uniqueValues;

uniqueValues = [...new Set(DataFile.map(item => item.Cat))]; //Success
giveUniqueValues2('Cat'); //Fail No Values Returned
giveUniqueValues2(Cat); //Fail Error Out

</code>```

答:
You're almost there! Just change .prop to [prop], so the section in the if would be:

```<code>    if (!array.includes(dataset[i][prop])) {
        array.push(dataset[i][prop]);
    }
</code>```

DEMO

var dset2 = {
    "DataFile": [{
            "ID": 1,
            "Cat": "D School",
            "Vert": "D Safety",
            "Ind": "A Ind",
        },
        {
            "ID": 2,
            "Cat": "T School",
            "Vert": "D Safety",
            "Ind": "B Ind",
        },
        {
            "ID": 3,
            "Cat": "S School",
            "Vert": "D Safety",
            "Ind": "B Ind",
        }
    ]
};

var catValueArray = [];
var dsetSwitch = dset2.DataFile;

function pullUniqueValues(dataset, array, prop) {
    for (i = 0; i < dataset.length; i++) {
        if (!array.includes(dataset[i][prop])) {
            array.push(dataset[i][prop]);
        }
    }
    console.log(array);
}
pullUniqueValues(dset2.DataFile, catValueArray, 'Cat');```
</div>
</div>
</p>
<p>The function can be simplified to:</p>
```const pullUniqueValues = prop => [...new Set(
    dset2.DataFile.map(file => file[prop])
)];
```
<p><strong>DEMO</strong></p>
<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var dset2 = {
    "DataFile": [{
            "ID": 1,
            "Cat": "D School",
            "Vert": "D Safety",
            "Ind": "A Ind",
        },
        {
            "ID": 2,
            "Cat": "T School",
            "Vert": "D Safety",
            "Ind": "B Ind",
        },
        {
            "ID": 3,
            "Cat": "S School",
            "Vert": "D Safety",
            "Ind": "B Ind",
        }
    ]
};

const pullUniqueValues = prop => [...new Set( dset2.DataFile.map(file => file[prop]) )];

console.log( pullUniqueValues('Cat') );
console.log( pullUniqueValues('Ind') );</code>```

Body:
var dset2 = {
"DataFile": [{
"ID": 1,
"Cat": "D School",
"Vert": "D Safety",
"Ind": "A Ind",
 },
 {
  "ID": 2,
  "Cat": "T School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 },
{
  "ID": 3,
  "Cat": "S School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 }
]}

var catValueArray = [];
var vertValueArray = [];
var indValueArray = [];
for (i = 0; i < dset2.DataFile.length; i++) {
    if (!catValueArray.includes(dset2.DataFile[i].Cat)) {
        catValueArray.push(dset2.DataFile[i].Cat);
    }
    if (!vertValueArray.includes(dset2.DataFile[i].Vert)) {
        vertValueArray.push(dset2.DataFile[i].Vert);
    }
    if (!indValueArray.includes(dset2.DataFile[i].Ind)) {
        indValueArray.push(dset2.DataFile[i].Ind);
    }
    console.log(catValueArray);
    console.log(vertValueArray);
    console.log(indValueArray);
}

Results are

Array [ "D School", "T School", "S School" ];
Array [ "D Safety" ];
Array [ "A Ind", "B Ind" ];

I would like to convert this into a reusable function.
IE:

var catValueArray = [];
var dsetSwitch = dset2.DataFile;

function pullUniqueValues(dataset, array, prop) {
    for (i = 0; i < dataset.length; i++) {
        if (!array.includes(dataset[i].prop)) {
            array.push(dataset[i].prop);
        }
    }
    console.log(array);
}
pullUniqueValues(dset2.DataFile, catValueArray, 'Cat');

That doesn't work. However, if I move "Cat" inside the function, I can get a result.
IE:

var catValueArray = [];
var dsetSwitch = dset2.DataFile;
function pullUniqueValues(dataset, array, prop) {
    for (i = 0; i < dataset.length; i++) {
        if (!array.includes(dataset[i].Cat)) {
            array.push(dataset[i].Cat);
        }
    }
    console.log(array);
}
pullUniqueValues(dsetSwitch, catValueArray);

The end result is to reuse on a a datasets that has over 10 keys that will be used as identifiers and the number of items ill need to access them is very large. Currently because I can not get the Object parameter passed into the function, I have been forced to hard code every instance where I need to access the key. IE: Anytime I need to access "Cat" key, from the Object in the Array DataFile from within the Object dset2, I have to explicerly write the loop with dset2.DataFile[i].Cat.

Additional attempts with no success passing the property parameter into the function.

var DataFile = [{
"ID": 1,
"Cat": "D School",
"Vert": "D Safety",
"Ind": "A Ind",
 },
 {
  "ID": 2,
  "Cat": "T School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 },
{
  "ID": 3,
  "Cat": "S School",
  "Vert": "D Safety",
  "Ind": "B Ind",
 }
]

var uniqueValues = [];
function giveUniqueValues1(prop){
uniqueValues = DataFile.map(item => item.prop)
  .filter((value, index, self) => self.indexOf(value) === index);
}
function giveUniqueValues2(prop){
uniqueValues = [...new Set(DataFile.map(item => item.prop))];
}

uniqueValues = DataFile.map(item => item.Cat)
  .filter((value, index, self) => self.indexOf(value) === index); // Successs
giveUniqueValues1(Cat); //Failed Error
giveUniqueValues1('Cat'); //Failed Undefined result for uniqueValues;

uniqueValues = [...new Set(DataFile.map(item => item.Cat))]; //Success
giveUniqueValues2('Cat'); //Fail No Values Returned
giveUniqueValues2(Cat); //Fail Error Out

Body:
You're almost there! Just change .prop to [prop], so the section in the if would be:

    if (!array.includes(dataset[i][prop])) {
        array.push(dataset[i][prop]);
    }

DEMO

var dset2 = {
    "DataFile": [{
            "ID": 1,
            "Cat": "D School",
            "Vert": "D Safety",
            "Ind": "A Ind",
        },
        {
            "ID": 2,
            "Cat": "T School",
            "Vert": "D Safety",
            "Ind": "B Ind",
        },
        {
            "ID": 3,
            "Cat": "S School",
            "Vert": "D Safety",
            "Ind": "B Ind",
        }
    ]
};

var catValueArray = [];
var dsetSwitch = dset2.DataFile;

function pullUniqueValues(dataset, array, prop) {
    for (i = 0; i < dataset.length; i++) {
        if (!array.includes(dataset[i][prop])) {
            array.push(dataset[i][prop]);
        }
    }
    console.log(array);
}
pullUniqueValues(dset2.DataFile, catValueArray, 'Cat');

The function can be simplified to:

const pullUniqueValues = prop => [...new Set(
    dset2.DataFile.map(file => file[prop])
)];

DEMO

var dset2 = {
    "DataFile": [{
            "ID": 1,
            "Cat": "D School",
            "Vert": "D Safety",
            "Ind": "A Ind",
        },
        {
            "ID": 2,
            "Cat": "T School",
            "Vert": "D Safety",
            "Ind": "B Ind",
        },
        {
            "ID": 3,
            "Cat": "S School",
            "Vert": "D Safety",
            "Ind": "B Ind",
        }
    ]
};

const pullUniqueValues = prop => [...new Set( dset2.DataFile.map(file => file[prop]) )];

console.log( pullUniqueValues('Cat') );
console.log( pullUniqueValues('Ind') );


问:
People bypassing anti-swear system by using duplicate letters
Ok so, I made an anti-swear system in discord.py, but you can easily bypass it. Here's an example: let's say "cat" is a swear word, well you can just do "ccaatt" and the bot won't detect it. How do I fix this?
Here's the code:

@client.event
async def on_message(message):
    try:
      if message.author.bot:
        return
      if client.user in message.mentions:
          response = f"Hello! I'm Stealth Bot. My prefix is `-`. To see a list of commands do `-help`."
          await message.channel.send(response)
          print(f"{message.author.name} pinged me in {message.channel}!")
          pass
      if message.channel.id == 828667602351161354 or message.channel.id == 820049182860509206:
        pass
      else:
        if profanity.contains_profanity(message.content):
            await message.delete()
            warnMessage = f"Hey {message.author.mention}! Don't say that!\n*You said ||{message.content}||*"
            await message.channel.send(warnMessage, delete_after=5.0)
            print(f"{message.author.name} tried saying: {message.content}")
            channel = client.get_channel(836232733126426666)

            embed = discord.Embed(title=f"Someone tried to swear!", colour=0x2D2D2D)
            embed.add_field(name="Person who tried to swear:", value=f"{message.author.name}", inline=False)
            embed.add_field(name="What they tried to say:", value=f"{message.content}", inline=False)
            embed.add_field(name="Debug:", value=f"{profanity}", inline=False)
            embed.add_field(name="Debug 2:", value=f"{message.content.lower}", inline=False)
            embed.add_field(name="Channel they tried to swear in:", value=f"<#{message.channel.id}>", inline=False)

            await channel.send(embed=embed)
            pass
      await client.process_commands(message)
    except Exception as e:
        print(e)
```

答: To be honest a proper discord Mod using discord.py require Machine Learning and AI no matter how much u format the messages there will be many flaws there was a competition on kaggle to rate toxic messages. The 1st place solution was transformed into a module called detoxify in python if you actually want a very good anti swear and have a good compute and a bit of storage on the cloud pc you are deploying on then I think you can use it. I would recommend using heroku it is widely used for deploying ML applications.


问:
why doesn't the qr code (generated with qr.make()) take me to the right URL?
I am trying to generate a qr code of a google sheets file that ends with "edit#gid=1473689815". This last part of the URL is the name of a specific sheet in the file. So the problem is that when I scann the qr code with my iPhone (without a spefic qrcode leser app) the code brings me to the first sheet of the file. Do you maybe know if this part of the URL is making some trouble at the moment of the qrcodegeneration? What else should I try?
And no matter which app I use (neither generating the qrcode on google sheets itself) the qr code brings me ALWAYS to the first sheet of the file.
Thanks for your help!</p>

答:
Try to encode the url before generating the qrcode with

```<code>encodeURI(url)
</code>```

encodeURI

Body:
Try to encode the url before generating the qrcode with

encodeURI(url)

encodeURI


问:
Read data frame from get_prediction function of statsmodels library
I am creating forecast model using arima here i have use statsmodels

Get forecast steps ahead in future

```<code>pred_uc = results.get_prediction(start='2001-05-01',end='2002-05-01')
print(pred_uc)
</code>```

When I print this i get its in objects can it be converted into readable format in array or data frame

```<code><statsmodels.tsa.statespace.mlemodel.PredictionResultsWrapper object at 0x00000000156E71D0>
</code>```

Here it looks like data is stored in memory location and since i am noob in python i need a bit of help here...

code from

Source code of statsmodels library

答:
You may try this:</p>
```<code>pred_uc = fitted_model.get_prediction(start='2001-05-01', end='2002-05-01')
pred_uc = pred_uc.predicted_mean
pred_uc.columns = ['predicted1','predicted2', 'predicted_n']
pred_uc.head()
</code>```

Body:
I am creating forecast model using arima here i have use statsmodels

Get forecast steps ahead in future

pred_uc = results.get_prediction(start='2001-05-01',end='2002-05-01')
print(pred_uc)

When I print this i get its in objects can it be converted into readable format in array or data frame

<statsmodels.tsa.statespace.mlemodel.PredictionResultsWrapper object at 0x00000000156E71D0>

Here it looks like data is stored in memory location and since i am noob in python i need a bit of help here...

code from

Source code of statsmodels library

Body:
You may try this:

pred_uc = fitted_model.get_prediction(start='2001-05-01', end='2002-05-01')
pred_uc = pred_uc.predicted_mean
pred_uc.columns = ['predicted1','predicted2', 'predicted_n']
pred_uc.head()


问:
Pass a variable number of arguments into a function
I know how to use variadic templates and ellipses to accept a variable number of arguments, but how do you pass a variable number of arguments into a function?

Take the following code for example:

```<code>#include <iostream>

struct A {
   A(int a, int b) : x(a), y(b) {}
   int x, y;
};

struct B {
    B(int a, int b, int c) : x(a), y(b), z(c) {}
    int x, y, z;
};

template<typename T, typename... TArgs>
T* createElement(TArgs&&... MArgs) {
    T* element = new T(std::forward<TArgs>(MArgs)...);
    return element;
}

int main() {

    int Aargs[] = { 1, 2 };
    int Bargs[] = { 1, 2, 3 };

    A* a = createElement<A>(Aargs); //ERROR
    B* b = createElement<B>(Bargs); //ERROR

    std::cout << "a.x: " << a->x << "\na.y: " << a->y << "\n" << std::endl;
    std::cout << "b.x: " << b->x << "\nb.y: " << b->y << "\nb.z: " << b->z << "\n" << std::endl;

    delete a;
    delete b;
}
</code>```

Is there any way to expand the arrays so that each of their values is like an argument being passed to the function (similar to parameter pack expansion)?

Or, if not, is there any other way to make this work?

答:
You can expand the array using a std::index_sequence

```<code>#include <iostream>
#include <utility>

struct A {
   A(int a, int b) : x(a), y(b) {}
   int x, y;
};

struct B {
    B(int a, int b, int c) : x(a), y(b), z(c) {}
    int x, y, z;
};

template<typename T, typename... TArgs>
T* createElement(TArgs&&... MArgs) {
    T* element = new T(std::forward<TArgs>(MArgs)...);
    return element;
}

template<typename T, typename U, size_t...  I>
T* createElementFromArrayHelper(std::index_sequence<I...>, U* a){
    return createElement<T>(a[I]...);
}

template<typename T, typename U, size_t N>
T* createElementFromArray(U (&a)[N]){
    return createElementFromArrayHelper<T>(std::make_index_sequence<N>{}, a);
}

int main() {

    int Aargs[] = { 1, 2 };
    int Bargs[] = { 1, 2, 3 };

    A* a = createElementFromArray<A>(Aargs);
    B* b = createElementFromArray<B>(Bargs);

    std::cout << "a.x: " << a->x << "\na.y: " << a->y << "\n" << std::endl;
    std::cout << "b.x: " << b->x << "\nb.y: " << b->y << "\nb.z: " << b->z << "\n" << std::endl;

    delete a;
    delete b;

}
</code>```

Body:
I know how to use variadic templates and ellipses to accept a variable number of arguments, but how do you pass a variable number of arguments into a function?

Take the following code for example:

#include <iostream>

struct A {
   A(int a, int b) : x(a), y(b) {}
   int x, y;
};

struct B {
    B(int a, int b, int c) : x(a), y(b), z(c) {}
    int x, y, z;
};

template<typename T, typename... TArgs>
T* createElement(TArgs&&... MArgs) {
    T* element = new T(std::forward<TArgs>(MArgs)...);
    return element;
}

int main() {

    int Aargs[] = { 1, 2 };
    int Bargs[] = { 1, 2, 3 };

    A* a = createElement(Aargs); //ERROR
    B* b = createElement(Bargs); //ERROR

    std::cout << "a.x: " <x << "\na.y: " <y << "\n" << std::endl;
    std::cout << "b.x: " <x << "\nb.y: " <y << "\nb.z: " <z << "\n" << std::endl;

    delete a;
    delete b;
}

Is there any way to expand the arrays so that each of their values is like an argument being passed to the function (similar to parameter pack expansion)?

Or, if not, is there any other way to make this work?

Body:
You can expand the array using a std::index_sequence

#include <iostream>
#include <utility>

struct A {
   A(int a, int b) : x(a), y(b) {}
   int x, y;
};

struct B {
    B(int a, int b, int c) : x(a), y(b), z(c) {}
    int x, y, z;
};

template<typename T, typename... TArgs>
T* createElement(TArgs&&... MArgs) {
    T* element = new T(std::forward<TArgs>(MArgs)...);
    return element;
}

template<typename T, typename U, size_t...  I>
T* createElementFromArrayHelper(std::index_sequence<I...>, U* a){
    return createElement<T>(a[I]...);
}

template<typename T, typename U, size_t N>
T* createElementFromArray(U (&a)[N]){
    return createElementFromArrayHelper<T>(std::make_index_sequence<N>{}, a);
}

int main() {

    int Aargs[] = { 1, 2 };
    int Bargs[] = { 1, 2, 3 };

    A* a = createElementFromArray<A>(Aargs);
    B* b = createElementFromArray<B>(Bargs);

    std::cout << "a.x: " << a->x << "\na.y: " << a->y << "\n" << std::endl;
    std::cout << "b.x: " << b->x << "\nb.y: " << b->y << "\nb.z: " << b->z << "\n" << std::endl;

    delete a;
    delete b;

}


答:
When a user changes the order of the elements (by moving an element or toggling a sort function), it should update the array in memory, which should trigger a re-rendering of the DOM elements. Modern front-end JS frameworks do a good job of updating only the necessary DOM elements (using a virtual-dom).

Also, having a single source of truth will allow you to easily expand on the functionality without incurring too much technical debt. For example, if you decide to add pagination or CRUD methods.

Title: Reorder HTML elements - most efficient vs practical way

Body:
I am implementing an UI list of items. It supports ordering by sort functions and custom drag and drop ordering.

It will be used for displaying hundreds of items.

I am looking for the "best" way to implement the ordering.

Sorting is always done on data model in memory and is then projected onto the UI.

First solution I know about is just reorder the DOM elements. Simple, but it feels like a little too resource heavy...

...in comparison with flexbox and css order. That is the second solution I have in mind. Assign order with increasing values and let css do its magic... hopefully with less resources used.

The problem with css order is that if I remove or add list items, it does not reindex (the order value) automatically, so there is more maintenance to keep the system working as opposed to using DOM element order.

Do you see any (dis)advantages with using either of those?
Do you agree that using css order is (significantly) faster/less expensive?
Any other options to order elements?

Edit:
Pagination is not an option. My question is only concerning the mechanisms to reorder elements.


问:
Pandas column to row transformation for a Range
I am looking to transform the below df based on the range from range(merge_m,merge_end,merge_freq)

```<code>data={'cf':['cf1','cf2'],'Amount':['1000','2000'],
     'merge_m':['1','3'],
     'merge_end':['4','5'],
     'merge_freq':['1','2']}

df=pd.DataFrame(data)
</code>```

and I am looking to convert this into:

```<code>data_f={'m':[1,2,3,4,5],
        'cf1':['1000','1000','1000','1000',0],
         'cf2':[0,0,'2000',0,'2000']}
df_f=pd.DataFrame(data_f)
</code>```

答:
One way to solve this question, assuming I interpreted it correctly:

# convert to numeric dtypes:
df = df.transform(pd.to_numeric, errors="ignore")

# generate ranges based on the last three columns:
ranges = zip(df.merge_m, df.merge_end + df.merge_freq, df.merge_freq)
ranges = [
    range(start, end, freq)
    for start, end, freq in ranges
 ]

# Compute new dataframe:
(df
.loc[:, ["cf", "Amount"]]
.assign(m=ranges)
.explode("m")
.pivot( "m", "cf", "Amount")
.fillna(0, downcast="infer")
.rename_axis(columns=None)
.reset_index()
)

   m   cf1   cf2
0  1  1000     0
1  2  1000     0
2  3  1000  2000
3  4  1000     0
4  5     0  2000
```

Body:
I am looking to transform the below df based on the range from range(merge_m,merge_end,merge_freq)

data={'cf':['cf1','cf2'],'Amount':['1000','2000'],
     'merge_m':['1','3'],
     'merge_end':['4','5'],
     'merge_freq':['1','2']}

df=pd.DataFrame(data)

and I am looking to convert this into:

data_f={'m':[1,2,3,4,5],
        'cf1':['1000','1000','1000','1000',0],
         'cf2':[0,0,'2000',0,'2000']}
df_f=pd.DataFrame(data_f)


问:
Fill Javascript 2d Array with passed Variable
I have an 2d array created thats 50 by 2 and want to fill it with a passed array. I know the array works and the passed variables. But I can't get the passed variable to fill up the array, it just fills with plain text. Is my syntax wrong?

```<code>for (i=0; i <50; i++){
basket[i]=new Array(2);
}

function addtobasket(itemname, itemvalue){
    basket[itemcount][itemcount]='itemname itemvalue;'
}
</code>```

TIA!

答:
'itemname itemvalue' will just fill the array with 'itemname itemvalue'

So you need to write:

```<code>basket[itemcount][itemcount]=itemname+' '+itemvalue;
</code>```

Don't forget to put the semicolon AFTER the string.

Body:
I have an 2d array created thats 50 by 2 and want to fill it with a passed array. I know the array works and the passed variables. But I can't get the passed variable to fill up the array, it just fills with plain text. Is my syntax wrong?

for (i=0; i <50; i++){
basket[i]=new Array(2);
}

function addtobasket(itemname, itemvalue){
    basket[itemcount][itemcount]='itemname itemvalue;'
}

TIA!

Body:
'itemname itemvalue' will just fill the array with 'itemname itemvalue'

So you need to write:

basket[itemcount][itemcount]=itemname+' '+itemvalue;

Don't forget to put the semicolon AFTER the string.


问:
count the distance between to strings in an array Ruby
i have an array

```<code>line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]

user_input1 = "flinders street"
user_input2 = "glenferrie"
</code>```

how could I count the distance between the two strings?
expected output 5.

答:
The first thing that comes to mind:</p>
```<code>line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]

user_input1 = "flinders street"
user_input2 = "glenferrie"

(line_one.find_index(user_input1) - line_one.find_index(user_input2)).abs
#=>  5
</code>```

Body:
i have an array

line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]

user_input1 = "flinders street"
user_input2 = "glenferrie"

how could I count the distance between the two strings?
expected output 5.

Body:
The first thing that comes to mind:

line_one = ["flinders street", "richmond", "east richmond", "burnley", "hawthorn", "glenferrie"]

user_input1 = "flinders street"
user_input2 = "glenferrie"

(line_one.find_index(user_input1) - line_one.find_index(user_input2)).abs
#=>  5