问:
how to add complementary intervals in pandas dataframe
Lets say that I have a signal of 100 samples L=100

In this signal I found some intervals that I label as "OK". The intervals are stored in a Pandas DataFrame that looks like this:

```<code>c = pd.DataFrame(np.array([[10,26],[50,84]]),columns=['Start','End'])
c['Value']='OK'
</code>```

How can I add the complementary intervals in another dataframe in order to have something like this

```<code> d = pd.DataFrame(np.array([[0,9],[10,26],[27,49],[50,84],[85,100]]),columns=['Start','End'])
 d['Value']=['Check','OK','Check','OK','Check']
</code>```

答:
You can use the first Dataframe to create the second one and merge like suggested @jezrael :

```<code>d = pd.DataFrame({"Start":[0] + sorted(pd.concat([c.Start , c.End+1])), "End": sorted(pd.concat([c.Start-1 , c.End]))+[100]} )
d = pd.merge(d, c, how='left')
d['Value'] = d['Value'].fillna('Check')
d = d.reindex_axis(["Start","End","Value"], axis=1)
</code>```

output

```<code>    Start   End Value
0   0       9   Check
1   10     26   OK
2   27     49   Check
3   50     84   OK
4   85    100   Check
</code>```

Body:
Lets say that I have a signal of 100 samples L=100

In this signal I found some intervals that I label as "OK". The intervals are stored in a Pandas DataFrame that looks like this:

c = pd.DataFrame(np.array([[10,26],[50,84]]),columns=['Start','End'])
c['Value']='OK'

How can I add the complementary intervals in another dataframe in order to have something like this

 d = pd.DataFrame(np.array([[0,9],[10,26],[27,49],[50,84],[85,100]]),columns=['Start','End'])
 d['Value']=['Check','OK','Check','OK','Check']

Body:
You can use the first Dataframe to create the second one and merge like suggested @jezrael :

d = pd.DataFrame({"Start":[0] + sorted(pd.concat([c.Start , c.End+1])), "End": sorted(pd.concat([c.Start-1 , c.End]))+[100]} )
d = pd.merge(d, c, how='left')
d['Value'] = d['Value'].fillna('Check')
d = d.reindex_axis(["Start","End","Value"], axis=1)

output

    Start   End Value
0   0       9   Check
1   10     26   OK
2   27     49   Check
3   50     84   OK
4   85    100   Check


来源: stackexchange

问:
Silently update mobile iron app
I have no experience with mobile iron but we are looking into possibilities of mobile iron updating our enterprise app without asking users to update it. Any related information is much appreciated. Thanks.</p>

答: You can use "Send Message" Command(MobileIron Admin portal->App distribution page->Select the Enterpise App->Actions->Send Message)to push silent instal/updates of Apps.</p>

ContentLicense: CC BY-SA 3.0

Title: Silently update mobile iron app


问:
how can i achieve FibonacciSecret in php
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

```<code><?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>
</code>```

Output

```<code>h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-
</code>```

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

答:
Your Fibonacci series generation code was not correct, Try this:

Update:

This code will stop once it sum goes out of the range of message length.

```<code>$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';

// remove all the spaces from message
$message = str_replace(' ', '', $message);
$str_split = str_split($message);

$x = 0;
$y = 1;
$next = 0;

//stopping the loop if the character index goes out of range
for($i=1;$next<=count($str_split);$i++)
{
    if($i == 1) //for first element use 0 as the sum
    {
        $farray[] = $x;
        continue;
    }
if($i == 2) //for second element use 1 as the sum
{
     $farray[] = $y;
    continue;
}

$next = $x + $y;
$x=$y;
$y=$next;

$farray[] = $next;
}

foreach($farray as $key=>$fvalue){
   echo $str_split[$fvalue]."--";
}
</code>```

Original Answer:-

It Works:-

```<code>$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';

// remove all the spaces from message
$message = str_replace(' ', '', $message);
$str_split = str_split($message);

$x = 0;
$y = 1;
$next = 0;

for($i=1;$i<=10;$i++)
{
    if($i == 1) //for first element use 0 as the sum
    {
        $farray[] = $x;
        continue;
    }

    if($i == 2) //for second element use 1 as the sum
    {
         $farray[] = $y;
        continue;
    }

    $next = $x + $y;
    $x=$y;
    $y=$next;

    $farray[] = $next;
}

foreach($farray as $key=>$fvalue){
   echo $str_split[$fvalue]."--";
}
</code>```

Body:
I'm trying to get all the characters in that message at positions that are present in the Fibonacci sequence (a sequence formed by the the Fibonacci number sorted in ascending order). Please ignore whitespace characters and use the extended Fibonacci.

Return the obtained characters capitalized and connected by the '-' character.

Example

For message = "The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown",

the output should be

FibonacciSecret(message) = "T-H-H-E-D-V-C-E-M-T".

The first Fibonacci is 0 then the first letter is T

The second Fibonacci is 1 then the second letter is H

The third Fibonacci is 1 then the third letter is H ... and so on.

Thus, the answer should be "T-H-H-E-D-V-C-E-M-T".

Tried Code

<?php
$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';
$str_split = str_split($message);

$x = 0;
$y = 1;

for($i=0;$i<=10;$i++)
{
    $z = $x + $y;
    $farray[] = $z;
    $x=$y;
    $y=$z;
}

foreach($farray as $key=>$fvalue){
       echo $str_split[$fvalue]."-";
}

?>

Output

h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-h-h-T-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-
E_NOTICE : type 8 -- Undefined offset: -1 -- at line 18
-T-

Expected Output

the answer should be "T-H-H-E-D-V-C-E-M-T".

Can anyone tell me. Where im going wrong in this one ?

Body:
Your Fibonacci series generation code was not correct, Try this:

Update:

This code will stop once it sum goes out of the range of message length.

$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';

// remove all the spaces from message
$message = str_replace(' ', '', $message);
$str_split = str_split($message);

$x = 0;
$y = 1;
$next = 0;

//stopping the loop if the character index goes out of range
for($i=1;$next<=count($str_split);$i++)
{
    if($i == 1) //for first element use 0 as the sum
    {
        $farray[] = $x;
        continue;
    }
if($i == 2) //for second element use 1 as the sum
{
     $farray[] = $y;
    continue;
}

$next = $x + $y;
$x=$y;
$y=$next;

$farray[] = $next;
}

foreach($farray as $key=>$fvalue){
   echo $str_split[$fvalue]."--";
}

Original Answer:-

It Works:-

$message = 'The Da Vinci Code is a 2003 mystery-detective novel by Dan Brown';

// remove all the spaces from message
$message = str_replace(' ', '', $message);
$str_split = str_split($message);

$x = 0;
$y = 1;
$next = 0;

for($i=1;$i<=10;$i++)
{
    if($i == 1) //for first element use 0 as the sum
    {
        $farray[] = $x;
        continue;
    }

    if($i == 2) //for second element use 1 as the sum
    {
         $farray[] = $y;
        continue;
    }

    $next = $x + $y;
    $x=$y;
    $y=$next;

    $farray[] = $next;
}

foreach($farray as $key=>$fvalue){
   echo $str_split[$fvalue]."--";
}


问:
Auto-implemented property in VB.NET with a protected setter?
So far I had a read-only property in VB.NET as

```<code>Public ReadOnly Property Username() As String
</code>```

Now I need to make changes to my code as the setter to this property needs to be protected. In C# I would have done:

```<code>public string Username {get; protected set;}
</code>```

But I can't find such a short hand and good-looking solution in VB.NET. Does VB.NET provide that and I am unaware of this? Or do I have to write so much code and make it look little uglier?

```<code>Public Property Username() As String
    Get
        Return m_Username
    End Get
    Protected Set
        m_Username = Value
    End Set
End Property
Private m_Username As String
</code>```

It's going to make my class so dirty if I had 20 properties and set them like this.

答: Unfortunately, there is no such shorthand syntax in VB.  Also see: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/auto-implemented-properties</p>

Body:
So far I had a read-only property in VB.NET as

Public ReadOnly Property Username() As String

Now I need to make changes to my code as the setter to this property needs to be protected. In C# I would have done:

public string Username {get; protected set;}

But I can't find such a short hand and good-looking solution in VB.NET. Does VB.NET provide that and I am unaware of this? Or do I have to write so much code and make it look little uglier?

Public Property Username() As String
    Get
        Return m_Username
    End Get
    Protected Set
        m_Username = Value
    End Set
End Property
Private m_Username As String

It's going to make my class so dirty if I had 20 properties and set them like this.


问:
Eclipse: Error starting static Resources java.lang.IllegalArgumentException
I have a project called myproject2 in my Eclipse IDE. I have a Tomcat application server and I can add there the resource myproject2 (it is a Spring MVC project).

Now I closed the myproject2 in Eclipse, removed myproject2 from the Tomcat resources and do a fresh Subversion checkout with projectname: myproject3.

REstarting the IDE I want to set myproject3 to the Tomcat server so this should be deployed. But all what is available is myproject2 to choose. So I choose it. I can access http://localhost:8080/myproject2/ but I get this warning and serve in the console:

```<code>14.12.2010 11:43:11 org.apache.catalina.startup.HostConfig deployDescriptor
WARNING: A docBase C:\Spring\apache-tomcat-6.0.29-windows-x86\apache-tomcat-6.0.29\webapps\myproject2 inside the host appBase has been specified, and will be ignored
14.12.2010 11:43:11 org.apache.catalina.core.StandardContext resourcesStart
SERVE: Error starting static Resources
java.lang.IllegalArgumentException: Document base C:\Spring\apache-tomcat-6.0.29-windows-x86\apache-tomcat-6.0.29\webapps\myproject3 does not exist or is not a readable directory
at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:142)
at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4249)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4418)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:546)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:637)
at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:563)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:498)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1277)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:321)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:445)
at org.apache.catalina.core.StandardService.start(StandardService.java:519)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
14.12.2010 11:43:11 org.apache.catalina.core.StandardContext start
SERVE: Error in resourceStart()
14.12.2010 11:43:11 org.apache.catalina.core.StandardContext start
SERVE: Error getConfigured
14.12.2010 11:43:11 org.apache.catalina.core.StandardContext start
SERVE: Context [/myproject3] startup failed due to previous errors
14.12.2010 11:43:11 org.apache.catalina.core.StandardContext stop
INFO: Container org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/myproject3] has not been started
</code>```

So what's wrong here? Why don't I have a myproject3 to choose what should be deployed in Tomcat?

Does anyone know?

Best Regards.

Update:

.project (myproject2):

```<code><projectDescription>
    <name>myproject</name>
    <comment>My-Project. NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse.</comment>
    <projects/>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.jdt.core.javanature</nature>
    </natures>
</projectDescription>
</code>```

.project (myproject3)

```<code><?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>myproject</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.wst.common.project.facet.core.builder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.wst.validation.validationbuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.maven.ide.eclipse.maven2Builder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
         <nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
         <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
         <nature>org.maven.ide.eclipse.maven2Nature</nature>
         <nature>org.eclipse.jdt.core.javanature</nature>
         <nature>org.eclipse.wst.common.project.facet.core.nature</nature>
         <nature>org.eclipse.wst.jsdt.core.jsNature</nature>
    </natures>
</projectDescription>
</code>```

答:
Are you using the Eclipse WTP and Tomcat-server integration to deploy your app, or are you creating a WAR and deploying it to Tomcat yourself?

If you're using the integration, you might try creating a WAR and deploying it yourself, next, to see what happens.  Post an update - I'll follow up after.

I've read your original question again.  Maybe the problem is with the way you created myproject3.  I suspect doesn't have the necessary project nature to be deployed to a server by Eclipse.  ("Project nature" is an Eclipse concept; a project can have several of them; different parts of Eclipse check project natures to determine what projects they can act on.)  You said you checked out the code from Subversion and created the project in one step.  That doesn't necessarily create the right type of project.  Eclipse's J2EE deployment mechanism only allows you to deploy projects with a certain project nature - I think it's "eclipse.common.project.facet.core.nature".  Also, your project needs certain Eclipse builders to be viable; I think "org.eclipse.wst.common.project.facet.core.builder" is one of them.

The .project file at the root of your project is where natures and builders are configured.  You should examine those files in your two projects.

Q: in your Eclipse workspace, are myproject2/.project and myproject3/.project significantly different (besides the name)?  Post the differences here.

Q: does myproject2, in SVN, contain the .project file?

Answering those questions should tell you more.  You may want to carefully examine the different options for checking out and creating a project in a single step.

ContentLicense: CC BY-SA 2.5

Body:
I have a project called myproject2 in my Eclipse IDE. I have a Tomcat application server and I can add there the resource myproject2 (it is a Spring MVC project).

Now I closed the myproject2 in Eclipse, removed myproject2 from the Tomcat resources and do a fresh Subversion checkout with projectname: myproject3.

REstarting the IDE I want to set myproject3 to the Tomcat server so this should be deployed. But all what is available is myproject2 to choose. So I choose it. I can access http://localhost:8080/myproject2/ but I get this warning and serve in the console:

14.12.2010 11:43:11 org.apache.catalina.startup.HostConfig deployDescriptor
WARNING: A docBase C:\Spring\apache-tomcat-6.0.29-windows-x86\apache-tomcat-6.0.29\webapps\myproject2 inside the host appBase has been specified, and will be ignored
14.12.2010 11:43:11 org.apache.catalina.core.StandardContext resourcesStart
SERVE: Error starting static Resources
java.lang.IllegalArgumentException: Document base C:\Spring\apache-tomcat-6.0.29-windows-x86\apache-tomcat-6.0.29\webapps\myproject3 does not exist or is not a readable directory
at org.apache.naming.resources.FileDirContext.setDocBase(FileDirContext.java:142)
at org.apache.catalina.core.StandardContext.resourcesStart(StandardContext.java:4249)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4418)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:791)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:771)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:546)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:637)
at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:563)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:498)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1277)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:321)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:119)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1053)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:785)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1045)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:445)
at org.apache.catalina.core.StandardService.start(StandardService.java:519)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:710)
at org.apache.catalina.startup.Catalina.start(Catalina.java:581)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
14.12.2010 11:43:11 org.apache.catalina.core.StandardContext start
SERVE: Error in resourceStart()
14.12.2010 11:43:11 org.apache.catalina.core.StandardContext start
SERVE: Error getConfigured
14.12.2010 11:43:11 org.apache.catalina.core.StandardContext start
SERVE: Context [/myproject3] startup failed due to previous errors
14.12.2010 11:43:11 org.apache.catalina.core.StandardContext stop
INFO: Container org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/myproject3] has not been started

So what's wrong here? Why don't I have a myproject3 to choose what should be deployed in Tomcat?

Does anyone know?

Best Regards.

Update:

.project (myproject2):

<projectDescription>
    <name>myproject</name>
    <comment>My-Project. NO_M2ECLIPSE_SUPPORT: Project files created with the maven-eclipse-plugin are not supported in M2Eclipse.</comment>
    <projects/>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
        </buildCommand>
    </buildSpec>
    <natures>
        <nature>org.eclipse.jdt.core.javanature</nature>
    </natures>
</projectDescription>

.project (myproject3)

<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
    <name>myproject</name>
    <comment></comment>
    <projects>
    </projects>
    <buildSpec>
        <buildCommand>
            <name>org.eclipse.wst.jsdt.core.javascriptValidator</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.wst.common.project.facet.core.builder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.jdt.core.javabuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.eclipse.wst.validation.validationbuilder</name>
            <arguments>
            </arguments>
        </buildCommand>
        <buildCommand>
            <name>org.maven.ide.eclipse.maven2Builder</name>
            <arguments>
            </arguments>
        </buildCommand>
    </buildSpec>
    <natures>
         <nature>org.eclipse.jem.workbench.JavaEMFNature</nature>
         <nature>org.eclipse.wst.common.modulecore.ModuleCoreNature</nature>
         <nature>org.maven.ide.eclipse.maven2Nature</nature>
         <nature>org.eclipse.jdt.core.javanature</nature>
         <nature>org.eclipse.wst.common.project.facet.core.nature</nature>
         <nature>org.eclipse.wst.jsdt.core.jsNature</nature>
    </natures>
</projectDescription>


问:
Python: Selenium find element by xpath returns empty list
I am trying to get the values of open, high, low, close of the interactive chart on this website: Currency Chart from website.

This is the xpath of the element: //*[@id="chart-area"]/div/div[3]/table/tbody/tr[1]/td[2]/div/div[3]/div[2]/div/span[1]

I have added an attribute name on html debugger, tried to find_elements_by_name but it also returned an empty list. The find_by_class_name method returns error that cannot search compound values. I need to get the Open, High, Low and Close values whenever I hover the mouse on the chart and print it in the console.

I am trying to get the value at the same time I move the mouse on the chart area. I don't know if it is because the field is dynamic, as it changes as I scroll on the chart.

Edit: The values are located at the top left corner of the chart and when you move the mouse in the chart area, the cursor snaps to the point and the data gets updated. Even in the raw version of the data, Raw Data Website, I cannot get the content of the elements when using class names="line-content", css_selector = 'html body' or the xpath='/html/body/table/tbody/tr/td[2]'.

The outputs are like this: Message: Unable to locate element: .line-content, Message: Unable to locate element: /html/body/table/tbody/tr/td[2]

My code:

```<code>driver = webdriver.Firefox()
driver.get("https://www.investing.com/currencies/eur-usd-chart")
open_value_1 = driver.find_elements(By.XPATH, '//*[@id="chart-area"]/div/div[3]/table/tbody/tr[1]/td[2]/div/div[3]/div[2]/div/span[1]')

# If mouse moved and the value changed - print it
while True:
    open_value_2 = driver.find_elements(By.XPATH, '//*[@id="chart-area"]/div/div[3]/table/tbody/tr[1]/td[2]/div/div[3]/div[2]/div/span[1]')
    if open_value_2 is not open_value_1:
        print(open_value_2)
    time.sleep(1)
</code>```

答:
Maybe there is some issue with your Xpath </p>

```<code>(//*[@id="chart-area"]/div/div[3]/table/tbody/tr[1]/td[2]/div/div[3]/div[2]/div/span[1])
</code>```

<p>you can try bellow Xpath </p>

```<code>//*[@id="chart-area"]/div/div[3]/table/tbody/tr[1]/td[2]/div/div[3]/div[1]/div/span[1]
</code>```

Body:
I am trying to get the values of open, high, low, close of the interactive chart on this website: Currency Chart from website.

This is the xpath of the element: //*[@id="chart-area"]/div/div[3]/table/tbody/tr[1]/td[2]/div/div[3]/div[2]/div/span[1]

I have added an attribute name on html debugger, tried to find_elements_by_name but it also returned an empty list. The find_by_class_name method returns error that cannot search compound values. I need to get the Open, High, Low and Close values whenever I hover the mouse on the chart and print it in the console.

I am trying to get the value at the same time I move the mouse on the chart area. I don't know if it is because the field is dynamic, as it changes as I scroll on the chart.

Edit: The values are located at the top left corner of the chart and when you move the mouse in the chart area, the cursor snaps to the point and the data gets updated. Even in the raw version of the data, Raw Data Website, I cannot get the content of the elements when using class names="line-content", css_selector = 'html body' or the xpath='/html/body/table/tbody/tr/td[2]'.

