问:
WinRM on Azure RM VM
I'm trying to connect to an AzureRM VM. I've read through so many tutorials on WinRM but I still cannot get this to work:

```<code>    Enter-PSSession -ComputerName "$($HOST).cloudapp.net" -Credential $username
</code>```

When I run this, I get the following error:

The user name or password is incorrect. For more information, see the about_Remote_Troubleshooting Help topic

When I add the -UseSSL param I get this error:

The WinRM client cannot process the request because the server name cannot be resolved. For more information, see the
  about_Remote_Troubleshooting Help topic.

The credentials I'm entering are correct. So I also tried "localhost\$username" and I get a different error:

The following error with errorcode 0x80090311 occurred while using Kerberos authentication:

So I tried to use -Authentication basic and I get:

The WinRM client cannot process the request. Unencrypted traffic is currently disabled in the client configuration

But I have already checked and unencrypted traffic is enabled.

Has anyone come across this issue before? Any suggestions as to what to try next?

```<code>    credentials = Get-Credential -UserName $username -Message "Enter Azure account credentials"
    $continue=$false
    Do{
$session = New-PSSession -ComputerName "$($VMName).cloudapp.net" -Credential $credentials
if ($session -ne $null)
{
  $continue=$true
}
Write-Output "Unable to create a PowerShell session . . . sleeping and trying again in 30 seconds."
Start-Sleep -Seconds 30
      }
   Until(
$continue=$true)
</code>```

EDIT Adding what the settings are now on the Server:

```<code>   WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client

Type            Name                           SourceOfValue   Value
----            ----                           -------------   -----
System.String   NetworkDelayms                                 5000
System.String   URLPrefix                                      wsman
System.String   AllowUnencrypted                               true
Container       Auth
Container       DefaultPorts
System.String   TrustedHosts
</code>```

And the client:

```<code>   WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client

 Type            Name                           SourceOfValue   Value
 ----            ----                           -------------   -----
 System.String   NetworkDelayms                                 5000
 System.String   URLPrefix                                      wsman
 System.String   AllowUnencrypted                               true
 Container       Auth
 Container       DefaultPorts
 System.String   TrustedHosts                                   @{Value = "XX.XX.XX.XX"}
</code>```

答:
Below parameter helps to connect the Azure VM through WINRM </p>

```<code>    $hostName="DomainName"
$winrmPort = "5986"
# Get the credentials of the machine
$cred = Get-Credential
# Connect to the machine
$soptions = New-PSSessionOption -SkipCACheck
Enter-PSSession -ComputerName $hostName -Port $winrmPort -Credential $cred -SessionOption $soptions -UseSSL
</code>```

Title: WinRM on Azure RM VM

Body:
I'm trying to connect to an AzureRM VM. I've read through so many tutorials on WinRM but I still cannot get this to work:

    Enter-PSSession -ComputerName "$($HOST).cloudapp.net" -Credential $username

When I run this, I get the following error:

The user name or password is incorrect. For more information, see the about_Remote_Troubleshooting Help topic

When I add the -UseSSL param I get this error:

The WinRM client cannot process the request because the server name cannot be resolved. For more information, see the
  about_Remote_Troubleshooting Help topic.

The credentials I'm entering are correct. So I also tried "localhost\$username" and I get a different error:

The following error with errorcode 0x80090311 occurred while using Kerberos authentication:

So I tried to use -Authentication basic and I get:

The WinRM client cannot process the request. Unencrypted traffic is currently disabled in the client configuration

But I have already checked and unencrypted traffic is enabled.

Has anyone come across this issue before? Any suggestions as to what to try next?

    credentials = Get-Credential -UserName $username -Message "Enter Azure account credentials"
    $continue=$false
    Do{
$session = New-PSSession -ComputerName "$($VMName).cloudapp.net" -Credential $credentials
if ($session -ne $null)
{
  $continue=$true
}
Write-Output "Unable to create a PowerShell session . . . sleeping and trying again in 30 seconds."
Start-Sleep -Seconds 30
      }
   Until(
$continue=$true)

EDIT Adding what the settings are now on the Server:

   WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client

Type            Name                           SourceOfValue   Value
----            ----                           -------------   -----
System.String   NetworkDelayms                                 5000
System.String   URLPrefix                                      wsman
System.String   AllowUnencrypted                               true
Container       Auth
Container       DefaultPorts
System.String   TrustedHosts

And the client:

   WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Client

 Type            Name                           SourceOfValue   Value
 ----            ----                           -------------   -----
 System.String   NetworkDelayms                                 5000
 System.String   URLPrefix                                      wsman
 System.String   AllowUnencrypted                               true
 Container       Auth
 Container       DefaultPorts
 System.String   TrustedHosts                                   @{Value = "XX.XX.XX.XX"}

Body:
Below parameter helps to connect the Azure VM through WINRM

    $hostName="DomainName"
$winrmPort = "5986"
# Get the credentials of the machine
$cred = Get-Credential
# Connect to the machine
$soptions = New-PSSessionOption -SkipCACheck
Enter-PSSession -ComputerName $hostName -Port $winrmPort -Credential $cred -SessionOption $soptions -UseSSL


来源: stackexchange

问:
Static allocation of opaque data types
Very often malloc() is absolutely not allowed when programming for embedded systems. Most of the time I'm pretty able to deal with this, but one thing irritates me: it keeps me from using so called 'opaque types' to enable data hiding. Normally I'd do something like this:

```<code>// In file module.h
typedef struct handle_t handle_t;

handle_t *create_handle();
void operation_on_handle(handle_t *handle, int an_argument);
void another_operation_on_handle(handle_t *handle, char etcetera);
void close_handle(handle_t *handle);

// In file module.c
struct handle_t {
    int foo;
    void *something;
    int another_implementation_detail;
};

handle_t *create_handle() {
    handle_t *handle = malloc(sizeof(struct handle_t));
    // other initialization
    return handle;
}
</code>```

There you go: create_handle() performs a malloc() to create an 'instance'. A construction often used to prevent having to malloc() is to change the prototype of create_handle() like this:

```<code>void create_handle(handle_t *handle);
</code>```

And then the caller could create the handle this way:

```<code>// In file caller.c
void i_am_the_caller() {
    handle_t a_handle;    // Allocate a handle on the stack instead of malloc()
    create_handle(&a_handle);
    // ... a_handle is ready to go!
}
</code>```

But unfortunately this code is obviously invalid, the size of handle_t isn't known!

I never really found a solution to solve this in a proper way. I'd very like to know if anyone has a proper way of doing this, or maybe a complete different approach to enable data hiding in C (not using static globals in the module.c of course, one must be able to create multiple instances).

答:
You can use the _alloca function. I believe that it's not exactly Standard, but as far as I know, nearly all common compilers implement it. When you use it as a default argument, it allocates off the caller's stack.

```<code>// Header
typedef struct {} something;
size_t get_size();
something* create_something(void* mem);

// Usage
something* ptr = create_something(_alloca(get_size())); // or define a macro.

// Implementation
size_t get_size() {
    return sizeof(real_handle_type);
}
something* create_something(void* mem) {
    real_handle_type* ptr = (real_handle_type*)mem;
    // Fill out real_type
    return (something*)mem;
}
</code>```

You could also use some kind of object pool semi-heap - if you have a maximum number of currently available objects, then you could allocate all memory for them statically, and just bit-shift for which ones are currently in use.

```<code>#define MAX_OBJECTS 32
real_type objects[MAX_OBJECTS];
unsigned int in_use; // Make sure this is large enough
something* create_something() {
     for(int i = 0; i < MAX_OBJECTS; i++) {
         if (!(in_use & (1 << i))) {
             in_use |= (1 << i);
             return &objects[i];
         }
     }
     return NULL;
}
</code>```

My bit-shifting is a little off, been a long time since I've done it, but I hope that you get the point.

ContentLicense: CC BY-SA 2.5

Title: Static allocation of opaque data types

Body:
Very often malloc() is absolutely not allowed when programming for embedded systems. Most of the time I'm pretty able to deal with this, but one thing irritates me: it keeps me from using so called 'opaque types' to enable data hiding. Normally I'd do something like this:

// In file module.h
typedef struct handle_t handle_t;

handle_t *create_handle();
void operation_on_handle(handle_t *handle, int an_argument);
void another_operation_on_handle(handle_t *handle, char etcetera);
void close_handle(handle_t *handle);

// In file module.c
struct handle_t {
    int foo;
    void *something;
    int another_implementation_detail;
};

handle_t *create_handle() {
    handle_t *handle = malloc(sizeof(struct handle_t));
    // other initialization
    return handle;
}

There you go: create_handle() performs a malloc() to create an 'instance'. A construction often used to prevent having to malloc() is to change the prototype of create_handle() like this:

void create_handle(handle_t *handle);

And then the caller could create the handle this way:

// In file caller.c
void i_am_the_caller() {
    handle_t a_handle;    // Allocate a handle on the stack instead of malloc()
    create_handle(&a_handle);
    // ... a_handle is ready to go!
}

But unfortunately this code is obviously invalid, the size of handle_t isn't known!

I never really found a solution to solve this in a proper way. I'd very like to know if anyone has a proper way of doing this, or maybe a complete different approach to enable data hiding in C (not using static globals in the module.c of course, one must be able to create multiple instances).

Body:
You can use the _alloca function. I believe that it's not exactly Standard, but as far as I know, nearly all common compilers implement it. When you use it as a default argument, it allocates off the caller's stack.

// Header
typedef struct {} something;
size_t get_size();
something* create_something(void* mem);

// Usage
something* ptr = create_something(_alloca(get_size())); // or define a macro.

// Implementation
size_t get_size() {
    return sizeof(real_handle_type);
}
something* create_something(void* mem) {
    real_handle_type* ptr = (real_handle_type*)mem;
    // Fill out real_type
    return (something*)mem;
}

You could also use some kind of object pool semi-heap - if you have a maximum number of currently available objects, then you could allocate all memory for them statically, and just bit-shift for which ones are currently in use.

#define MAX_OBJECTS 32
real_type objects[MAX_OBJECTS];
unsigned int in_use; // Make sure this is large enough
something* create_something() {
     for(int i = 0; i < MAX_OBJECTS; i++) {
         if (!(in_use & (1 << i))) {
             in_use |= (1 << i);
             return &objects[i];
         }
     }
     return NULL;
}

My bit-shifting is a little off, been a long time since I've done it, but I hope that you get the point.

ContentLicense: CC BY-SA 4.0


问:
Fetching data in form of radio button format for quiz game in PHP
I have stored data in database statically. Its having 5 col One for question and 4 col. for answers. Basically its a quiz game format. Now I want to fetch data from database in the form of radio button for that 4 col. How to implement that method. Currently i am fetching in normal text mode.

Here is the code

```<code> <?php

// Create connection
$conn = new mysqli("localhost","root","","QuizQuestions");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully<br><br>";

$sql = "SELECT Question, Answer1, Answer2, Answer3, Answer4 FROM Questions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "<br>Question: " . $row["Question"]. "<br>";
    echo " A) " . $row["Answer1"]. "<br>";
    echo " B) " . $row["Answer2"]. "<br>";
    echo " C) " . $row["Answer3"]. "<br>";
    echo " D) " . $row["Answer4"]. "<br>";
}
} else {
 echo "0 results";
}
$conn->close();

?>
</code>```

答:
why you dont try select than radio? but here's what you're looking for if i'm not mistaken</p>

```<code><input type="radio" name="'.$row["Answer1"].'" value="'.$row["Answer1"].'" />
then just validate in your javascript if the radio button has a value make it checked.
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have stored data in database statically. Its having 5 col One for question and 4 col. for answers. Basically its a quiz game format. Now I want to fetch data from database in the form of radio button for that 4 col. How to implement that method. Currently i am fetching in normal text mode.

Here is the code

 <?php

// Create connection
$conn = new mysqli("localhost","root","","QuizQuestions");

// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully

";

$sql = "SELECT Question, Answer1, Answer2, Answer3, Answer4 FROM Questions";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "
Question: " . $row["Question"]. "
";
    echo " A) " . $row["Answer1"]. "
";
    echo " B) " . $row["Answer2"]. "
";
    echo " C) " . $row["Answer3"]. "
";
    echo " D) " . $row["Answer4"]. "
";
}
} else {
 echo "0 results";
}
$conn->close();

?>

Body:
why you dont try select than radio? but here's what you're looking for if i'm not mistaken

<input type="radio" name="'.$row["Answer1"].'" value="'.$row["Answer1"].'" />
then just validate in your javascript if the radio button has a value make it checked.


问:
Change part of controltemplate in styled controls?
I have customized the ToggleButton control using a ControlTemplate like so:

```<code><StackPanel>
    <StackPanel.Resources>
        <Style x:Key="OptionBarButton" TargetType="{x:Type ToggleButton}">
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ToggleButton">
                        <Border Padding="18,12,18,12" Background="{TemplateBinding Background}">
                            <ContentPresenter />
                        </Border>
                        <ControlTemplate.Triggers>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsChecked" Value="True" />
                                    <Condition Property="IsMouseOver" Value="True" />
                                </MultiTrigger.Conditions>
                                <MultiTrigger.Setters>
                                    <Setter Property="Background" Value="DarkBlue" />
                                </MultiTrigger.Setters>
                            </MultiTrigger>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsChecked" Value="True" />
                                    <Condition Property="IsMouseOver" Value="False" />
                                </MultiTrigger.Conditions>
                                <MultiTrigger.Setters>
                                    <Setter Property="Background" Value="SkyBlue" />
                                </MultiTrigger.Setters>
                            </MultiTrigger>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsChecked" Value="False" />
                                    <Condition Property="IsMouseOver" Value="False" />
                                </MultiTrigger.Conditions>
                                <MultiTrigger.Setters>
                                    <Setter Property="Background" Value="#88000000" />
                                </MultiTrigger.Setters>
                            </MultiTrigger>
                            <MultiTrigger>
                                <MultiTrigger.Conditions>
                                    <Condition Property="IsChecked" Value="False" />
                                    <Condition Property="IsMouseOver" Value="True" />
                                </MultiTrigger.Conditions>
                                <MultiTrigger.Setters>
                                    <Setter Property="Background" Value="#F0000000" />
                                </MultiTrigger.Setters>
                            </MultiTrigger>
                        </ControlTemplate.Triggers>

                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </StackPanel.Resources>

    <ToggleButton Style="{StaticResource OptionBarButton}">
        <Image Source="../Assets/icons/action.png" Height="26" RenderOptions.BitmapScalingMode="Fant" />
    </ToggleButton>

    <ToggleButton Style="{StaticResource OptionBarButton}">
        <Image Source="../Assets/icons/action2.png" Height="26" RenderOptions.BitmapScalingMode="Fant" />
    </ToggleButton>

</StackPanel>
</code>```

This works fine, however I would now want to change some parts of the template in some of the styled controls, namely the IsChecked color states (SkyBlue/DarkBlue).

Is it possible to modify / pass these colors in/to the template when using it? I know I can use attached properties or/and subclass the ToggleButton class (adding dependency properties to it), but I was wondering if there isn't a more idiomatic way to solve this, perhaps only with xaml. Having to write custom code in C# seems a little bit overkill for such a simple use case?

答:
Unfortunately, ControlTemplates are a all-or-nothing thing. If you want to change the colors you reference inside them, you have to switch templates. I suppose that having references to resources in the template is not an option for you.

I would create Dependency Properties for each of the variable colors in OptionBarButton.

Body:
I have customized the ToggleButton control using a ControlTemplate like so:

<StackPanel>
    <StackPanel.Resources>

    </StackPanel.Resources>

    <ToggleButton Style="{StaticResource OptionBarButton}">
        <Image Source="../Assets/icons/action.png" Height="26" RenderOptions.BitmapScalingMode="Fant" />
    </ToggleButton>

    <ToggleButton Style="{StaticResource OptionBarButton}">
        <Image Source="../Assets/icons/action2.png" Height="26" RenderOptions.BitmapScalingMode="Fant" />
    </ToggleButton>

</StackPanel>

This works fine, however I would now want to change some parts of the template in some of the styled controls, namely the IsChecked color states (SkyBlue/DarkBlue).

Is it possible to modify / pass these colors in/to the template when using it? I know I can use attached properties or/and subclass the ToggleButton class (adding dependency properties to it), but I was wondering if there isn't a more idiomatic way to solve this, perhaps only with xaml. Having to write custom code in C# seems a little bit overkill for such a simple use case?


问:
How differentiating a char of an int?
I want to know, if have a command that find  which is the type of that it's in the variable , if it's a char or int.
For example to make a program that, if anything that isn't a number is entered, show an error to user, because I am using an int variable in the scanf, but if the user type a char, the program continue, I want do it stop, when an type char are typed</p>

答: Try using isdigit(int c). It returns a non-zero value if c in a digit, otherwise il resturs 0. For more information type 'man isdigit'</p>

Title: How differentiating a char of an int?


问:
Big ugly SQL query problem
I have two tables:
Status(status_id, desc1, desc2, desc3, desc4)
Status_Level(status_level_id, desc, levelD, levelS)

The connection is on the desc1..4 fileds in Status and desc in Status_Level.
I need to select status_id, levelD and levelS where levelD and levelS are highest levels of all four descs.

I tried this:

```<code>SELECT Status.status_id, MAX(levelS) AS ds_column, MAX(levelD) AS ss_column
FROM Status, Status_level WHERE
Status_level.desc=Status.desc1 OR
Status_level.desc=Status.desc2 OR
Status_level.desc=Status.desc3 OR
Status_level.desc=Status.desc4
GROUP BY Status.status_id
</code>```

My SQL is very rusty so any help would be greatly appreciated.
Thanks.

edit:
example:

```<code>Status:
-----------------------------------------------------------
| 1 | ABC_LEVEL_1 | DEF_LEVEL_5| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------
| 2 | ABC_LEVEL_1 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_1|
-----------------------------------------------------------
| 3 | ABC_LEVEL_4 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------

Status_Level:
---------------------------
| 1 | ABC_LEVEL_1 | 1 | 7 |
---------------------------
| 1 | DEF_LEVEL_5 | 5 | 6 |
---------------------------
| 1 | CBA_LEVEL_2 | 2 | 3 |
---------------------------
| 1 | ABC_LEVEL_4 | 4 | 5 |
---------------------------
| 1 | DEF_LEVEL_1 | 1 | 2 |

Desired output:

-------------
| 1 | 5 | 7 | <- 5 from DEF_LEVEL_5 and 7 from ABC_LEVEL_1
-------------
| 2 | 2 | 7 | <- 2 from CBA_LEVEL_2 and 7 from ABC_LEVEL_1
-------------
| 3 | 4 | 5 | <- 4 from ABC_LEVEL_4 and 5 from ABC_LEVEL_4
-------------
</code>```

答:
```<code>SELECT Status.status_id, MAX(levelS) AS ds_column, MAX(levelD) AS ss_column
FROM Status, Status_level WHERE
Status_level.desc in (Status.desc1, Status.desc2, Status.desc3, Status.desc4)
GROUP BY Status.status_id
</code>```

Title: Big ugly SQL query problem

Body:
I have two tables:
Status(status_id, desc1, desc2, desc3, desc4)
Status_Level(status_level_id, desc, levelD, levelS)

The connection is on the desc1..4 fileds in Status and desc in Status_Level.
I need to select status_id, levelD and levelS where levelD and levelS are highest levels of all four descs.

I tried this:

SELECT Status.status_id, MAX(levelS) AS ds_column, MAX(levelD) AS ss_column
FROM Status, Status_level WHERE
Status_level.desc=Status.desc1 OR
Status_level.desc=Status.desc2 OR
Status_level.desc=Status.desc3 OR
Status_level.desc=Status.desc4
GROUP BY Status.status_id

My SQL is very rusty so any help would be greatly appreciated.
Thanks.

edit:
example:

Status:
-----------------------------------------------------------
| 1 | ABC_LEVEL_1 | DEF_LEVEL_5| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------
| 2 | ABC_LEVEL_1 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_1|
-----------------------------------------------------------
| 3 | ABC_LEVEL_4 | DEF_LEVEL_1| CBA_LEVEL_2 | ABC_LEVEL_4|
-----------------------------------------------------------

Status_Level:
---------------------------
| 1 | ABC_LEVEL_1 | 1 | 7 |
---------------------------
| 1 | DEF_LEVEL_5 | 5 | 6 |
---------------------------
| 1 | CBA_LEVEL_2 | 2 | 3 |
---------------------------
| 1 | ABC_LEVEL_4 | 4 | 5 |
---------------------------
| 1 | DEF_LEVEL_1 | 1 | 2 |

Desired output:

-------------
| 1 | 5 | 7 | <- 5 from DEF_LEVEL_5 and 7 from ABC_LEVEL_1
-------------
| 2 | 2 | 7 | <- 2 from CBA_LEVEL_2 and 7 from ABC_LEVEL_1
-------------
| 3 | 4 | 5 | <- 4 from ABC_LEVEL_4 and 5 from ABC_LEVEL_4
-------------


问:
Insert schemaLocation in the XML File using XSLT v2.0
I'm having a problem inserting a schemaLocation in the XML File. I almost got the expected output but the other elements populates the schemaLocation. Here is my sample file:

INPUT:

```<code><Sync releaseID="9.2">
<Document>
    <Group>
        <Header>
            <Field1>232</Field1>
            <Field2>dfd</Field2>
        </Header>
    </Group>
</Document>
</code>```

And, I want to add the namespace and schemalocation in <Document> tag. Here is my XSLT:

```<code><xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="*[ancestor-or-self::Document]">
    <xsl:element name="{name()}" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
        <xsl:attribute name="xsi:schemaLocation">urn:iso:std:iso:20022:tech:xsd:pain.001.001.03</xsl:attribute>
        <xsl:apply-templates select="*"/>
    </xsl:element>
</xsl:template>
</xsl:stylesheet>
</code>```

GENERATED OUTPUT:

```<code><Sync releaseID="9.2">
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
    <Group xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
        <Header xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
            <Field1 xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">232</Field1>
            <Field2 xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">dfd</Field2>
        </Header>
    </Group>
</Document>
</code>```

EXPECTED OUTPUT:

```<code><Sync releaseID="9.2">
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
    <Group>
        <Header>
            <Field1>232</Field1>
            <Field2>dfd</Field2>
        </Header>
    </Group>
</Document>
</code>```

How can I remove the schemaLocation in the other elements?

Thanks.

答: You only want to do this special processing for the Document element, not for every element that has Document as an ancestor, so just change the match pattern from match="*[ancestor-or-self::Document]" to match="Document".

Body:
I'm having a problem inserting a schemaLocation in the XML File. I almost got the expected output but the other elements populates the schemaLocation. Here is my sample file:

INPUT:

<Sync releaseID="9.2">
<Document>
    <Group>

            <Field1>232</Field1>
            <Field2>dfd</Field2>

    </Group>
</Document>

And, I want to add the namespace and schemalocation in <Document> tag. Here is my XSLT:

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
<xsl:template match="@*|node()">
    <xsl:copy>
        <xsl:apply-templates select="@*|node()"/>
    </xsl:copy>
</xsl:template>
<xsl:template match="*[ancestor-or-self::Document]">
    <xsl:element name="{name()}" namespace="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
        <xsl:attribute name="xsi:schemaLocation">urn:iso:std:iso:20022:tech:xsd:pain.001.001.03</xsl:attribute>
        <xsl:apply-templates select="*"/>
    </xsl:element>
</xsl:template>
</xsl:stylesheet>

GENERATED OUTPUT:

<Sync releaseID="9.2">
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
    <Group xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">

            <Field1 xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">232</Field1>
            <Field2 xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">dfd</Field2>

    </Group>
</Document>

EXPECTED OUTPUT:

<Sync releaseID="9.2">
<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="urn:iso:std:iso:20022:tech:xsd:pain.001.001.03">
    <Group>

            <Field1>232</Field1>
            <Field2>dfd</Field2>

    </Group>
</Document>

How can I remove the schemaLocation in the other elements?

Thanks.


问:
Msg 102, Level 15, State 1, Line 18 Incorrect syntax near ','
Is doesn't seem to like the first comma after SUM(c.[chargeable weight]). Do you guys can identify why? I genuinely can't understand the reason why it is doing this.

```<code>    Select
 (SUM(c.[Chargeable Weight]), MAX (ts.systemstamp), mm.MovementRef
                                FROM      dbo.whsConsignment wc
                                                   INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                   INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                    inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                   inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                                                --AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'C'
                                                                                --AND ts.SlackNoSlack like 'No Slack - Must Load%'
                                                                                --and ts.SLackNoSLack like 'No Slack - Tripped%'
                                                                                and ts.scheduledescription = 'No Slack - Tripped'
                                                                                group by mm.MovementRef) as chargeableweight
                                                                                --and ts.systemstamp = max (ts.systemstamp)
 Into #2chargns
</code>```

答:
You missed the SELECT within the brackets

```<code>   SELECT * FROM
 (SELECT SUM(c.[Chargeable Weight]) AS Sum, MAX (ts.systemstamp) AS Max, mm.MovementRef
                                FROM      dbo.whsConsignment wc
                                                   INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                   INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                    inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                   inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                                                --AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'C'
                                                                                --AND ts.SlackNoSlack like 'No Slack - Must Load%'
                                                                                --and ts.SLackNoSLack like 'No Slack - Tripped%'
                                                                                and ts.scheduledescription = 'No Slack - Tripped'
                                                                                group by mm.MovementRef) as chargeableweight
                                                                                --and ts.systemstamp = max (ts.systemstamp)
 Into #2chargns
</code>```

Body:
Is doesn't seem to like the first comma after SUM(c.[chargeable weight]). Do you guys can identify why? I genuinely can't understand the reason why it is doing this.

    Select
 (SUM(c.[Chargeable Weight]), MAX (ts.systemstamp), mm.MovementRef
                                FROM      dbo.whsConsignment wc
                                                   INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                   INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                    inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                   inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                                                --AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'C'
                                                                                --AND ts.SlackNoSlack like 'No Slack - Must Load%'
                                                                                --and ts.SLackNoSLack like 'No Slack - Tripped%'
                                                                                and ts.scheduledescription = 'No Slack - Tripped'
                                                                                group by mm.MovementRef) as chargeableweight
                                                                                --and ts.systemstamp = max (ts.systemstamp)
 Into #2chargns

Body:
You missed the SELECT within the brackets

   SELECT * FROM
 (SELECT SUM(c.[Chargeable Weight]) AS Sum, MAX (ts.systemstamp) AS Max, mm.MovementRef
                                FROM      dbo.whsConsignment wc
                                                   INNER JOIN dbo.cgtConsignment c ON c.[Consignment Reference] = wc.ConsignmentReference
                                                   INNER JOIN dbo.tsAdditionalColInfo ts on ts.[ConsignmentReference]= wc.ConsignmentReference
                                                    inner join dbo.movConLink m on m.ConsignmentReference = c.[Consignment Reference]
                                                   inner join dbo.movMovement mm on mm.MovementID = m.MovementID
                                                                                --AND wc.whsHeaderID = wh.WhsHeaderID
                                                                                AND wc.StatusCode = 'NL'
                                                                                AND c.[Service Type] = 'C'
                                                                                --AND ts.SlackNoSlack like 'No Slack - Must Load%'
                                                                                --and ts.SLackNoSLack like 'No Slack - Tripped%'
                                                                                and ts.scheduledescription = 'No Slack - Tripped'
                                                                                group by mm.MovementRef) as chargeableweight
                                                                                --and ts.systemstamp = max (ts.systemstamp)
 Into #2chargns


问:
Index was outside the bounds of the array.C#
I've a part of program that have method to generate code (HelmID), to generate it, i've to read from text file to get the latest HelmID. Here's my text file.

```<code>T001#C001#H001#FullFace#S001#
T001#C001#H002#FullFace#S002#
</code>```

The problem is, the method wont generate to H003 (after H002) and give error message 'Index was outside the bounds of the array'. Here's my method code.

```<code>public string newHelmetCode()
        {
            string Str, HelmetCode;
            int HelmetInt;
            string[] strArray = new string[5];
            if (new FileInfo("TransDetail.txt").Length == 0)
            {
                HelmetCode = "H001";
                return HelmetCode;
            }
            else
            {
                Str = File.ReadLines("TransDetail.txt").Last();
                strArray = Str.Split(new string[] { "#" }, StringSplitOptions.None);

                HelmetCode = strArray[2].Substring(1, 3);
                HelmetInt = Convert.ToInt32(HelmetCode) + 1;

                if (HelmetInt <= 9)
                {
                    HelmetCode = "H00" + HelmetInt.ToString();
                }
                else if (HelmetInt <= 99)
                {
                    HelmetCode = "H0" + HelmetInt.ToString();
                }
                else if (HelmetInt <= 999)
                {
                    HelmetCode = "H" + HelmetInt.ToString();
                }
                return HelmetCode;
            }
        }