The outputs are like this: Message: Unable to locate element: .line-content, Message: Unable to locate element: /html/body/table/tbody/tr/td[2]

My code:

driver = webdriver.Firefox()
driver.get("https://www.investing.com/currencies/eur-usd-chart")
open_value_1 = driver.find_elements(By.XPATH, '//*[@id="chart-area"]/div/div[3]/table/tbody/tr[1]/td[2]/div/div[3]/div[2]/div/span[1]')

# If mouse moved and the value changed - print it
while True:
    open_value_2 = driver.find_elements(By.XPATH, '//*[@id="chart-area"]/div/div[3]/table/tbody/tr[1]/td[2]/div/div[3]/div[2]/div/span[1]')
    if open_value_2 is not open_value_1:
        print(open_value_2)
    time.sleep(1)

Body:
Maybe there is some issue with your Xpath

(//*[@id="chart-area"]/div/div[3]/table/tbody/tr[1]/td[2]/div/div[3]/div[2]/div/span[1])

you can try bellow Xpath

//*[@id="chart-area"]/div/div[3]/table/tbody/tr[1]/td[2]/div/div[3]/div[1]/div/span[1]


问:
Javascript sum of arrays and average
I have an issue with getting the sum of two arrays and combining their averages while rounding off.

I don't want to hardcode but rather pass two random arrays.
so here is the code but it keeps returning NaN

function sumAverage(arr) {
  var result = 0;
  // Your code here
  // set an array
  arr = [];
  a = [];
  b = [];
  arr[0] = a;
  arr[1] = b;

  var sum = 0;

  // compute sum of elements in the array
  for (var j = 0; j < a.length; j++) {
    sum += a[j];
  }

  // get the  average of elements in the array
  var total = 0;
  total += sum / a.length;

  var add = 0;

  for (var i = 0; i < b.length; i++)
    add += b[i];

  var math = 0;
  math += add / b.length;

  result += math + total;

  Math.round(result);

  return result;
}
console.log(sumAverage([
  [2, 3, 4, 5],
  [6, 7, 8, 9]
]));```

答:
If you wanted to do it a bit more functionally, you could do something like this:

function sumAverage(arrays) {
  const average = arrays.reduce((acc, arr) => {
    const total = arr.reduce((total, num) => total += num, 0);
    return acc += total / arr.length;
  }, 0);

  return Math.round(average);
}

console.log('sum average:', sumAverage([[1,2,3], [4,5,6]]));```

Title: Javascript sum of arrays and average


问:
Difference between field and property in OrientDB
I am using OrientDB for the first time. I read that this database operates in a schema less mode.

Although there seems to be some confusion between Field and Property. What is the difference between these two?

The ALTER command does work on fields but fields are shown under the property name in OrientDB studio in query results. Field operations are done through UPDATE. Am I missing something. Please clarify.

答:
The field and property are the same thing in OrientDB.

When you use UPDATE you should not specify the word property or field, the property is just used in ALTER queries, for example ALTER PROPETY, see:

https://orientdb.com/docs/last/SQL-Alter-Property.html

and

https://orientdb.com/docs/last/SQL-Update.html


问:
Notice: Undefined index: SESS_NAME in student_vote.php on line 9
```<code>   <?php
    include "connection.php";

     if(!isset($_SESSION))
        {
            session_start();
        }
    $cand1  = $_POST['cand1'];

    $cand2  = $_POST['vice1'];

    $sess   =  $_SESSION['SESS_NAME'];

    if(!$cand1){
    $error="<center><h4><font color='#FF0000'>Please fill empty fields</h4></center></font>";
    include"student.php";
    exit();
    }

        $cand1 = addslashes($cand1);

        $cand1 = mysqli_real_escape_string($con,$cand1);

    $sql = 'SELECT * FROM student WHERE username="'.$_SESSION['SESS_NAME'].'" AND status="VOTED"';

    $result = mysqli_query($con,$sql);

                if (mysqli_num_rows($result)==1){

            $msg="<center><h4><font color='#FF0000'>You have already been voted, No need to vote again</h4></center></font>";
            include 'student.php';
            exit();
                }

                else{

                 $sql = 'UPDATE candidate SET votecount = votecount + 1 WHERE cand_id = "'.$_POST['cand1'].'" OR cand_id = "'.$_POST['vice1'].'"';

                $sql2 = 'UPDATE student SET status="VOTED" WHERE username="'.$_SESSION['SESS_NAME'].'"';

                $result = mysqli_query($con,$sql);
                $result2 = mysqli_query($con,$sql2);

        if(!$result && !$result2){
        die("Error on mysql query".mysqli_error());
        }
        else{
        $msg="<center><h4><font color='#FF0000'>Congratulation, you have made your vote.</h4></center></font>";
        include 'student.php';
        exit();
        }
                }

    ?>
</code>```

the  errors are  at code including
      $sess= $_SESSION['SESS_NAME']; and at username="'.$_SESSION['SESS_NAME'].'"
i have tried every possibility so can you check my code?
mainly the error is undefined index at $session[session_name]?

答: Are you sure the session 'SESS_NAME' is getting set? In the code above you are only trying to access its value. Undefined index is the error thrown when there is no session with that name.

Body:
   <?php
    include "connection.php";

     if(!isset($_SESSION))
        {
            session_start();
        }
    $cand1  = $_POST['cand1'];

    $cand2  = $_POST['vice1'];

    $sess   =  $_SESSION['SESS_NAME'];

    if(!$cand1){
    $error="
Please fill empty fields
";
    include"student.php";
    exit();
    }

        $cand1 = addslashes($cand1);

        $cand1 = mysqli_real_escape_string($con,$cand1);

    $sql = 'SELECT * FROM student WHERE username="'.$_SESSION['SESS_NAME'].'" AND status="VOTED"';

    $result = mysqli_query($con,$sql);

                if (mysqli_num_rows($result)==1){

            $msg="
You have already been voted, No need to vote again
";
            include 'student.php';
            exit();
                }

                else{

                 $sql = 'UPDATE candidate SET votecount = votecount + 1 WHERE cand_id = "'.$_POST['cand1'].'" OR cand_id = "'.$_POST['vice1'].'"';

                $sql2 = 'UPDATE student SET status="VOTED" WHERE username="'.$_SESSION['SESS_NAME'].'"';

                $result = mysqli_query($con,$sql);
                $result2 = mysqli_query($con,$sql2);

        if(!$result && !$result2){
        die("Error on mysql query".mysqli_error());
        }
        else{
        $msg="
Congratulation, you have made your vote.
";
        include 'student.php';
        exit();
        }
                }

    ?>

the  errors are  at code including
      $sess= $_SESSION['SESS_NAME']; and at username="'.$_SESSION['SESS_NAME'].'"
i have tried every possibility so can you check my code?
mainly the error is undefined index at $session[session_name]?


问:
JavaScript change style of a specific child div from another child div
Let's say that we have a loop which result 3 divs with other 4 divs inside each, like this:

```<code><div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>

<div class="one">
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
   <div class="two">second class</div>
</div>
</code>```

Now, I want to change the style css with javascript. How can I make something like this in javascript and work?

document.getElementsByClassName('one')[2].document.getElementsByClassName('two')[3].style.cssText {...};

I want to change the style css of the class .two from child [3] which is inside class .one from child [2]

答:
You can use below code -</p>

```<code>var parent = document.getElementsByClassName('one')[2]
parent.getElementsByClassName('two')[3].style.color = "blue";
</code>```

Body:
Let's say that we have a loop which result 3 divs with other 4 divs inside each, like this:

second class

second class

second class

second class

second class

second class

second class

second class

second class

second class

second class

second class

Now, I want to change the style css with javascript. How can I make something like this in javascript and work?

document.getElementsByClassName('one')[2].document.getElementsByClassName('two')[3].style.cssText {...};

I want to change the style css of the class .two from child [3] which is inside class .one from child [2]

Body:
You can use below code -

var parent = document.getElementsByClassName('one')[2]
parent.getElementsByClassName('two')[3].style.color = "blue";


问:
How to parse a JSON Input stream
I am using java to call a url that returns a JSON object:

```<code>url = new URL("my URl");
urlInputStream = url.openConnection().getInputStream();
</code>```

How can I convert the response into string form and parse it?

答:
If you like to use Jackson Databind (which Spring uses by default for its HttpMessageConverters), then you may use the ObjectMapper.readTree(InputStream) API. For example,

```<code>ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(myInputStream);
</code>```

Title: How to parse a JSON Input stream

Body:
I am using java to call a url that returns a JSON object:

url = new URL("my URl");
urlInputStream = url.openConnection().getInputStream();

How can I convert the response into string form and parse it?

Body:
If you like to use Jackson Databind (which Spring uses by default for its HttpMessageConverters), then you may use the ObjectMapper.readTree(InputStream) API. For example,

ObjectMapper mapper = new ObjectMapper();
JsonNode json = mapper.readTree(myInputStream);


问:
how to insert cases into a table based on a parameter without duplicating the main select query?
I have a insert statement in sql server 2008 like below:

```<code>INSERT INTO MYTABLE
SELECT Id,Name,Date
FROM #temp
...joins...
where ...conditions...
</code>```

I need to add a parameter to the code, and based on the parameter I will decide which table the output data should be inserted into. Check below:

```<code>declare @checkValue bit;
if (@checkValue = 1)
begin
   INSERT INTO MYTABLE
    SELECT Id,Name,Date
    FROM #temp
    ...joins...
    where ...conditions...
end
else
begin
    INSERT INTO MY_OTHER_TABLE
    SELECT Id,Name,Date
    FROM #temp
    ...joins...
    where ...conditions...
end
</code>```

I handled the situation like above for now, however the main query is pretty long and I do not want to duplicate it, it does not look professional to me. I am looking for a better way to deal with such an issue. Any help or advice should be appreciated. Thanks.

答:
You could use dynamic SQL (evil :), like so:

```<code>declare @cmd varchar(max) = '
INSERT INTO ' + @tableName + '
SELECT ...
';

execute (@cmd);
</code>```

Or you create stored procedures (one statically INSERTs to table A, another one into table B >> code duplication) which are called depending on @checkValue, or a combination of both like here:

Stored procedure to insert values into dynamic table

Body:
I have a insert statement in sql server 2008 like below:

INSERT INTO MYTABLE
SELECT Id,Name,Date
FROM #temp
...joins...
where ...conditions...

I need to add a parameter to the code, and based on the parameter I will decide which table the output data should be inserted into. Check below:

declare @checkValue bit;
if (@checkValue = 1)
begin
   INSERT INTO MYTABLE
    SELECT Id,Name,Date
    FROM #temp
    ...joins...
    where ...conditions...
end
else
begin
    INSERT INTO MY_OTHER_TABLE
    SELECT Id,Name,Date
    FROM #temp
    ...joins...
    where ...conditions...
end

I handled the situation like above for now, however the main query is pretty long and I do not want to duplicate it, it does not look professional to me. I am looking for a better way to deal with such an issue. Any help or advice should be appreciated. Thanks.

Body:
You could use dynamic SQL (evil :), like so:

declare @cmd varchar(max) = '
INSERT INTO ' + @tableName + '
SELECT ...
';

execute (@cmd);

Or you create stored procedures (one statically INSERTs to table A, another one into table B >> code duplication) which are called depending on @checkValue, or a combination of both like here:

Stored procedure to insert values into dynamic table


问:
Cocos2d-x zoom in zoom out in rendertexture
I are working on a coloring game for kids.I have used bucket fill and it working fine but the problem is coloring image contains some small areas which are impossible to fill by touching on it. I wanted to Implement zoom in and zoom out so that kids can zoom in to small area fill it and zoom out. I have tried scaling rendertexture but it scale around anchor point. Is there a way that I can scale around the touch location ?</p>

答: Scaling will always be done around the anchor point. You have to reposition your RenderTexture, after scaling, so your touch location remains centered.</p>


问:
spring-kafka how to run consumer in background
I found a tutorial on spring-kafka where they created a producer and consumer. However, the program was run through a test case. As the test case ends, the consumer stops.

How to ensure the consumer keeps running in the backgorund so that I can test some messages from my terminal command line.

SpringKafkaExampleApplication.java

```<code>package com.howtoprogram.kafka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringKafkaExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringKafkaExampleApplication.class,
        args);
    }
}
</code>```

KafkaProducerConfig.java

```<code>package com.howtoprogram.kafka;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

@Configuration
@EnableKafka
public class KafkaProducerConfig {
    @Bean
    public ProducerFactory<String, String> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    @Bean
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,
        "localhost:9092");
        props.put(ProducerConfig.RETRIES_CONFIG, 0);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
        props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
        StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
        StringSerializer.class);
        return props;
    }

    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<String, String>(producerFactory());
    }
}
</code>```

KafkaConsumerConfig.java

```<code>package com.howtoprogram.kafka;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;

@Configuration
@EnableKafka
public class KafkaConsumerConfig {
    @Bean
    KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        factory.setConcurrency(3);
        factory.getContainerProperties().setPollTimeout(3000);
        return factory;
    }

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfigs());
    }

    @Bean
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> propsMap = new HashMap<>();
        propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100");
        propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000");
        propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, "group1");
        propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        return propsMap;
    }

    @Bean
    public Listener listener() {
        return new Listener();
    }
}
</code>```

Listener.java

```<code>package com.howtoprogram.kafka;

import java.util.concurrent.CountDownLatch;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;

public class Listener {

public final CountDownLatch countDownLatch1 = new CountDownLatch(1);

    @KafkaListener(id = "foo", topics = "topic1", group = "group1")
    public void listen(ConsumerRecord<?, ?> record) {
        System.out.println(record);
        countDownLatch1.countDown();
    }

}
</code>```

SpringKafkaExampleApplicationTests.java

```<code>package com.howtoprogram.kafka;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.concurrent.TimeUnit;

import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.kafka.test.rule.KafkaEmbedded;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringKafkaExampleApplicationTests {

@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Autowired
private Listener listener;

@Test
public void contextLoads() throws InterruptedException {

    ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send("topic1", "ABC");
    future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
        @Override
        public void onSuccess(SendResult<String, String> result) {
            System.out.println("success");
        }

        @Override
        public void onFailure(Throwable ex) {
            System.out.println("failed");
        }
    });
    System.out.println(Thread.currentThread().getId());
    assertThat(this.listener.countDownLatch1.await(60, TimeUnit.SECONDS)).isTrue();

}

}
</code>```

Please help!

答:
We run our Kafka application in a while(true) loop with an @Scheduled on a Spring Bean : https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html
This way you can also delay the consumption of messages when the rest of your application is initialising.

@Scheduled(initialDelay = 5000L, fixedDelay = 10000L)
public void process() {

  while (keepRunning) {
    try {
      ConsumerRecords<String, String> records = consumer.poll(500);
      // do processing here
    }
  }
}
```

The fixedDelay is a bit strange. This value needs to be available, but is effectively ignored.

It might be tempting to start the consumer in the @PostConstruct but this way Spring keeps thinking the bean is in the init-phase. (so don't do this as Artem Bilan mentions below)

Body:
I found a tutorial on spring-kafka where they created a producer and consumer. However, the program was run through a test case. As the test case ends, the consumer stops.

How to ensure the consumer keeps running in the backgorund so that I can test some messages from my terminal command line.

SpringKafkaExampleApplication.java

package com.howtoprogram.kafka;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class SpringKafkaExampleApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringKafkaExampleApplication.class,
        args);
    }
}

KafkaProducerConfig.java

package com.howtoprogram.kafka;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.producer.ProducerConfig;
import org.apache.kafka.common.serialization.StringSerializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.core.DefaultKafkaProducerFactory;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.core.ProducerFactory;

@Configuration
@EnableKafka
public class KafkaProducerConfig {
    @Bean
    public ProducerFactory<String, String> producerFactory() {
        return new DefaultKafkaProducerFactory<>(producerConfigs());
    }

    @Bean
    public Map<String, Object> producerConfigs() {
        Map<String, Object> props = new HashMap<>();
        props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,
        "localhost:9092");
        props.put(ProducerConfig.RETRIES_CONFIG, 0);
        props.put(ProducerConfig.BATCH_SIZE_CONFIG, 16384);
        props.put(ProducerConfig.LINGER_MS_CONFIG, 1);
        props.put(ProducerConfig.BUFFER_MEMORY_CONFIG, 33554432);
        props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,
        StringSerializer.class);
        props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,
        StringSerializer.class);
        return props;
    }

    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<String, String>(producerFactory());
    }
}

KafkaConsumerConfig.java

package com.howtoprogram.kafka;

import java.util.HashMap;
import java.util.Map;

import org.apache.kafka.clients.consumer.ConsumerConfig;
import org.apache.kafka.common.serialization.StringDeserializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
import org.springframework.kafka.config.ConcurrentKafkaListenerContainerFactory;
import org.springframework.kafka.config.KafkaListenerContainerFactory;
import org.springframework.kafka.core.ConsumerFactory;
import org.springframework.kafka.core.DefaultKafkaConsumerFactory;
import org.springframework.kafka.listener.ConcurrentMessageListenerContainer;

@Configuration
@EnableKafka
public class KafkaConsumerConfig {
    @Bean
    KafkaListenerContainerFactory<ConcurrentMessageListenerContainer<String, String>> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        factory.setConcurrency(3);
        factory.getContainerProperties().setPollTimeout(3000);
        return factory;
    }

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(consumerConfigs());
    }

    @Bean
    public Map<String, Object> consumerConfigs() {
        Map<String, Object> propsMap = new HashMap<>();
        propsMap.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        propsMap.put(ConsumerConfig.ENABLE_AUTO_COMMIT_CONFIG, false);
        propsMap.put(ConsumerConfig.AUTO_COMMIT_INTERVAL_MS_CONFIG, "100");
        propsMap.put(ConsumerConfig.SESSION_TIMEOUT_MS_CONFIG, "15000");
        propsMap.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        propsMap.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        propsMap.put(ConsumerConfig.GROUP_ID_CONFIG, "group1");
        propsMap.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");
        return propsMap;
    }

    @Bean
    public Listener listener() {
        return new Listener();
    }
}

Listener.java

package com.howtoprogram.kafka;

import java.util.concurrent.CountDownLatch;

import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.kafka.annotation.KafkaListener;

public class Listener {

public final CountDownLatch countDownLatch1 = new CountDownLatch(1);

    @KafkaListener(id = "foo", topics = "topic1", group = "group1")
    public void listen(ConsumerRecord<?, ?> record) {
        System.out.println(record);
        countDownLatch1.countDown();
    }

}

SpringKafkaExampleApplicationTests.java

package com.howtoprogram.kafka;

import static org.assertj.core.api.Assertions.assertThat;

import java.util.concurrent.TimeUnit;

import org.junit.ClassRule;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.kafka.test.rule.KafkaEmbedded;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringKafkaExampleApplicationTests {

@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Autowired
private Listener listener;

@Test
public void contextLoads() throws InterruptedException {

    ListenableFuture<SendResult<String, String>> future = kafkaTemplate.send("topic1", "ABC");
    future.addCallback(new ListenableFutureCallback<SendResult<String, String>>() {
        @Override
        public void onSuccess(SendResult<String, String> result) {
            System.out.println("success");
        }

        @Override
        public void onFailure(Throwable ex) {
            System.out.println("failed");
        }
    });
    System.out.println(Thread.currentThread().getId());
    assertThat(this.listener.countDownLatch1.await(60, TimeUnit.SECONDS)).isTrue();

}

}

Please help!

Body:
We run our Kafka application in a while(true) loop with an @Scheduled on a Spring Bean : https://docs.spring.io/spring/docs/current/spring-framework-reference/html/scheduling.html
This way you can also delay the consumption of messages when the rest of your application is initialising.

@Scheduled(initialDelay = 5000L, fixedDelay = 10000L)
public void process() {

  while (keepRunning) {
    try {
      ConsumerRecords<String, String> records = consumer.poll(500);
      // do processing here
    }
  }
}

The fixedDelay is a bit strange. This value needs to be available, but is effectively ignored.

It might be tempting to start the consumer in the @PostConstruct but this way Spring keeps thinking the bean is in the init-phase. (so don't do this as Artem Bilan mentions below)


问:
Error Azure bot service generating APP ID & password
I am trying to create a bot service using Microsoft Azure, however, when I click the button to generate an APP ID and password I receive the following error "There's a temporary problem with the service. Please try again. If you continue to get this message, try again later.". Can anyone help? </p>

答: Issue solved. In order to generate an Microsoft App ID and Password we need to have an Microsoft account. After creating an Microsoft email id I was able to generate the App ID and Password without any errors.</p>


问:
How to revert SVN commit on wrong branch without losing history
I just screwed up and need to figure out how to revert several commits without destroying everything.

I am trying to merge branch1 and branch2 in a temporary branch like so:

```<code>1)  svn cp ^/branch1 ^/branch1a  // Create a branch
2)  svn sw ^/branch1a            // Switch to that branch
3)  svn merge ^/branch2 .        // Merge branch2 to branch1a
4)  <do lots of manual work>
5)  svn ci .                     // revision 991,994,995, return to step 4 if needed
6)  svn sw ^/branch1             // When happy, switch back to branch1
7)  svn merge ^/branch1a .       // Merge our happy changes back into branch1
8)  svn ci                       // Commit these changes
</code>```

I'm still iterating around steps 4-5, but realized that I forgot to do step 2. I need to revert my revisions from branch1, and apply them to branch1a so I can continue work.

I tried to do a revert with svn merge -c991,994,995 ., but my working copy seemed to be unchanged.  Also, I need to ensure that I can keep these changes and re-apply them in branch1a.  What is a sequence of commands I can use?

答:
I ended up using TortoiseSVN to accomplish this. Instructions are mostly here:
https://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-howto-rollback.html

Ensure your working copy is clean and on branch1

Open the log dialogue

Select the revisions you don't like (shift-click for range, ctrl-click of
individual revs)

Right click and select "Revert changes from these revisions". This will revert your working copy.

svn ci . to commit the changes to the repo (this is rev 997)

svn sw ^/branch1a to get back to the intended branch

svn merge -c 991,994,995 . to bring the reverted changes here

svn ci . to commit the revisions to the repo.

I'm just a little worried that when it comes time to merge branch1a back into branch1, revision 997 will get in the way and prevent a good merge.  If someone gives a good answer of a good resolution, I'll be happy to select that answer over this one (which is partial until I actually get to import the revs).

Body:
I just screwed up and need to figure out how to revert several commits without destroying everything.

I am trying to merge branch1 and branch2 in a temporary branch like so:

1)  svn cp ^/branch1 ^/branch1a  // Create a branch
2)  svn sw ^/branch1a            // Switch to that branch
3)  svn merge ^/branch2 .        // Merge branch2 to branch1a
4)  <do lots of manual work>
5)  svn ci .                     // revision 991,994,995, return to step 4 if needed
6)  svn sw ^/branch1             // When happy, switch back to branch1
7)  svn merge ^/branch1a .       // Merge our happy changes back into branch1
8)  svn ci                       // Commit these changes

I'm still iterating around steps 4-5, but realized that I forgot to do step 2. I need to revert my revisions from branch1, and apply them to branch1a so I can continue work.

I tried to do a revert with svn merge -c991,994,995 ., but my working copy seemed to be unchanged.  Also, I need to ensure that I can keep these changes and re-apply them in branch1a.  What is a sequence of commands I can use?


问:
Is it bad to have your test and production environments on the same machine?
Would it be bad to have things set up so that MySite.com is production and test.MySite.com is test?  Both running off the same machine.  The site doesn't get a lot of traffic.

UPDATE

I am talking about an ASP.NET web application running on a Windows server.

答: Is compliance with any kind of standard an issue?  Generally you want developers to have lots of access to test environments so they can resolve issues.  However, it's not always a good idea (or even allowed) for developers to have the same level of access to production systems.</p>


问:
How to call one controller's function from another controller
I was wondering if is it possible to call one controller's function from another controller. This way i tried but failed:

```<code><div ng-app="MyApp">
    <div ng-controller="Ctrl1">
        <button ng-click="func1()">func1</button>
    </div>
    <br>
    <div ng-controller="Ctrl2">
        <button ng-click="func2()">func2</button>
    </div>