</code>```

The error come from this code HelmetCode = strArray[2].Substring(1, 3);. It should generate cause i'm using Substring (and convert to int) to get latest number on last row on text file. Any reply would appricate

答:
Obviously the strArray has less than three items in it.

You should check on the length first. (My guess is that the last line is an empty line btw):

```<code>if (strArray.Length >= 3)
{
    // do
}
</code>```

You should also check the length of the string you want to Substring, because when the length < 1, you will get an ArgumentOutOfRangeException.

So check the length:

```<code>string test = strArray[2];

if (test.Length > 1)
{
    // do
}
</code>```

Body:
I've a part of program that have method to generate code (HelmID), to generate it, i've to read from text file to get the latest HelmID. Here's my text file.

T001#C001#H001#FullFace#S001#
T001#C001#H002#FullFace#S002#

The problem is, the method wont generate to H003 (after H002) and give error message 'Index was outside the bounds of the array'. Here's my method code.

public string newHelmetCode()
        {
            string Str, HelmetCode;
            int HelmetInt;
            string[] strArray = new string[5];
            if (new FileInfo("TransDetail.txt").Length == 0)
            {
                HelmetCode = "H001";
                return HelmetCode;
            }
            else
            {
                Str = File.ReadLines("TransDetail.txt").Last();
                strArray = Str.Split(new string[] { "#" }, StringSplitOptions.None);

                HelmetCode = strArray[2].Substring(1, 3);
                HelmetInt = Convert.ToInt32(HelmetCode) + 1;

                if (HelmetInt <= 9)
                {
                    HelmetCode = "H00" + HelmetInt.ToString();
                }
                else if (HelmetInt <= 99)
                {
                    HelmetCode = "H0" + HelmetInt.ToString();
                }
                else if (HelmetInt <= 999)
                {
                    HelmetCode = "H" + HelmetInt.ToString();
                }
                return HelmetCode;
            }
        }

The error come from this code HelmetCode = strArray[2].Substring(1, 3);. It should generate cause i'm using Substring (and convert to int) to get latest number on last row on text file. Any reply would appricate

Body:
Obviously the strArray has less than three items in it.

You should check on the length first. (My guess is that the last line is an empty line btw):

if (strArray.Length >= 3)
{
    // do
}

You should also check the length of the string you want to Substring, because when the length < 1, you will get an ArgumentOutOfRangeException.

So check the length:

string test = strArray[2];

if (test.Length > 1)
{
    // do
}


问:
Loop Through Magento Categories, Meta Keywords and Descriptions
I have a file that is successfully looping through my categories and subcategories. I am successfully able to echo all the categories and their links

BUT

I do not understand why these (keywords and description) are not echoing

```<code><?php echo htmlspecialchars($this->getKeywords()) ?>
<?php echo htmlspecialchars($this->getDescription()) ?>
</code>```

The file is located here
app/design/frontend/mystoretheme/default/template/catalog/category/listofcats.phtml

Then im placing it on a block in a cms page {{block type="catalog/navigation" name="catalog.category" template="catalog/category/listofcats.phtml"}}

The goal is to be able to display each of the categories list of keywords and their descriptions within the same
 and loop giving me a list like this

Category

Keywords

Description

Here is my code. I have omitted my attempts at keyword and description since they are not working.

```<code><div class="block block-list block-categories">
<div id="block-categories" class="block-title active">
    <strong><span>Categories </span></strong>
</div>
<div id="leftnav" class="block-content" style="display:block">
    <?php $helper = $this->helper('catalog/category') ?>
        <?php $categories = $this->getStoreCategories() ?>
    <?php if (count($categories) > 0): ?>
        <ul id="leftnav-tree" class="level0">
            <?php foreach($categories as $category): ?>
                <li class="level0<?php if ($this->isCategoryActive($category)): ?> active<?php endif; ?>">
                    <a href="<?php echo $helper->getCategoryUrl($category) ?>"><span><?php echo $this->escapeHtml($category->getName()) ?></span></a>
                    <?php //if ($this->isCategoryActive($category)): ?>
                        <?php $subcategories = $category->getChildren() ?>
                        <?php if (count($subcategories) > 0): ?>
                            <ul id="leftnav-tree-<?php echo $category->getId() ?>" class="level1">
                                <?php foreach($subcategories as $subcategory): ?>
                                    <li class="level1<?php if ($this->isCategoryActive($subcategory)): ?> active<?php endif; ?>">
                                        <a href="<?php echo $helper->getCategoryUrl($subcategory) ?>"><?php echo $this->escapeHtml(trim($subcategory->getName(), '- ')) ?></a>
                                         <?php $secondLevelSubcategories = $subcategory->getChildren() ?>
                                         <?php if (count($secondLevelSubcategories ) > 0): ?>
                            <ul id="leftnav-tree-<?php echo $subcategory->getId() ?>" class="level2">
                                <?php foreach($secondLevelSubcategories as $secondLevelSubcategory ): ?>
                                    <li class="level2<?php if ($this->isCategoryActive($secondLevelSubcategory )): ?> active<?php endif; ?>">
                                        <a href="<?php echo $helper->getCategoryUrl($secondLevelSubcategory ) ?>"><?php echo $this->escapeHtml(trim($secondLevelSubcategory ->getName(), '- ')) ?></a>
                                    </li>
                                    <?php endforeach; ?>
                            </ul>
                            <script type="text/javascript">decorateList('leftnav-tree-<?php echo $category->getId() ?>', 'recursive')</script>
                        <?php endif; ?>
                                <?php endforeach; ?>
                            </ul>
                            <script type="text/javascript">decorateList('leftnav-tree-<?php echo $category->getId() ?>', 'recursive')</script>
                        <?php endif; ?>
                    <?php //endif; ?>
                </li>
            <?php endforeach; ?>
        </ul>
        <script type="text/javascript">decorateList('leftnav-tree', 'recursive')</script>
    <?php endif; ?>
</div>
</code>```

答:
Please check this:</p>

```<code><?php
$categories = Mage::getModel('catalog/category')
                ->getCollection()
                ->setStoreId(Put the store id here)
                ->addAttributeToSelect('*')
                ->addIsActiveFilter();
foreach ($categories as $category) {
    echo $category->getName();
    echo "-";
    echo $category->getMetaKeywords();
    echo "-";
    echo $category->getMetaDescription();
    echo "<br/>";
}
?>
</code>```

Body:
I have a file that is successfully looping through my categories and subcategories. I am successfully able to echo all the categories and their links

BUT

I do not understand why these (keywords and description) are not echoing

<?php echo htmlspecialchars($this->getKeywords()) ?>
<?php echo htmlspecialchars($this->getDescription()) ?>

The file is located here
app/design/frontend/mystoretheme/default/template/catalog/category/listofcats.phtml

Then im placing it on a block in a cms page {{block type="catalog/navigation" name="catalog.category" template="catalog/category/listofcats.phtml"}}

The goal is to be able to display each of the categories list of keywords and their descriptions within the same
 and loop giving me a list like this

Category

Keywords

Description

Here is my code. I have omitted my attempts at keyword and description since they are not working.

    Categories

    <?php $helper = $this->helper('catalog/category') ?>
        <?php $categories = $this->getStoreCategories() ?>
    <?php if (count($categories) > 0): ?>

            <?php foreach($categories as $category): ?>
                <li class="level0<?php if ($this->isCategoryActive($category)): ?> active<?php endif; ?>">
                    <a href="<?php echo $helper->getCategoryUrl($category) ?>"><?php echo $this->escapeHtml($category->getName()) ?>
                    <?php //if ($this->isCategoryActive($category)): ?>
                        <?php $subcategories = $category->getChildren() ?>
                        <?php if (count($subcategories) > 0): ?>
                            <ul id="leftnav-tree-<?php echo $category->getId() ?>" class="level1">
                                <?php foreach($subcategories as $subcategory): ?>
                                    <li class="level1<?php if ($this->isCategoryActive($subcategory)): ?> active<?php endif; ?>">
                                        <a href="<?php echo $helper->getCategoryUrl($subcategory) ?>"><?php echo $this->escapeHtml(trim($subcategory->getName(), '- ')) ?>
                                         <?php $secondLevelSubcategories = $subcategory->getChildren() ?>
                                         <?php if (count($secondLevelSubcategories ) > 0): ?>
                            <ul id="leftnav-tree-<?php echo $subcategory->getId() ?>" class="level2">
                                <?php foreach($secondLevelSubcategories as $secondLevelSubcategory ): ?>
                                    <li class="level2<?php if ($this->isCategoryActive($secondLevelSubcategory )): ?> active<?php endif; ?>">
                                        <a href="<?php echo $helper->getCategoryUrl($secondLevelSubcategory ) ?>"><?php echo $this->escapeHtml(trim($secondLevelSubcategory ->getName(), '- ')) ?>

                                    <?php endforeach; ?>

                        <?php endif; ?>
                                <?php endforeach; ?>

                        <?php endif; ?>
                    <?php //endif; ?>

            <?php endforeach; ?>

    <?php endif; ?>

Body:
Please check this:

<?php
$categories = Mage::getModel('catalog/category')
                ->getCollection()
                ->setStoreId(Put the store id here)
                ->addAttributeToSelect('*')
                ->addIsActiveFilter();
foreach ($categories as $category) {
    echo $category->getName();
    echo "-";
    echo $category->getMetaKeywords();
    echo "-";
    echo $category->getMetaDescription();
    echo "<br/>";
}
?>


问:
Horizontal scroll bar bot working in bootstrap modal
I am having a modal, showing div in 'modal-body'.

```<code><div class="modal-body">
    <div class="scoll-tree">
        <div class="history">
            Report Event Details
        </div>
        <div class="history">
            Report Event Details 1
        </div>
       <div class="history">
            Report Event Details 2
        </div>
       <div class="history">
            Report Event Details 3
        </div>
    </div>
</div>
</code>```

Set the class as bellow :

```<code>.scoll-tree{
   width: 400px;
   height:80px;
   overflow-x: scroll;
}

.history {
    background: rgba(255, 255, 255, 0.7);
    float: left;
    min-width: 5em;
    width: 25ex;
    max-height: 3em;
    margin: 2em;
    padding: 1em;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 16px;
    box-shadow: 2px 5px 5px rgba(0,0,0,0.2);
    vertical-align: central;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
</code>```

I want horizontal scroll bar to 'scoll-tree' container,  when 'history' div exceed the width.

Currently it give vertical scroll bar, i want only horizontal scroll bar.

https://jsfiddle.net/hemantmalpote/4duq2svh/35/

答:
Well not sure whether it is what you are looking for, but check it https://jsfiddle.net/4duq2svh/44/. I changed you css little bit, </p>

```<code>.modal-body {
    width: 400px;
    overflow-x: scroll;
}
.scoll-tree{
   width: 800px;//ideally you it is better to make js script which will calculate this value
   height:80px;
}
</code>```

Body:
I am having a modal, showing div in 'modal-body'.

            Report Event Details

            Report Event Details 1

            Report Event Details 2

            Report Event Details 3

Set the class as bellow :

.scoll-tree{
   width: 400px;
   height:80px;
   overflow-x: scroll;
}

.history {
    background: rgba(255, 255, 255, 0.7);
    float: left;
    min-width: 5em;
    width: 25ex;
    max-height: 3em;
    margin: 2em;
    padding: 1em;
    border: 1px solid rgba(0, 0, 0, 0.2);
    border-radius: 16px;
    box-shadow: 2px 5px 5px rgba(0,0,0,0.2);
    vertical-align: central;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

I want horizontal scroll bar to 'scoll-tree' container,  when 'history' div exceed the width.

Currently it give vertical scroll bar, i want only horizontal scroll bar.

https://jsfiddle.net/hemantmalpote/4duq2svh/35/

Body:
Well not sure whether it is what you are looking for, but check it https://jsfiddle.net/4duq2svh/44/. I changed you css little bit,

.modal-body {
    width: 400px;
    overflow-x: scroll;
}
.scoll-tree{
   width: 800px;//ideally you it is better to make js script which will calculate this value
   height:80px;
}


问:
Unable to bring uploaded images into uploads file using php
After creating a form and typing the php code, i have a form where i am able to input a file, specifically an image, and without reciving any error messages, as well as getting the success message in my url, the image uploaded still can not be found in its destination folder.

Here is the HTML

```<code><form action="" class="navbar-form navbar-right" role="search">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Find Art Here">
                    </div>
                    <button type="submit" class="btn btn-primary">Search</button>
                </form>
</code>```

and here's the php

```<code><?php
if (isset($_POST['submit'])) {
$file = $_FILES['file'];

$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];

$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));

$allow = array('jpg', 'jpeg', 'png', 'pdf');

if (in_array($fileActualExt, $allow)) {
    if($fileError === 0){
        if($fileSize < 5000000) {
            $fileNameNew = uniqid('', true).".".$fileActualExt;
        $fileDestination = 'uplaods/'.$fileNameNew;
        move_uploaded_file($fileTmpName, $fileDestination);
            header("Location: index.php?uploadsucess");
        } else{
            echo "Your file is too big";
        }
    } else {
        echo "There was an error uplaoding your file!";
    }
} else{
    echo "You cannot upload files of this type!";
}
</code>```

}

Code is based and modified from this video : https://www.youtube.com/watch?v=JaRq73y5MJk

Any help would be much appreciated!

答:
in your form add this

```<code>  enctype="multipart/form-data"
</code>```

example

```<code>  <form method="post" class="login-form" enctype="multipart/form-data"
     action="my.php">
</code>```

Body:
After creating a form and typing the php code, i have a form where i am able to input a file, specifically an image, and without reciving any error messages, as well as getting the success message in my url, the image uploaded still can not be found in its destination folder.

Here is the HTML

<form action="" class="navbar-form navbar-right" role="search">

                        <input type="text" class="form-control" placeholder="Find Art Here">

                    <button type="submit" class="btn btn-primary">Search</button>
                </form>

and here's the php

<?php
if (isset($_POST['submit'])) {
$file = $_FILES['file'];

$fileName = $file['name'];
$fileTmpName = $file['tmp_name'];
$fileSize = $file['size'];
$fileError = $file['error'];
$fileType = $file['type'];

$fileExt = explode('.', $fileName);
$fileActualExt = strtolower(end($fileExt));

$allow = array('jpg', 'jpeg', 'png', 'pdf');

if (in_array($fileActualExt, $allow)) {
    if($fileError === 0){
        if($fileSize < 5000000) {
            $fileNameNew = uniqid('', true).".".$fileActualExt;
        $fileDestination = 'uplaods/'.$fileNameNew;
        move_uploaded_file($fileTmpName, $fileDestination);
            header("Location: index.php?uploadsucess");
        } else{
            echo "Your file is too big";
        }
    } else {
        echo "There was an error uplaoding your file!";
    }
} else{
    echo "You cannot upload files of this type!";
}

}

Code is based and modified from this video : https://www.youtube.com/watch?v=JaRq73y5MJk

Any help would be much appreciated!

Body:
in your form add this

  enctype="multipart/form-data"

example

  <form method="post" class="login-form" enctype="multipart/form-data"
     action="my.php">


问:
NSTimer Triggering UIProgressView Failure
I'm using a NSTimer in a NSObject class (Timer), that fires a method, that increments a variable and fires a method in a View Controller (InfoViewController). (Confused ;-D )

Everything shows up on the screen and and the timer is started correctly. The variable f.hunger updates and shows the correct value (when using printf("%f", f.hunger) ) but the UIProgress bar doesn't update itself. f.hunger's starting value is 1.

If anyone can help me, point out where I've made an obvious mistake or got a suggestion it would be most appreciated as it's been doing my head in for a good few hours now. I've added some sample code below to show what I'm doing a bit more clearly.

Cheers everyone. :-D

Timers Class

```<code>- (void)startHungerTimer
{
 if(hungerTimer.isValid == NO)
 {
  infoVC = [[InfoViewController alloc] init];
  self.hungerTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self     selector:@selector(incrementHungerTimer:) userInfo:nil repeats:YES];
 }
}

- (void)incrementHungerTimer:(NSTimer *)aTimer
{
    f.hunger -= 0.01;
    [infoVC updateHungerProgress];
}
</code>```

Info View Controller

```<code>- (void)updateHungerProgress
{
 Functions *f = [Functions sharedFunctions];
 hungerBar.progress = f.hunger;
}