</div>
</code>```

```<code>var app = angular.module('MyApp', []);

app.controller('Ctrl1', function($scope) {

  $scope.func1 = function() {
    alert('Ctrl1 and func1')
  }

    $scope.$on("MyFunction", function () {
        alert('Ctrl1 MyFunction')
    });
});

app.controller('Ctrl2', function($scope) {

  $scope.func2 = function() {
    alert('Ctrl2 and func2')
    $scope.$emit("MyFunction");
  }

});
</code>```

when func2 is calling then i used $scope.$emit("MyFunction"); to call Ctrl1 MyFunction but it does not worked. so is it not possible ?

please put some light here.

答:
when you wanted to communicate with sibiling controllers you have to catch the event($on) using rootScope. use this

```<code>$rootScope.$on("MyFunction", function () {
            alert('Ctrl1 MyFunction')
});
</code>```

Demo

var app = angular.module('MyApp', []);

app.controller('Ctrl1', function($scope,$rootScope) {

  $scope.func1 = function() {
    alert('Ctrl1 and func1')
  }

    $rootScope.$on("MyFunction", function () {
        alert('Ctrl1 MyFunction')
    });
});

app.controller('Ctrl2', function($scope) {

  $scope.func2 = function() {
    alert('Ctrl2 and func2')
    $scope.$emit("MyFunction");
  }

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
    <div ng-controller="Ctrl1">
        <button ng-click="func1()">func1</button>
    </div>
    <br>
    <div ng-controller="Ctrl2">
        <button ng-click="func2()">func2</button>
    </div>
</div></code>```