- (void)loadView
{
    hungerBar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    [hungerBar setFrame:CGRectMake(17.0, 30.0, 160.0, 10.0)];
    hungerBar.progress = f.hunger;
    [bView addSubview:hungerBar];
    [hungerBar release];
}
</code>```

答: My guess, given your question and comments, is that your "hungerBar" outlet isn't connected to the progress bar in Interface Builder.</p>

Body:
I'm using a NSTimer in a NSObject class (Timer), that fires a method, that increments a variable and fires a method in a View Controller (InfoViewController). (Confused ;-D )

Everything shows up on the screen and and the timer is started correctly. The variable f.hunger updates and shows the correct value (when using printf("%f", f.hunger) ) but the UIProgress bar doesn't update itself. f.hunger's starting value is 1.

If anyone can help me, point out where I've made an obvious mistake or got a suggestion it would be most appreciated as it's been doing my head in for a good few hours now. I've added some sample code below to show what I'm doing a bit more clearly.

Cheers everyone. :-D

Timers Class

- (void)startHungerTimer
{
 if(hungerTimer.isValid == NO)
 {
  infoVC = [[InfoViewController alloc] init];
  self.hungerTimer = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self     selector:@selector(incrementHungerTimer:) userInfo:nil repeats:YES];
 }
}

- (void)incrementHungerTimer:(NSTimer *)aTimer
{
    f.hunger -= 0.01;
    [infoVC updateHungerProgress];
}

Info View Controller

- (void)updateHungerProgress
{
 Functions *f = [Functions sharedFunctions];
 hungerBar.progress = f.hunger;
}

- (void)loadView
{
    hungerBar = [[UIProgressView alloc] initWithProgressViewStyle:UIProgressViewStyleDefault];
    [hungerBar setFrame:CGRectMake(17.0, 30.0, 160.0, 10.0)];
    hungerBar.progress = f.hunger;
    [bView addSubview:hungerBar];
    [hungerBar release];
}


问:
Is it possible to store a list of ids as an attribute for an object in rails?
I'm trying to implement a voting system where users can upvote/downvote links posted by other users. A user can only vote on a link once, so before I execute upvote or downvote I need to check if the user has already voted and if they had already voted, wheather they upvoted or downvoted, so that I can disable the button for the other.

There are a few ways to do this. The most immediate solution that comes to me is to have two additional columns in the link model, one to store a list of ids of users that upvoted and the other to store a list of ids of users that downvoted.

Two concerns arise in my mind. One, is this even considered a good practice (in terms of database efficiency) and if it is the best way to do it, how do I store a list of ids as an attribute for the model? What would be the data type I need to enter for the migration?

答:
Is it possible to store a list of ids as an attribute for an object in rails?

Yes, it possible. One way is using Array datatype as

```<code>def change
  add_column :links, :upvote_user_ids, :array, :default => []
end
</code>```

is this even considered a good practice (in terms of database efficiency)

No, it is not at all recommended. Over the period of time the list will explode degrading your system thoroughly..

Consider acts_as_votable gem, this solves your query elegantly..

Body:
Is it possible to store a list of ids as an attribute for an object in rails?

Yes, it possible. One way is using Array datatype as

def change
  add_column :links, :upvote_user_ids, :array, :default => []
end

is this even considered a good practice (in terms of database efficiency)

No, it is not at all recommended. Over the period of time the list will explode degrading your system thoroughly..

Consider acts_as_votable gem, this solves your query elegantly..


问:
Authenticating ldap user with multiple suffix value/domain
I am trying to authenticate and then query AD tree using Spring Ldap Security and Spring Ldap.

Following is my configuration file -

```<code><?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:ldap="http://www.springframework.org/schema/ldap"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.2.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/ldap
        http://www.springframework.org/schema/ldap/spring-ldap.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">

    <http use-expressions="true">
        <form-login login-page="/myApp/ldap" default-target-url="/myApp/ldap/config"
            authentication-failure-url="/myApp/ldap?error=true" />
        <logout />
    </http>

    <beans:bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location">
            <beans:value>classpath:/ldap.properties</beans:value>
        </beans:property>
        <beans:property name="SystemPropertiesMode">
            <beans:value>2</beans:value>
        </beans:property>
    </beans:bean>

    <beans:bean id="adAuthenticationProvider" scope="prototype"
        class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">
        <!-- the domain name (may be null or empty). If no domain name is configured, it is assumed that the username will always contain the domain name. -->
        <beans:constructor-arg index="0" value="${sample.ldap.domain}" />
        <!-- an LDAP url (or multiple URLs) -->
        <beans:constructor-arg index="1" value="${sample.ldap.url}" />
        <!-- Determines whether the supplied password will be used as the credentials in the successful authentication token. -->
        <beans:property name="useAuthenticationRequestCredentials"
            value="true" />
        <!-- by setting this property to true, when the authentication fails the error codes will also be used to control the exception raised. -->
        <beans:property name="convertSubErrorCodesToExceptions"
            value="true" />
    </beans:bean>

    <authentication-manager erase-credentials="false">
        <authentication-provider ref="adAuthenticationProvider" />
    </authentication-manager>

    <beans:bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location">
            <beans:value>classpath:/ldap.properties</beans:value>
        </beans:property>
        <beans:property name="SystemPropertiesMode">
            <beans:value>2</beans:value> <!-- OVERRIDE is 2 -->
        </beans:property>
    </beans:bean>

    <ldap:context-source id="contextSource"
                         url="${sample.ldap.url}"
                         base="${sample.ldap.base}"
                         referral="follow"
                         authentication-source-ref="authenticationSource"
                         base-env-props-ref="baseEnvironmentProperties"/>

    <util:map id="baseEnvironmentProperties">
        <beans:entry key="com.sun.jndi.ldap.connect.timeout" value="60000" />
        <beans:entry key="java.naming.ldap.attributes.binary" value="objectGUID objectSid"/>
    </util:map>

    <beans:bean id="authenticationSource"
        class="org.springframework.security.ldap.authentication.SpringSecurityAuthenticationSource" />

    <ldap:ldap-template id="ldapTemplate"
        context-source-ref="contextSource" />

</beans:beans>
</code>```

And property file is -

```<code>sample.ldap.url=ldap://xxx.xxx.xxx.xxx:3268
sample.ldap.base=dc=example,dc=com
sample.ldap.clean=true
sample.ldap.directory.type=AD
sample.ldap.domain=example.com
</code>```

These setting works fine for following login -

username - example@example.com or example
Password - blah

but fails when i try -
username - example2@example.net or example
Password - blah2

These both are valid logins, and have been validated by login using AD Explorer.

Seems like i need to update my configuration to support UPN suffix/domains as default works fine and other do not.

Is there a way i can append to this config file to support this logic, supporting authenticating/querying multiple domains?

答:
To explain @NewBee's solution:

1 ActiveDirectoryLdapAuthenticationProvider:

Specialized LDAP authentication provider which uses Active Directory configuration conventions.

It will authenticate using the Active Directory userPrincipalName or sAMAccountName (or a custom searchFilter) in the form username@domain. If the username does not already end with the domain name, the userPrincipalName will be built by appending the configured domain name to the username supplied in the authentication request. If no domain name is configured, it is assumed that the username will always contain the domain name.

The user authorities are obtained from the data contained in the memberOf attribute.

2 LDAP authentication in Spring Security:

Obtaining the unique LDAP Distinguished Name, or DN, from the login name.

This will often mean performing a search in the directory, unless the exact mapping of usernames to DNs is known in advance. So a user might enter his/her name when logging in, but the actual name used to authenticate to LDAP will be the full DN, such as uid=(username),ou=users,dc=springsource,dc=com.

Authenticating the user, either by binding as that user or by performing a remote compare operation of the user's password against the password attribute in the directory entry for the DN.

Loading the list of authorities for the user.

For a reference to How to configure multiple UPN Suffixes. Plus in ActiveDirectoryLdapAuthenticationProvider you could write a function for reading multiple suffixes, as the library is adaptable.

Body:
I am trying to authenticate and then query AD tree using Spring Ldap Security and Spring Ldap.

Following is my configuration file -

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/security"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:beans="http://www.springframework.org/schema/beans"
    xmlns:ldap="http://www.springframework.org/schema/ldap"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/security
        http://www.springframework.org/schema/security/spring-security-3.2.xsd
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/ldap
        http://www.springframework.org/schema/ldap/spring-ldap.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util.xsd">

    <http use-expressions="true">
        <form-login login-page="/myApp/ldap" default-target-url="/myApp/ldap/config"
            authentication-failure-url="/myApp/ldap?error=true" />
        <logout />
    </http>

    <beans:bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location">
            <beans:value>classpath:/ldap.properties</beans:value>
        </beans:property>
        <beans:property name="SystemPropertiesMode">
            <beans:value>2</beans:value>
        </beans:property>
    </beans:bean>

    <beans:bean id="adAuthenticationProvider" scope="prototype"
        class="org.springframework.security.ldap.authentication.ad.ActiveDirectoryLdapAuthenticationProvider">

        <beans:constructor-arg index="0" value="${sample.ldap.domain}" />

        <beans:constructor-arg index="1" value="${sample.ldap.url}" />

        <beans:property name="useAuthenticationRequestCredentials"
            value="true" />

        <beans:property name="convertSubErrorCodesToExceptions"
            value="true" />
    </beans:bean>

    <authentication-manager erase-credentials="false">
        <authentication-provider ref="adAuthenticationProvider" />
    </authentication-manager>

    <beans:bean
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <beans:property name="location">
            <beans:value>classpath:/ldap.properties</beans:value>
        </beans:property>
        <beans:property name="SystemPropertiesMode">
            <beans:value>2</beans:value>
        </beans:property>
    </beans:bean>

    <ldap:context-source id="contextSource"
                         url="${sample.ldap.url}"
                         base="${sample.ldap.base}"
                         referral="follow"
                         authentication-source-ref="authenticationSource"
                         base-env-props-ref="baseEnvironmentProperties"/>

    <util:map id="baseEnvironmentProperties">
        <beans:entry key="com.sun.jndi.ldap.connect.timeout" value="60000" />
        <beans:entry key="java.naming.ldap.attributes.binary" value="objectGUID objectSid"/>
    </util:map>

    <beans:bean id="authenticationSource"
        class="org.springframework.security.ldap.authentication.SpringSecurityAuthenticationSource" />

    <ldap:ldap-template id="ldapTemplate"
        context-source-ref="contextSource" />

</beans:beans>

And property file is -

sample.ldap.url=ldap://xxx.xxx.xxx.xxx:3268
sample.ldap.base=dc=example,dc=com
sample.ldap.clean=true
sample.ldap.directory.type=AD
sample.ldap.domain=example.com

These setting works fine for following login -

username - example@example.com or example
Password - blah

but fails when i try -
username - example2@example.net or example
Password - blah2

These both are valid logins, and have been validated by login using AD Explorer.

Seems like i need to update my configuration to support UPN suffix/domains as default works fine and other do not.

Is there a way i can append to this config file to support this logic, supporting authenticating/querying multiple domains?


问:
Replace the string with correct word in python
This is my string, for which I have split the string to words

data is the collection of correct words

sentence is the string which contains some incorrect words which needs to be replaced with the corrected once

```<code>data="blue whale","red rose","city of joy","dream pride","rain drops","ten house","think twice"
data=[words for segments in data for words in segments.split()]