Body:
I was wondering if is it possible to call one controller's function from another controller. This way i tried but failed:

        <button ng-click="func1()">func1</button>

        <button ng-click="func2()">func2</button>

var app = angular.module('MyApp', []);

app.controller('Ctrl1', function($scope) {

  $scope.func1 = function() {
    alert('Ctrl1 and func1')
  }

    $scope.$on("MyFunction", function () {
        alert('Ctrl1 MyFunction')
    });
});

app.controller('Ctrl2', function($scope) {

  $scope.func2 = function() {
    alert('Ctrl2 and func2')
    $scope.$emit("MyFunction");
  }

});

when func2 is calling then i used $scope.$emit("MyFunction"); to call Ctrl1 MyFunction but it does not worked. so is it not possible ?

please put some light here.

Body:
when you wanted to communicate with sibiling controllers you have to catch the event($on) using rootScope. use this

$rootScope.$on("MyFunction", function () {
            alert('Ctrl1 MyFunction')
});

Demo

var app = angular.module('MyApp', []);

app.controller('Ctrl1', function($scope,$rootScope) {

  $scope.func1 = function() {
    alert('Ctrl1 and func1')
  }

    $rootScope.$on("MyFunction", function () {
        alert('Ctrl1 MyFunction')
    });
});

app.controller('Ctrl2', function($scope) {

  $scope.func2 = function() {
    alert('Ctrl2 and func2')
    $scope.$emit("MyFunction");
  }

});

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="MyApp">
    <div ng-controller="Ctrl1">
        <button ng-click="func1()">func1</button>
    </div>
    <br>
    <div ng-controller="Ctrl2">
        <button ng-click="func2()">func2</button>
    </div>
</div>


问:
how to throttle in camel context
I am using Apache camel and jboss fuse, I have created a sample route blue print listed below in, i have sucessfully handling exceptions in all my routes now the problem is i can not find any example of throttling in routes as i have defined. in apache camel documentation, they have given simple DSL throttling and in stackoverflow i have found rabbitMq throttling which is not my case. how to throttle routes like this in apache camel

```<code><?xml version="1.0" encoding="UTF-8"?>
    <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
        xmlns:camel="http://camel.apache.org/schema/blueprint"
        xmlns:cxf="http://camel.apache.org/schema/blueprint/cxf"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd        http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
        <cxf:rsServer address="/testservice" id="testserver" serviceClass="com.company.HelloBean">
        <camelContext id="testContext" trace="false" xmlns="http://camel.apache.org/schema/blueprint">
            <route id="testRoute" >
              <throttle timePeriodMillis="10000">
                <constant>3</constant>
                <from id="_from1" uri="cxfrs:bean:testserver"/>
                    <bean beanType="com.company.HelloBean"
                        id="_bean1" method="hello"/>
              </throttle>
            </route>
        </camelContext>
    </blueprint>
</code>```

this give error when in deploy application in jboss fuse. that can not find service

答:
hy, all you need is you are currently defining your from endpoint in throttle tag which is wrong you need to define the throttling tag only in TO tag like this

```<code>  <throttle id="_throttle1" rejectExecution="true" timePeriodMillis="10000">
                <constant>1</constant>
                <bean beanType="com.company.HelloBean"
                    id="_bean1" method="hello"/>
            </throttle>
</code>```

when requests come to an end point from, you will throttle while requests are going TO another end point you are using beans so, you can do something like this

```<code>    <?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
    xmlns:camel="http://camel.apache.org/schema/blueprint"
    xmlns:cxf="http://camel.apache.org/schema/blueprint/cxf"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd        http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
    <cxf:rsServer address="/testservice" id="testserver" serviceClass="com.evampsaanga.gethomepage.GetHomePageDataLand">
        <cxf:providers>
            <bean class="com.evampsaanga.restresponses.ExceptionHandler" id="securityException"/>
        </cxf:providers>
    </cxf:rsServer>
<!--     <bean class="com.saanga.servicetest.THR" id="myPolicy"/> -->
    <camelContext id="testContext" trace="false" xmlns="http://camel.apache.org/schema/blueprint">
        <route id="testRoute" >
            <from id="_from1" uri="cxfrs:bean:testserver"/>
            <log id="_log1" message="header : ${headers}"/>
            <setHeader headerName="headerbalance" id="_setHeader1">
                <simple>${headers}</simple>
            </setHeader>
            <setBody id="_setBody1">
                <simple>${body}</simple>
            </setBody>
            <throttle id="_throttle1" rejectExecution="true" timePeriodMillis="10000">
                <constant>1</constant>
                <bean beanType="com.evampsaanga.gethomepage.GetHomePageDataLand"
                    id="_bean1" method="Get"/>
            </throttle>
        </route>
    </camelContext>
</blueprint>
</code>```

Title: how to throttle in camel context

Body:
I am using Apache camel and jboss fuse, I have created a sample route blue print listed below in, i have sucessfully handling exceptions in all my routes now the problem is i can not find any example of throttling in routes as i have defined. in apache camel documentation, they have given simple DSL throttling and in stackoverflow i have found rabbitMq throttling which is not my case. how to throttle routes like this in apache camel

<?xml version="1.0" encoding="UTF-8"?>
    <blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
        xmlns:camel="http://camel.apache.org/schema/blueprint"
        xmlns:cxf="http://camel.apache.org/schema/blueprint/cxf"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd        http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
        <cxf:rsServer address="/testservice" id="testserver" serviceClass="com.company.HelloBean">
        <camelContext id="testContext" trace="false" xmlns="http://camel.apache.org/schema/blueprint">
            <route id="testRoute" >
              <throttle timePeriodMillis="10000">
                <constant>3</constant>
                <from id="_from1" uri="cxfrs:bean:testserver"/>
                    <bean beanType="com.company.HelloBean"
                        id="_bean1" method="hello"/>
              </throttle>
            </route>
        </camelContext>
    </blueprint>

this give error when in deploy application in jboss fuse. that can not find service

Body:
hy, all you need is you are currently defining your from endpoint in throttle tag which is wrong you need to define the throttling tag only in TO tag like this

  <throttle id="_throttle1" rejectExecution="true" timePeriodMillis="10000">
                <constant>1</constant>
                <bean beanType="com.company.HelloBean"
                    id="_bean1" method="hello"/>
            </throttle>

when requests come to an end point from, you will throttle while requests are going TO another end point you are using beans so, you can do something like this

    <?xml version="1.0" encoding="UTF-8"?>
<blueprint xmlns="http://www.osgi.org/xmlns/blueprint/v1.0.0"
    xmlns:camel="http://camel.apache.org/schema/blueprint"
    xmlns:cxf="http://camel.apache.org/schema/blueprint/cxf"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.osgi.org/xmlns/blueprint/v1.0.0 http://www.osgi.org/xmlns/blueprint/v1.0.0/blueprint.xsd        http://camel.apache.org/schema/blueprint http://camel.apache.org/schema/blueprint/camel-blueprint.xsd">
    <cxf:rsServer address="/testservice" id="testserver" serviceClass="com.evampsaanga.gethomepage.GetHomePageDataLand">
        <cxf:providers>
            <bean class="com.evampsaanga.restresponses.ExceptionHandler" id="securityException"/>
        </cxf:providers>
    </cxf:rsServer>
<!--     <bean class="com.saanga.servicetest.THR" id="myPolicy"/> -->
    <camelContext id="testContext" trace="false" xmlns="http://camel.apache.org/schema/blueprint">
        <route id="testRoute" >
            <from id="_from1" uri="cxfrs:bean:testserver"/>
            <log id="_log1" message="header : ${headers}"/>
            <setHeader headerName="headerbalance" id="_setHeader1">
                <simple>${headers}</simple>
            </setHeader>
            <setBody id="_setBody1">
                <simple>${body}</simple>
            </setBody>
            <throttle id="_throttle1" rejectExecution="true" timePeriodMillis="10000">
                <constant>1</constant>
                <bean beanType="com.evampsaanga.gethomepage.GetHomePageDataLand"
                    id="_bean1" method="Get"/>
            </throttle>
        </route>
    </camelContext>
</blueprint>


答:
Looks like to me you haven't declared the variable $_SESSION['SESS_NAME']. Try doing the following

```<code>var_dump($_SESSION);
</code>```

This will show you all the defined variables in the session, if SESS_NAME isn't there then it hasn't been defined. Maybe you have failed to define it somewhere else?

Title: Notice: Undefined index: SESS_NAME in student_vote.php on line 9

Body:
Looks like to me you haven't declared the variable $_SESSION['SESS_NAME']. Try doing the following

var_dump($_SESSION);

This will show you all the defined variables in the session, if SESS_NAME isn't there then it hasn't been defined. Maybe you have failed to define it somewhere else?


问:
jenkins can not find android SDK
I try to build a HelloWorld Android project with jenkins, but fail.

Error message:

```<code>* What went wrong:
A problem occurred configuring project ':app'.
> The SDK directory '/home/xxxx/Android/Sdk' does not exist.
</code>```

But I am sure that SDK directory exists, because I can success build it in command line.

What I have try:

set ANDROID_HOME in jenkins and remove project local.properties

build in jenkins fail, can not find sdk

build in command fail, can not find sdk

add project local.properties

build in jenkins fail, can not find sdk

build in command success

Fixed
see this link

Reason

jenkins has no pemission to access of user(xxxx) home folder.

Then I run chmod 777 /home/xxxx and it works now.

答:
I fixed this.

see this link

Reason

jenkins has no pemission to access of user(xxxx) home folder.

Then I run chmod 777 /home/xxxx and it works now.

Title: jenkins can not find android SDK

Body:
I try to build a HelloWorld Android project with jenkins, but fail.

Error message:

* What went wrong:
A problem occurred configuring project ':app'.
> The SDK directory '/home/xxxx/Android/Sdk' does not exist.

But I am sure that SDK directory exists, because I can success build it in command line.

What I have try:

set ANDROID_HOME in jenkins and remove project local.properties

build in jenkins fail, can not find sdk

build in command fail, can not find sdk

add project local.properties

build in jenkins fail, can not find sdk

build in command success

Fixed
see this link

Reason

jenkins has no pemission to access of user(xxxx) home folder.

Then I run chmod 777 /home/xxxx and it works now.


问:
Dynamically add element to DOM in angular
This is how my page looks like on initial load

```<code><body>
 <div class="col-md-12" id="dataPanes">
   <div class="row dataPane"> Chunk of html elements </div>
 </div>

 <div class"col-md-12 text-right">
   <input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addElementChunk()" />
</body>
</code>```

I am in need to add rows to div#dataPanes on button click

If I was using jQuery,addElementChunk() function would have looked as below

```<code>var addElementChunk = function()
{
   var html = "<div class='row dataPane'> Chunk of html elements </div>";
   $("#dataPanes").append(html);
}
</code>```

but how do I implement the same in angular??

答:
You can also append a new html element in this way. I think its very easy to write and also understand. hope it will help you.
angular.element used to access the html element.
 Here is the html code:

 angular.module('myApp',[]).controller('myCtrl', function($scope){

   $scope.addElementChunk = function()
    {
       var htmlStr = '
 Chunk of html elements
';
      debugger;
      angular.element(document.getElementById('dataPanes')).append(htmlStr);
    }

 });```
<pre class="snippet-code-html lang-html prettyprint-override"><code> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.3/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

 <div class="col-md-12" id="dataPanes">
   <div class="row dataPane"> Chunk of html elements </div>
 </div>

 <div class="col-md-12 text-right">
   <input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addElementChunk()" />
</div>
</div></code>```

Here is the fiddle link

Body:
This is how my page looks like on initial load

 Chunk of html elements

   <input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addElementChunk()" />

I am in need to add rows to div#dataPanes on button click

If I was using jQuery,addElementChunk() function would have looked as below

var addElementChunk = function()
{
   var html = "
 Chunk of html elements
";
   $("#dataPanes").append(html);
}

but how do I implement the same in angular??

Body:
You can also append a new html element in this way. I think its very easy to write and also understand. hope it will help you.
angular.element used to access the html element.
 Here is the html code:

 angular.module('myApp',[]).controller('myCtrl', function($scope){

   $scope.addElementChunk = function()
    {
       var htmlStr = '<div class="row dataPane"> Chunk of html elements </div>';
      debugger;
      angular.element(document.getElementById('dataPanes')).append(htmlStr);
    }

 });

 <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/angular.js/1.0.3/angular.min.js"></script>