sentence = ["I'll have to thnik twycee before going to ceety of joiy along with red rossy"]
sentence = sentence.split()
</code>```

now I'm trying to spell check

```<code> def words(text): return re.findall(r'\w+', text.lower())
    WORDS = Counter(data)

    def P(word, N=sum(WORDS.values())):
        "Probability of `word`."
        return WORDS[word] / N

    def correction(word):
        "Most probable spelling correction for word."
        return max(candidates(word), key=P)

    def candidates(word):
        "Generate possible spelling corrections for word."
        return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

    def known(words):
        "The subset of `words` that appear in the dictionary of WORDS."
        return set(w for w in words if w in WORDS)

    def edits1(word):
        "All edits that are one edit away from `word`."
        letters    = 'abcdefghijklmnopqrstuvwxyz'
        splits     = [(word[:i], word[i:])    for i in range(len(word) + 1)]
        deletes    = [L + R[1:]               for L, R in splits if R]
        transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
        replaces   = [L + c + R[1:]           for L, R in splits if R for c in letters]
        inserts    = [L + c + R               for L, R in splits for c in letters]
        return set(deletes + transposes + replaces + inserts)

    def edits2(word):
        "All edits that are two edits away from `word`."
        return (e2 for e1 in edits1(word) for e2 in edits1(e1))
</code>```

Now what I want to do is that I want to replace all the incorrect words with the corrected words and update in the object sentence

correction('thnik')

O/P

think

code for updating the object "sentence"

```<code>for i  in sentence:
        sentence = correction(i)
        sentence = [sentence.append(i)]
        print(sentence)
</code>```

as the program would check for all given words and would output the result, I would join them all using sentence = ' '.join(sentence)
but the for loop code gives my error "AttributeError: 'str' object has no attribute 'append'", any help would be much appreciated. Thanks

答:
```<code>sentence = "Thsi is my cdoe"   #Lets assume this is your sentence.
formatted_sentence = ''
for i  in sentence:
    corrected_word = correction(i) # if "Thsi" is passed to correction it should return "This"
    formatted_sentence += ' '.join(corrected_word)
print(formatted_sentence)
</code>```

Body:
This is my string, for which I have split the string to words

data is the collection of correct words

sentence is the string which contains some incorrect words which needs to be replaced with the corrected once

data="blue whale","red rose","city of joy","dream pride","rain drops","ten house","think twice"
data=[words for segments in data for words in segments.split()]

sentence = ["I'll have to thnik twycee before going to ceety of joiy along with red rossy"]
sentence = sentence.split()

now I'm trying to spell check

 def words(text): return re.findall(r'\w+', text.lower())
    WORDS = Counter(data)

    def P(word, N=sum(WORDS.values())):
        "Probability of `word`."
        return WORDS[word] / N

    def correction(word):
        "Most probable spelling correction for word."
        return max(candidates(word), key=P)

    def candidates(word):
        "Generate possible spelling corrections for word."
        return (known([word]) or known(edits1(word)) or known(edits2(word)) or [word])

    def known(words):
        "The subset of `words` that appear in the dictionary of WORDS."
        return set(w for w in words if w in WORDS)

    def edits1(word):
        "All edits that are one edit away from `word`."
        letters    = 'abcdefghijklmnopqrstuvwxyz'
        splits     = [(word[:i], word[i:])    for i in range(len(word) + 1)]
        deletes    = [L + R[1:]               for L, R in splits if R]
        transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R)>1]
        replaces   = [L + c + R[1:]           for L, R in splits if R for c in letters]
        inserts    = [L + c + R               for L, R in splits for c in letters]
        return set(deletes + transposes + replaces + inserts)

    def edits2(word):
        "All edits that are two edits away from `word`."
        return (e2 for e1 in edits1(word) for e2 in edits1(e1))

Now what I want to do is that I want to replace all the incorrect words with the corrected words and update in the object sentence

correction('thnik')

O/P

think

code for updating the object "sentence"

for i  in sentence:
        sentence = correction(i)
        sentence = [sentence.append(i)]
        print(sentence)

as the program would check for all given words and would output the result, I would join them all using sentence = ' '.join(sentence)
but the for loop code gives my error "AttributeError: 'str' object has no attribute 'append'", any help would be much appreciated. Thanks


问:
Access Location on an Android IOT device
I have an Android IoT device running Android 5.1.1 on Rockchip RK3288 that as name implies can connect to a WiFi network but doesn't have a GPS or a Cellular module. Whenever I try to access location and find the best location provider it always return me as a 'Passive' provider and hence i have no way of getting my current location.

```<code>Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
</code>```

I am a bit perplexed that the device has an active network connection but NETWORK_PROVIDER isn't available.

答:
Try Google Geolocation API.

Google Geolocation API use wifiAccessPoints and  cellTowers too. As you said device don't have GPS and Cellular module you need to use WifiAccessPoints for it.

For WifiAccessPoints you need to pass all your nearest wifi connection data. For E.g In android when click on WIFI it shows list of wifi near to you. So, you need to just pass all that wifi list to WifiAccessPoints so it returns the location of your device.

You can Pass Parameter "considerIp": "true" so using your Ip Address it get the current location of your device.

For My Opinion use Get Current location through IP Address which return the Highest Accuracy ratio for current location.This is also said by the Google Maps Geolocation API document.

For more information you can refer Google Geolocation API which also provide sample data so that you can check the result from here.

I hope this will give you some hint or get some idea to actually you want to achieve.

Body:
I have an Android IoT device running Android 5.1.1 on Rockchip RK3288 that as name implies can connect to a WiFi network but doesn't have a GPS or a Cellular module. Whenever I try to access location and find the best location provider it always return me as a 'Passive' provider and hence i have no way of getting my current location.

Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);

I am a bit perplexed that the device has an active network connection but NETWORK_PROVIDER isn't available.


问:
Android volley StringRequest POST method failed to pass params
I am currently trying to access my database using CodeIgniter. But I am not able to pass parameters from my StringRequest method. It said:

Message:  Undefined index: email

Here is my php code:

```<code>public function index() {
    echo $_POST['email'];
}
</code>```

Here is my StringRequest:

```<code>StringRequest request = new StringRequest(Request.Method.POST, SEND_REQUEST_URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                System.out.println(response);
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.d("Volley Error", error.getMessage());
    }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/x-www-form-urlencoded; charset=UTF-8";
        }

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("email", "test@test.com");
            return params;
        }
        };
        AppController.getInstance().addToRequestQueue(request);
</code>```

I have also tried to add:

```<code>@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String,String> params = new HashMap<String, String>();
    params.put("Content-Type","application/x-www-form-urlencoded");
    return params;
}
</code>```

Notes:

I know there is 'bug' in passing parameters using jsonrequest so I use stringrequest instead.

I have override the getBodyContentType method.

It doesn't need authorization.

It works fine when I test it with Postman.

Another thing to be noted:
It works if I hit the url to a single plain php file to echo the POST value. But it just can't get into the php files in my codeIgniter.

UPDATES:
I found out that although i used POST method from my android apps, somehow codeigniter takes it as a GET method. I know this using

$_SERVER['REQUEST_METHOD']

答:
```<code>        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

        StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                System.out.println(response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String, String> params = new HashMap<String, String>();
                params.put("email", "test@test.com");
                return params;
            }
        };

        requestQueue.add(request);