<div ng-app="myApp" ng-controller="myCtrl">

 <div class="col-md-12" id="dataPanes">
   <div class="row dataPane"> Chunk of html elements </div>
 </div>

 <div class="col-md-12 text-right">
   <input type="button" class="btn btn-primary" value="Add dynamic row" ng-click="addElementChunk()" />
</div>
</div>

Here is the fiddle link


问:
On what does the time complexity for graph algorithms depends on?
I stumbled over this question in my textbook:

"In general, on what does the time complexity of Prim's, Kruskal's and Dijkstra's algorithms depends on?"

a. The number of vertices in the graph.

b. The number of edges in the graph.

c. Both, on the number of vertices and edges in the graph.

Explain your choice.

So according to Wikipedia Prim's,Kruskal's and Dijkstra's algorithms worst case time complexities are O(ElogV), O(ElogV) and O(E+VlogV) respectively. So i guess the answer is c? But why?

答:
In worst case graph will be a complete graph i.e v(v-1)/2 edges ie e>>v and e ~ v^2

Time Complexity of Prim's and Dijkstra's algorithms are:

1. With Adjacency List and Priority queue:

    O((v+e) log v) in  worst case: e>>v so O( e log v)

2. With matrix and Priority queue:

      O(v^2 + e log v) in WC e ~ v^2

    So  O(v^2 + e log v) ~ O(e + e log v) ~ O(e log v).

3. When graph go denser ( Worst case is Complete Graph ) we use Fibonacci Heap
    and adjacency list:    O( e + v log v)

Time complexity of kruskal is O(e log e) in Worst case e ~ v^2
so log (v^2) = 2 log v

So we can safely say than  O(e log e) can be O( 2e log v)
ie O( e log v) in worst case.


问:
PHP - Outsource switch cases in different files
I want a switch-case instruction but outsource all the case-statements in diffenrent files.
Like this:

```<code><?php
switch ($a) {
    foreach (glob("/path/*.php") as $filename) {
            include $filename;
        }
}
</code>```

and in /path/ there are files like a.php and b.php with contents like

```<code><?php
case 1:
    echo "hello";
    break;
</code>```

How can I do this?

Edit:
I am using PHP7.1 if this is of interest.

答:
Your first code snippet will fail instantly because it is not valid syntax. switch/case statements have a true/false expression system. You can use in_array to retrieve your results. (assuming $a is the file name you are looking for)

Example:

```<code>$files = ['/path/to/file.txt','/path/to/file2.txt'];

$a = '/path/to/file.txt';
switch($a) {

    case in_array($a,$files) :
      echo 'test';
    break;

    default :

}
</code>```

In your example, you can try:

```<code>$location = glob("/path/");

switch($a) {

    case in_array($a,$location) :
      include $a;
    break;

    default :

}
</code>```

This is just example code of what you could do. There are many other ways to accomplish this, but you haven't given all the fact, such as $a values.

However, you may be wanting to run a whole set of files on different values of $a, another example:

```<code>switch($a) {
    case 'value_of_something_one' :
      foreach (glob("/path/to/one") as $filename) {
        include $filename;
      }
    break;

    case 'value_of_something_two' :
      foreach (glob("/path/to/two") as $filename) {
        include $filename;
      }
    break;

    default :
}
</code>```

Hope any of this helps.

PHP Documentation: (switch/case)
http://php.net/manual/en/control-structures.switch.php

Body:
I want a switch-case instruction but outsource all the case-statements in diffenrent files.
Like this:

<?php
switch ($a) {
    foreach (glob("/path/*.php") as $filename) {
            include $filename;
        }
}

and in /path/ there are files like a.php and b.php with contents like

<?php
case 1:
    echo "hello";
    break;

How can I do this?

Edit:
I am using PHP7.1 if this is of interest.

Body:
Your first code snippet will fail instantly because it is not valid syntax. switch/case statements have a true/false expression system. You can use in_array to retrieve your results. (assuming $a is the file name you are looking for)

Example:

$files = ['/path/to/file.txt','/path/to/file2.txt'];

$a = '/path/to/file.txt';
switch($a) {

    case in_array($a,$files) :
      echo 'test';
    break;

    default :

}

In your example, you can try:

$location = glob("/path/");

switch($a) {

    case in_array($a,$location) :
      include $a;
    break;

    default :

}

This is just example code of what you could do. There are many other ways to accomplish this, but you haven't given all the fact, such as $a values.

However, you may be wanting to run a whole set of files on different values of $a, another example:

switch($a) {
    case 'value_of_something_one' :
      foreach (glob("/path/to/one") as $filename) {
        include $filename;
      }
    break;

    case 'value_of_something_two' :
      foreach (glob("/path/to/two") as $filename) {
        include $filename;
      }
    break;

    default :
}

Hope any of this helps.

PHP Documentation: (switch/case)
http://php.net/manual/en/control-structures.switch.php


问:
Render column function(data,type,full) on Jquery datatable with complex header not working
I am new to jquery and trying to design a datatable from json response with complex header.

So far data is populated as per requirement but now I want to change some of the column data inside the same datatable based on the json data or based on other column data.

In a simple jquery datatable the facility of render columns with the use of function(data,type,full) was helpful to access other columns by writing full[columnIndex], but on complex header datatable its not working and giving   undefined value.

Please help me and let me know what code should I write in order to get dynamic access to other columns of the datatable.

Here is my code :

```<code>$('#example').dataTable({
    "responsive": true,
    "aaData": data,
    "aoColumns": [{
            "sTitle": "EVENT ID",
            "defaultContent": "",
            "mData": "eventId",
            "render": function(val, type, full) {
                //alert("event id :: " + val + "  ::: " + full[0]+"  ::: "  );
                return '<td id=event>' + val + '</td>';
            }
        },
        { "mData": "ecid_1.ecid" },
        { "mData": "ecid_1.name" },
        { "mData": "ecid_1.address" },
        { "mData": "ecid_2.ecid" },
        { "mData": "ecid_2.name" },
        { "mData": "ecid_2.address" },
        {
            "sTitle": "EVENT DATE",
            "defaultContent": ""
        },
        {
            "defaultContent": "",
            "render": function(val, type, full) {
                var event = full[0];
                //data[0].eventId
                alert(event);
                if (val == "" || val == null) {
                    //alert('<input align="left" id="radio1" type="radio" name="action'+i+'" value="Approve">Approve</input><br/><input align="left" id="radio2" type="radio" name="action'+i+'" value="Reject">Reject</input>');
                    return '<input align="left" id="radio1" type="radio" name="action" value="Approve" onclick="updateEvent('' + event + '','' + full[1] + '','approve','' + full[4] + '','' + +'');">Approve</input><br/><input align="left" id="radio2" type="radio" name="action" value="Reject" onclick="updateEvent('' + event + '','' + full[1] + '','reject','' + full[4] + '','' + +'');">Reject</input>';
                } else {
                    return val;
                }
                //alert("action:::"+data);
            }
        },
        {
            "sTitle": "ACTION DATE",
            "defaultContent": ""
        },
        {
            "sTitle": "ACTION COMMENTS",
            "defaultContent": "",
            "render": function(data, type, full) {
                if (full[4] == "" || full[4] == null) {
                    //alert('<input align="left" id="radio1" type="radio" name="action'+i+'" value="Approve">Approve</input><br/><input align="left" id="radio2" type="radio" name="action'+i+'" value="Reject">Reject</input>');
                    return '<textarea  id="comment" type="text" name="comment" value"aaa"></textarea>';
                } else {
                    return '<textarea readonly style="background-color:#D3D3D3;"  id="comment" name="comment">' + data + '</textarea>';
                }
                //alert("action:::"+data);
            }
        },
        {
            "render": function(data, type, full) {
                var table = $('#example').DataTable();
                var rowIndex = $(this).closest('tr').index();
                //alert(full[2]);
                return '<a href="/MatchMergeAPI/jsp/details.jsp#someRoute?ecid1=' + full[1] + '&ecid2=' + full[2] + '&event=' + full[0] + '"><img src="/MatchMergeAPI/img/eventDetails.jpeg" alt="" style="width: 120px; height: 50px;" /></a>';
            }
        }
    ]
});
</code>```

My datatable now looks like this:

Where you can see the ACTION column which is supposed to give a radio button as per render function but now giving array of data

答:
Ok, so I found the solution too after many hit and trial.
inside render function(data, type, full) we are getting the array of row data inside full, so to get any one of the column value we have to actually get it from the array using the key and the key is exact same as the json objects.

So If I want to get eventId in any of the other columns then code will go like this :

```<code>       function(data,type,full){
         var eventId = full['eventId'];
         return eventId;
        }
</code>```

Body:
I am new to jquery and trying to design a datatable from json response with complex header.

So far data is populated as per requirement but now I want to change some of the column data inside the same datatable based on the json data or based on other column data.

In a simple jquery datatable the facility of render columns with the use of function(data,type,full) was helpful to access other columns by writing full[columnIndex], but on complex header datatable its not working and giving   undefined value.

Please help me and let me know what code should I write in order to get dynamic access to other columns of the datatable.

Here is my code :