</code>```

I hope this post can help you

Body:
I am currently trying to access my database using CodeIgniter. But I am not able to pass parameters from my StringRequest method. It said:

Message:  Undefined index: email

Here is my php code:

public function index() {
    echo $_POST['email'];
}

Here is my StringRequest:

StringRequest request = new StringRequest(Request.Method.POST, SEND_REQUEST_URL,
        new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                System.out.println(response);
            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.d("Volley Error", error.getMessage());
    }
    }) {
        @Override
        public String getBodyContentType() {
            return "application/x-www-form-urlencoded; charset=UTF-8";
        }

        @Override
        protected Map<String, String> getParams() {
            Map<String, String> params = new HashMap<String, String>();
            params.put("email", "test@test.com");
            return params;
        }
        };
        AppController.getInstance().addToRequestQueue(request);

I have also tried to add:

@Override
public Map<String, String> getHeaders() throws AuthFailureError {
    Map<String,String> params = new HashMap<String, String>();
    params.put("Content-Type","application/x-www-form-urlencoded");
    return params;
}

Notes:

I know there is 'bug' in passing parameters using jsonrequest so I use stringrequest instead.

I have override the getBodyContentType method.

It doesn't need authorization.

It works fine when I test it with Postman.

Another thing to be noted:
It works if I hit the url to a single plain php file to echo the POST value. But it just can't get into the php files in my codeIgniter.

UPDATES:
I found out that although i used POST method from my android apps, somehow codeigniter takes it as a GET method. I know this using

$_SERVER['REQUEST_METHOD']

Body:
        RequestQueue requestQueue = Volley.newRequestQueue(getApplicationContext());

        StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {

                System.out.println(response.toString());
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {

                Map<String, String> params = new HashMap<String, String>();
                params.put("email", "test@test.com");
                return params;
            }
        };

        requestQueue.add(request);

I hope this post can help you


问:
Deleting duplicate strings in array
At one point it compares array(1)compareto(array(1)) is this a problem? Amount birds is the amount of elements in array. I am trying to remove duplicate string in the array. Is it fixable or should i re approach.</p>

```<code>for (i = 0; i <= amountBirds - 1; i++)
{
    for (x = 1; x <= amountBirds; x++)
    {
        duplicate = birdArray[i].compareTo(birdArray[x]);

        if (duplicate == 0)
        {
            birdArray[i] = birdArray[x];
        }
    }
}
</code>```

答:
Either you can include a if check before using compareTo method

```<code>if ( i != x ) {
        duplicate = birdArray[i].compareTo(birdArray[x]);
}
</code>```

Or you can use Set in Java Collection library. This approach does not allow duplicate entries to be inserted. So at the time of insertion itself, you can avoid the duplicates.

Or you keep the birdArray as it is. And use a Set as a mediator to insert and remove the duplicates.

```<code>Set<String> birdSet = new LinkedHashSet<String>(); //to keep the order of the birds
for (i = 0; i < amountBirds; i++)
{
    birdSet.add (birdArray[i]);
}
birdArray = Arrays.copyOf(birdSet.toArray(), birdSet.size(), String[].class);
</code>```

Title: Deleting duplicate strings in array

Body:
At one point it compares array(1)compareto(array(1)) is this a problem? Amount birds is the amount of elements in array. I am trying to remove duplicate string in the array. Is it fixable or should i re approach.

for (i = 0; i <= amountBirds - 1; i++)
{
    for (x = 1; x <= amountBirds; x++)
    {
        duplicate = birdArray[i].compareTo(birdArray[x]);

        if (duplicate == 0)
        {
            birdArray[i] = birdArray[x];
        }
    }
}

Body:
Either you can include a if check before using compareTo method

if ( i != x ) {
        duplicate = birdArray[i].compareTo(birdArray[x]);
}

Or you can use Set in Java Collection library. This approach does not allow duplicate entries to be inserted. So at the time of insertion itself, you can avoid the duplicates.

Or you keep the birdArray as it is. And use a Set as a mediator to insert and remove the duplicates.

Set<String> birdSet = new LinkedHashSet<String>(); //to keep the order of the birds
for (i = 0; i < amountBirds; i++)
{
    birdSet.add (birdArray[i]);
}
birdArray = Arrays.copyOf(birdSet.toArray(), birdSet.size(), String[].class);


问:
hbase shell command to get all row keys with regex
How can I get all the values for keys having regex in hbase shell

for instance, I have something like
Row key               Column
1,2017-05-06          't1:5'
1,2017-05-07          't2:6'

Now I want something like all the column families for Row key '1,*' where * is denoted by all days. Is it possible?

答:
You can try something like this :

```<code>scan ‘myTable’, {FILTER => “(PrefixFilter (‘1,’)”}
</code>```

Source : HBase documentation suggestion https://learnhbase.wordpress.com/2013/03/02/hbase-shell-commands/

Body:
You can try something like this :

scan ‘myTable’, {FILTER => “(PrefixFilter (‘1,’)”}

Source : HBase documentation suggestion https://learnhbase.wordpress.com/2013/03/02/hbase-shell-commands/


问:
Change custom fields of Identity User
Hey I added Teams to my ApplicationUser like this:

```<code>public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here

        return userIdentity;
    }

    public virtual ICollection<Function> Functions { get; set; }
    public virtual ICollection<Participation> Participations { get; set; }
    public virtual ICollection<Team> Teams { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Mobile { get; set; }
    public DateTime Birthdate { get; set; }
}
</code>```

In my Controller I want to add a new Team for the user:

```<code>ApplicationUser user = UserManager.GetUserById(dto.PersonId[0]);
if (user != null)
{
    if (user.Teams == null)
    {
        user.Teams = new List<Team>();
    }
    user.Teams.Add(mannschaft);
    mannschaft.UsersId.Add(user?.Id);
    uow.SaveChanges();
    Team team = uow.RepTeam.Get(t => t.Bezeichnung == dto.Name).FirstOrDefault();
    return Request.CreateResponse(HttpStatusCode.Created, team?.Id);
}
</code>```

So theres no problem the team got added to the IdentityUser but when I want to call all teams in a different Controller like this:

```<code>ApplicationUser user = UserManager.GetUserById(userid);
ICollection<DtoTeam> foo = new List<DtoTeam>();
if (user != null)
{
    foreach (var teams in user.Teams)
    {
        foo.Add(uow.RepTeam.GetByKey(teams).ToDto());
    }
}
return foo;
</code>```

It says that there are no teams in the user...

答:
IMO , you still can use your table and remove the autogenerate table like Aspnet..Table or whatever

and if you want to save your data you can change path like identityUser to your table using OnmodelCreating()

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<IdentityUser>().ToTable("your_table_name");
    }
</code>```

any advance you can search google

Title: Change custom fields of Identity User

Body:
Hey I added Teams to my ApplicationUser like this:

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
        // Add custom user claims here

        return userIdentity;
    }

    public virtual ICollection<Function> Functions { get; set; }
    public virtual ICollection<Participation> Participations { get; set; }
    public virtual ICollection<Team> Teams { get; set; }
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Mobile { get; set; }
    public DateTime Birthdate { get; set; }
}

In my Controller I want to add a new Team for the user:

ApplicationUser user = UserManager.GetUserById(dto.PersonId[0]);
if (user != null)
{
    if (user.Teams == null)
    {
        user.Teams = new List<Team>();
    }
    user.Teams.Add(mannschaft);
    mannschaft.UsersId.Add(user?.Id);
    uow.SaveChanges();
    Team team = uow.RepTeam.Get(t => t.Bezeichnung == dto.Name).FirstOrDefault();
    return Request.CreateResponse(HttpStatusCode.Created, team?.Id);
}

So theres no problem the team got added to the IdentityUser but when I want to call all teams in a different Controller like this:

ApplicationUser user = UserManager.GetUserById(userid);
ICollection<DtoTeam> foo = new List<DtoTeam>();
if (user != null)
{
    foreach (var teams in user.Teams)
    {
        foo.Add(uow.RepTeam.GetByKey(teams).ToDto());
    }
}
return foo;

It says that there are no teams in the user...

Body:
IMO , you still can use your table and remove the autogenerate table like Aspnet..Table or whatever

and if you want to save your data you can change path like identityUser to your table using OnmodelCreating()

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<IdentityUser>().ToTable("your_table_name");
    }

any advance you can search google


问:
How costly is .NET reflection?
I constantly hear how bad reflection is to use. While I generally avoid reflection and rarely find situations where it is impossible to solve my problem without it, I was wondering...

For those who have used reflection in applications, have you measured performance hits and, is it really so bad?

答:
Reflection performance will depend on the implementation (repetitive calls should be cached eg: entity.GetType().GetProperty("PropName")). Since most of the reflection I see on a day to day basis is used to populate entities from data readers or other repository type structures I decided to benchmark performance specifically on reflection when it is used to get or set an objects properties.

I devised a test which I think is fair since it caches all the repeating calls and only times the actual SetValue or GetValue call. All the source code for the performance test is in bitbucket at: https://bitbucket.org/grenade/accessortest. Scrutiny is welcome and encouraged.

The conclusion I have come to is that it isn't practical and doesn't provide noticeable performance improvements to remove reflection in a data access layer that is returning less than 100,000 rows at a time when the reflection implementation is done well.

The graph above demonstrates the output of my little benchmark and shows that mechanisms that outperform reflection, only do so noticeably after the 100,000 cycles mark. Most DALs only return several hundred or perhaps thousands of rows at a time and at these levels reflection performs just fine.

OwnerDisplayName: Dan

Title: How costly is .NET reflection?


问:
Why is it impossible to mix Python2 with Python3?
Despite all that has been said and written on Python2 vs Python3, I have been unable to identify why the developers made it impossible to mix Python2 and Python3 code. Surely there must be a reason for this?

In Fortran, for instance, the many versions are incompatible with each other, but they can still happily co-exist within the same project. The same applies to C and C++: some C code is not compatible with C++, but the compiler is able to recognize the correct language using the file extension. Is there a specific reason for why this approach was not chosen for Python3? That is, let Python3 modules be identified by a .py3 extension (or a shebang comment), and use one single interpreter for both .py and .py3 code?

EDIT:

There is already a question named Why is Python 3 not backwards compatible? , but this question is different. I know that Python 3 introduces new features and breaks backwards compatibility because of this. It still does not mean that Python 2 and 3 cannot coexist the same way C and C++ can.

答:
You can't mix python2 and python3 in the same project, because:

The interpreters are different. You're either running an interpreter for python2, or for python3.  I don't know of any current interpreter that dynamically chooses the python2 or python3 runtime.

The syntax is (slightly) different.

The types are different.

However, you could certainly run both the python2 and python3 runtimes and use some sort of (IPC) message passing between them.

With the case of C, and C++, you can run them in the same process, so that's fine.  Incidentially, you can run python and C (or C++) in the same process, too.

The only way I can think of that would allow you to run python2 and python3 in the same process would be to embed both runtimes in the same process, however, they will very likely clobber each other's globals and get confused.