$('#example').dataTable({
    "responsive": true,
    "aaData": data,
    "aoColumns": [{
            "sTitle": "EVENT ID",
            "defaultContent": "",
            "mData": "eventId",
            "render": function(val, type, full) {
                //alert("event id :: " + val + "  ::: " + full[0]+"  ::: "  );
                return '' + val + '	';
            }
        },
        { "mData": "ecid_1.ecid" },
        { "mData": "ecid_1.name" },
        { "mData": "ecid_1.address" },
        { "mData": "ecid_2.ecid" },
        { "mData": "ecid_2.name" },
        { "mData": "ecid_2.address" },
        {
            "sTitle": "EVENT DATE",
            "defaultContent": ""
        },
        {
            "defaultContent": "",
            "render": function(val, type, full) {
                var event = full[0];
                //data[0].eventId
                alert(event);
                if (val == "" || val == null) {
                    //alert('<input align="left" id="radio1" type="radio" name="action'+i+'" value="Approve">Approve</input>
<input align="left" id="radio2" type="radio" name="action'+i+'" value="Reject">Reject</input>');
                    return '<input align="left" id="radio1" type="radio" name="action" value="Approve" onclick="updateEvent('' + event + '','' + full[1] + '','approve','' + full[4] + '','' + +'');">Approve</input>
<input align="left" id="radio2" type="radio" name="action" value="Reject" onclick="updateEvent('' + event + '','' + full[1] + '','reject','' + full[4] + '','' + +'');">Reject</input>';
                } else {
                    return val;
                }
                //alert("action:::"+data);
            }
        },
        {
            "sTitle": "ACTION DATE",
            "defaultContent": ""
        },
        {
            "sTitle": "ACTION COMMENTS",
            "defaultContent": "",
            "render": function(data, type, full) {
                if (full[4] == "" || full[4] == null) {
                    //alert('<input align="left" id="radio1" type="radio" name="action'+i+'" value="Approve">Approve</input>
<input align="left" id="radio2" type="radio" name="action'+i+'" value="Reject">Reject</input>');
                    return '<textarea  id="comment" type="text" name="comment" value"aaa"></textarea>';
                } else {
                    return '<textarea readonly style="background-color:#D3D3D3;"  id="comment" name="comment">' + data + '</textarea>';
                }
                //alert("action:::"+data);
            }
        },
        {
            "render": function(data, type, full) {
                var table = $('#example').DataTable();
                var rowIndex = $(this).closest('tr').index();
                //alert(full[2]);
                return '';
            }
        }
    ]
});

My datatable now looks like this:

Where you can see the ACTION column which is supposed to give a radio button as per render function but now giving array of data

Body:
Ok, so I found the solution too after many hit and trial.
inside render function(data, type, full) we are getting the array of row data inside full, so to get any one of the column value we have to actually get it from the array using the key and the key is exact same as the json objects.

So If I want to get eventId in any of the other columns then code will go like this :

       function(data,type,full){
         var eventId = full['eventId'];
         return eventId;
        }


问:
Angular 2 *ngFor and dynamic field
Here a little code:

```<code><div *ngFor="let field of fields">
  <div>
    <label>{{field}}</label><input name="item.field" [(ngModel)]="item.field">
  </div>
</div>
</code>```

"fields" is a list of string equals to each field of "item" object
"item" is an object with several property.

i want to generate a dynamic form using this simple *ngFor and write something like:

"item.field"

Am i doing it wrong ?

Thx you !

答:
Just use:</p>

```<code><label>{{item[field]}}</label><input name="item[field]" [(ngModel)]="item[field]">
</code>```

Title: Angular 2 *ngFor and dynamic field

Body:
Here a little code:

    {{field}}<input name="item.field" [(ngModel)]="item.field">

"fields" is a list of string equals to each field of "item" object
"item" is an object with several property.

i want to generate a dynamic form using this simple *ngFor and write something like:

"item.field"

Am i doing it wrong ?

Thx you !

Body:
Just use:

<label>{{item[field]}}</label><input name="item[field]" [(ngModel)]="item[field]">


问:
Convert list into a list of 2-tuples
I have a list:

```<code>list = [1, 2, 3]
</code>```

I want to get this list and add a tuple so this list becomes like this

```<code>T_list = [(1,x), (2, x), (3,x)]
</code>```

How do I do it?

答:
Use a simple list comprehension to do this:

```<code>>>> your_list = [1, 2, 3]
>>> x = 100
>>> your_list_with_tuples = [(k, x) for k in your_list]
>>> your_list_with_tuples
</code>```

Output

```<code>[(1, 100), (2, 100), (3, 100)]
</code>```

Also, don't name your variables list, dict, etc, because they shadow the builtin types/functions.

Title: Convert list into a list of 2-tuples

Body:
I have a list:

list = [1, 2, 3]

I want to get this list and add a tuple so this list becomes like this

T_list = [(1,x), (2, x), (3,x)]

How do I do it?

Body:
Use a simple list comprehension to do this:

>>> your_list = [1, 2, 3]
>>> x = 100
>>> your_list_with_tuples = [(k, x) for k in your_list]
>>> your_list_with_tuples

Output

[(1, 100), (2, 100), (3, 100)]

Also, don't name your variables list, dict, etc, because they shadow the builtin types/functions.


问:
passing dates in Python
I have the following issue with python with script in linux:
I am executing my_query.py passing as a parameter the date 2017-03-01

```<code>python my_query.py 2017-03-01
</code>```

How can I create a loop to iterate over that date so it cover the entire month (from date 1 to end of month).

Thanks!

答:
```<code>from dateutil.relativedelta import relativedelta
from dateutil.parser import parse
from datetime import timedelta

def dates_between(start, end):
    while start <= end:
        yield start
        start += timedelta(days=1)

start = parse('2017-03-01').date()

for day in dates_between(start, start + relativedelta(months=1)):
    print(day)
</code>```

Title: passing dates in Python

Body:
I have the following issue with python with script in linux:
I am executing my_query.py passing as a parameter the date 2017-03-01

python my_query.py 2017-03-01

How can I create a loop to iterate over that date so it cover the entire month (from date 1 to end of month).

Thanks!


问:
JavaMail: Java.awt.datatransfer.Transferable doesn't exist
I wasn't going to open a question, but I had no solution to this problem!

I have a problem receiving messages from IMAP server.

The error says "Caused by: java.lang.ClassNotFoundException: Didn't find class "java.awt.datatransfer.Transferable" on path...." Here's my code:

```<code>enter String test(){
    String all="";
    try{
        class Runner extends AsyncTask<Object, String, String> {
            @Override
            protected String doInBackground(Object... params) {
                Looper.prepare();
                String all ="";
                try{
                    Message[] msgs = ReceiveMail("imap.gmail.com","993","USER@gmail.com","PASS"); // After passing this line, error logging says error is in this line!
                    for(Message m: msgs){
                        all+=m.getSubject()+"\n"+m.getContent().toString()+"\n\n"; // Error shows here, but popups above
                    }
                    return all;
                }catch (Exception e){
                    e.printStackTrace();
                }
                Looper.loop();
                return all;
            }
        }
        Runner r = new Runner();
        all = r.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, this).get();
    }catch (Exception e){
        e.printStackTrace();
    }
    return all;
}
private Message[] ReceiveMail(String host,String port,String user,String pass){
    try{
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");
        props.setProperty("mail.imaps.host", host);
        props.setProperty("mail.imaps.port", port);
        props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.imaps.socketFactory.fallback", "false");
        Session imapSession = Session.getInstance(props);
        Store store = imapSession.getStore("imaps");
        store.connect(host, user, pass);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        return inbox.getMessages();
    }catch (Exception e){
        e.printStackTrace();
        //log_all("ReceiveMail function: "+e.getMessage());
    }
    return null;
}
</code>```

What is the problem?

Note When I don't use AsyncTask error "Network in main thread" appears.

SOLUTION:

Download these and add them as libraries.

Remove javax.* from dependencies tab in the module settings.

That'll solve it.

答:
Since it doesn't find some class maybe you are missing an external jar?

Edit

You can use JavaMail API to handle your email tasks. JavaMail API is available in JavaEE package and its jar is available for download. Sadly it cannot be used directly in an Android application since it uses AWT components which are completely incompatible in Android. (Thats why you get this error)

You can find the Android port for JavaMail at the following location: http://code.google.com/p/javamail-android/

Add the jars to your application and use the SMTP method

Body:
I wasn't going to open a question, but I had no solution to this problem!

I have a problem receiving messages from IMAP server.

The error says "Caused by: java.lang.ClassNotFoundException: Didn't find class "java.awt.datatransfer.Transferable" on path...." Here's my code:

enter String test(){
    String all="";
    try{
        class Runner extends AsyncTask<Object, String, String> {
            @Override
            protected String doInBackground(Object... params) {
                Looper.prepare();
                String all ="";
                try{
                    Message[] msgs = ReceiveMail("imap.gmail.com","993","USER@gmail.com","PASS"); // After passing this line, error logging says error is in this line!
                    for(Message m: msgs){
                        all+=m.getSubject()+"\n"+m.getContent().toString()+"\n\n"; // Error shows here, but popups above
                    }
                    return all;
                }catch (Exception e){
                    e.printStackTrace();
                }
                Looper.loop();
                return all;
            }
        }
        Runner r = new Runner();
        all = r.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, this).get();
    }catch (Exception e){
        e.printStackTrace();
    }
    return all;
}
private Message[] ReceiveMail(String host,String port,String user,String pass){
    try{
        Properties props = new Properties();
        props.setProperty("mail.store.protocol", "imaps");
        props.setProperty("mail.imaps.host", host);
        props.setProperty("mail.imaps.port", port);
        props.setProperty("mail.imaps.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        props.setProperty("mail.imaps.socketFactory.fallback", "false");
        Session imapSession = Session.getInstance(props);
        Store store = imapSession.getStore("imaps");
        store.connect(host, user, pass);
        Folder inbox = store.getFolder("Inbox");
        inbox.open(Folder.READ_ONLY);
        return inbox.getMessages();
    }catch (Exception e){
        e.printStackTrace();
        //log_all("ReceiveMail function: "+e.getMessage());
    }
    return null;
}

What is the problem?

Note When I don't use AsyncTask error "Network in main thread" appears.

SOLUTION:

Download these and add them as libraries.

Remove javax.* from dependencies tab in the module settings.

That'll solve it.