问:
How to normalize a NumPy array to within a certain range?
After doing some processing on an audio or image array, it needs to be normalized within a range before it can be written back to a file.  This can be done like so:

```<code># Normalize audio channels to between -1.0 and +1.0
audio[:,0] = audio[:,0]/abs(audio[:,0]).max()
audio[:,1] = audio[:,1]/abs(audio[:,1]).max()

# Normalize image to between 0 and 255
image = image/(image.max()/255.0)
</code>```

Is there a less verbose, convenience function way to do this? matplotlib.colors.Normalize() doesn't seem to be related.

答:
If the array contains both positive and negative data, I'd go with:

```<code>import numpy as np

a = np.random.rand(3,2)

# Normalised [0,1]
b = (a - np.min(a))/np.ptp(a)

# Normalised [0,255] as integer: don't forget the parenthesis before astype(int)
c = (255*(a - np.min(a))/np.ptp(a)).astype(int)

# Normalised [-1,1]
d = 2.*(a - np.min(a))/np.ptp(a)-1
</code>```

If the array contains nan, one solution could be to just remove them as:

```<code>def nan_ptp(a):
    return np.ptp(a[np.isfinite(a)])

b = (a - np.nanmin(a))/nan_ptp(a)
</code>```

However, depending on the context you might want to treat nan differently. E.g. interpolate the value, replacing in with e.g. 0, or raise an error.

Finally, worth mentioning even if it's not OP's question, standardization:

```<code>e = (a - np.mean(a)) / np.std(a)
</code>```

Body:
After doing some processing on an audio or image array, it needs to be normalized within a range before it can be written back to a file.  This can be done like so:

# Normalize audio channels to between -1.0 and +1.0
audio[:,0] = audio[:,0]/abs(audio[:,0]).max()
audio[:,1] = audio[:,1]/abs(audio[:,1]).max()

# Normalize image to between 0 and 255
image = image/(image.max()/255.0)

Is there a less verbose, convenience function way to do this? matplotlib.colors.Normalize() doesn't seem to be related.

Body:
If the array contains both positive and negative data, I'd go with:

import numpy as np

a = np.random.rand(3,2)

# Normalised [0,1]
b = (a - np.min(a))/np.ptp(a)

# Normalised [0,255] as integer: don't forget the parenthesis before astype(int)
c = (255*(a - np.min(a))/np.ptp(a)).astype(int)

# Normalised [-1,1]
d = 2.*(a - np.min(a))/np.ptp(a)-1

If the array contains nan, one solution could be to just remove them as:

def nan_ptp(a):
    return np.ptp(a[np.isfinite(a)])

b = (a - np.nanmin(a))/nan_ptp(a)

However, depending on the context you might want to treat nan differently. E.g. interpolate the value, replacing in with e.g. 0, or raise an error.

Finally, worth mentioning even if it's not OP's question, standardization:

e = (a - np.mean(a)) / np.std(a)


来源: stackexchange

问:
Load div (fade in) step by step
I make a html page. I want load step by step in page with jQuery but I don't know make it.

My HTML code:

```<code><div class="main-template">
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
</div>
</code>```

Fade-in burst in sequence!

答:
Maybe something like this? We iterate through all the elements with .each() and set a setTimeout() with a time dependent on the index i.

$(".main-child").each(function (i) {
    var element = $(this);
    setTimeout(function() {
      element.animate({"opacity": 1}, 500);
    }, 200*i);
  });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.main-child{
  width: 100%;
  height: 20px;
  background-color: red;
  opacity: 0;
}</code>```

```

ContentLicense: CC BY-SA 3.0

Title: Load div (fade in) step by step

Body:
I make a html page. I want load step by step in page with jQuery but I don't know make it.

My HTML code:

Fade-in burst in sequence!

Body:
Maybe something like this? We iterate through all the elements with .each() and set a setTimeout() with a time dependent on the index i.

$(".main-child").each(function (i) {
    var element = $(this);
    setTimeout(function() {
      element.animate({"opacity": 1}, 500);
    }, 200*i);
  });

.main-child{
  width: 100%;
  height: 20px;
  background-color: red;
  opacity: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main-template">
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
    <div class="main-child"></div>
</div>


问:
Detail form not sync with ADF tree based on a single recursive view object
I am working on form having a tree based on a single recursive view object, I have created a tree and a detail form which are based on the same recursive view object.

 The problem is when the page runs, It synchronize the detail form only with the top most tree nodes. When I select any sub-node in the tree, the details form is not showing the selected record.

Any help will be highly appreciated.

答:
I have the same scenario, and solved it with a secondary instance of the same VO and building the form upon that. how ever I added some code to Selection listener of the tree to make the synchronization. the adf ow to paper No. 50 also helped me a lot.

```<code>        Utilities.invokeEL("#{bindings.PlnFormTitle.treeModel.makeCurrent}", new Class[] { SelectionEvent.class },
                       new Object[] { selectionEvent });

    RowKeySet addedSet = selectionEvent.getAddedSet();
    Iterator it = addedSet.iterator();
    List<Key> keyList = (List<Key>) it.next();
    Key k = keyList.get(keyList.size() - 1);

    OperationBinding setCurrentRowWithKey = commonBindingOperation.getOperatioBinding("setCurrentRowWithKey");
    setCurrentRowWithKey.getParamsMap().put("rowKey", k.toStringFormat(true));

    setCurrentRowWithKey.execute();
</code>```

this code is what I used for synchronization.

Body:
I have the same scenario, and solved it with a secondary instance of the same VO and building the form upon that. how ever I added some code to Selection listener of the tree to make the synchronization. the adf ow to paper No. 50 also helped me a lot.

        Utilities.invokeEL("#{bindings.PlnFormTitle.treeModel.makeCurrent}", new Class[] { SelectionEvent.class },
                       new Object[] { selectionEvent });

    RowKeySet addedSet = selectionEvent.getAddedSet();
    Iterator it = addedSet.iterator();
    List<Key> keyList = (List<Key>) it.next();
    Key k = keyList.get(keyList.size() - 1);

    OperationBinding setCurrentRowWithKey = commonBindingOperation.getOperatioBinding("setCurrentRowWithKey");
    setCurrentRowWithKey.getParamsMap().put("rowKey", k.toStringFormat(true));

    setCurrentRowWithKey.execute();

this code is what I used for synchronization.


问:
How to Pass PHP Session Variable to external JS file in Symfony
Currently I am working in One PHP Symfony Project Regarding the Performance Evaluation of an Employee.
So I need to know how we can get PHP session variable of an employee (Employee Role) Please see the php file ( $role = $_SESSION['empRole']; ) to an external js file.(js file also attached). I am using PHP Symfony framework.

Actually I need to check who is logged in to the website.if it is admin/core members / Hr.
I need to apply validation to some fileds only when the Coremembers login the website.

Here is the code section that I need to pass $role to External JS file(in pastebin)

```<code>    public function executeIndex(sfWebRequest $request) {
        if (isset($_SESSION['empId'])) {
            $role = $_SESSION['empRole'];
            if ($role == "admin") {
                $empId = $this->getUser()->getAttribute('empId');
                $team_members = GroupwareEmployeesPeer::getAllSubordinatesId($empId`enter code here`);
                $nc = new Criteria();
                $nc->add(PeD`enter code here`ates`enter code here`Peer::NAME, 'Dashboard');
                $resultset = PeDatesPeer::doSelect($nc);
</code>```

So Can you guys give me a solution regarding this, since I am stuck with this for a long time.

Please see thepastebin code for php and external js file.

https://pastebin.com/kbkLjSFa - PHP File.

https://pastebin.com/M60Rg64U - JS file

答:
```<code> ?> <script> var php_variable = '<?php $variable ?>'; </script> <?php
</code>```

Global variable should be declared before external js file include . in js file access it using this variable name php_variable

After the above code . jquery external file should be included here

```<code><script src="external.js" ></script>
</code>```

external.js

```<code>consol.log(php_variable);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Currently I am working in One PHP Symfony Project Regarding the Performance Evaluation of an Employee.
So I need to know how we can get PHP session variable of an employee (Employee Role) Please see the php file ( $role = $_SESSION['empRole']; ) to an external js file.(js file also attached). I am using PHP Symfony framework.

Actually I need to check who is logged in to the website.if it is admin/core members / Hr.
I need to apply validation to some fileds only when the Coremembers login the website.

Here is the code section that I need to pass $role to External JS file(in pastebin)

    public function executeIndex(sfWebRequest $request) {
        if (isset($_SESSION['empId'])) {
            $role = $_SESSION['empRole'];
            if ($role == "admin") {
                $empId = $this->getUser()->getAttribute('empId');
                $team_members = GroupwareEmployeesPeer::getAllSubordinatesId($empId`enter code here`);
                $nc = new Criteria();
                $nc->add(PeD`enter code here`ates`enter code here`Peer::NAME, 'Dashboard');
                $resultset = PeDatesPeer::doSelect($nc);

So Can you guys give me a solution regarding this, since I am stuck with this for a long time.

Please see thepastebin code for php and external js file.

https://pastebin.com/kbkLjSFa - PHP File.

https://pastebin.com/M60Rg64U - JS file

Body:
 ?> <script> var php_variable = '<?php $variable ?>'; </script> <?php

Global variable should be declared before external js file include . in js file access it using this variable name php_variable

After the above code . jquery external file should be included here

<script src="external.js" ></script>

external.js

consol.log(php_variable);


问:
transform xml to xsl
I'm calling a web service, it is returning result in XML format. How do I convert returning XML into XSL and display that in web browser?</p>

答:
I think that you mean that you wish to transform XML to HTML using XSL transformation (XSLT). If my assumption is correct, see this link: http://www.ling.helsinki.fi/kit/2004k/ctl257/JavaXSLT/Ch05.html

or just search "xslt java" in google.

If my assumption is wrong, sorry for missunderstanding.

Title: transform xml to xsl

ContentLicense: CC BY-SA 2.5


问:
How to solve cache slamming / stampeding case with Varnish?
I'm considering to use Varnish as a caching solution for our infrastructure and I would like to ask if there a mechanism inside Varnish, which solves cache slamming / stampeding problem?</p>

答:
Since Varnish 4.0, You can serve stale while revalidate using the grace time (https://info.varnish-software.com/blog/grace-varnish-4-stale-while-revalidate-semantics-varnish ).

Varnish will asynchronously fetch the response from the backend and serve the stale cached content if it is in its grace period.


问:
Get List of subcategory
I have this category on my wordpress:

```<code>Test1
  - Sub1OfTest1
  - Sub2OfTest1
Test2
  - Sub1OfTest2
  - Sub2OfTest2
</code>```

Now iam at url: http://localhost/wordpress/category/test1
I write the following code on file category-test1.php

```<code><?php
$categories =  get_categories('child_of=2');

print_r($categories);
foreach ($categories as $category) : ?>

        <div class="qitem">
            <a href="<?php get_category_link( $category->term_id ); ?>" title="<?php echo $category->name; ?>">
                <?php echo $category->name; ?>
            </a>
            <h4>
                <span class="caption">
                    <?php echo $category->name; ?>
                </span>
            </h4>
            <p>
                <span class="caption">
                    <?php echo $category->description; ?>
                </span>
            </p>
        </div>
<?php
endforeach;
?>
</code>```

I'm trying to show sub category of Test1 but the code only return array(). What did I miss?

答:
//This is coding of getting sub category and sub-sub category

```<code>    $args = array
    (
        'number'     => $number,
        'orderby'    => 'title',
        'order'      => 'ASC',
        'hide_empty' => false,
        'include'    => array(11,281,28,51,99,93,33,55,107,20),
        'exclude'    => array(32,29),
    );
    $product_categories = get_terms( 'product_cat', $args );
    // echo '```';
    // print_r($product_categories);
    // echo '```';

    foreach($product_categories as $data):
        if($data->slug = 'cooking')
        {
            $child_arg = array('hide_empty'=>false,'parent'=>$data->term_id,'exclude'=>array(32,29));
        }
        else
        {
            $child_arg = array('hide_empty'=>false,'parent'=>$data->term_id);
        }
        $child_terms = get_terms('product_cat',$child_arg);
        // echo "```";
        // print_r($child_terms);
        // echo "```";
        foreach($child_terms as $data1):
            if($data1->slug = 'cooking')
            {
                $sub_child_arg = array('hide_empty'=>false,'parent'=>$data1->term_id,'exclude'=>array(32,29));
            }
            else
            {
                $sub_child_arg = array('hide_empty'=>false,'parent'=>$data1->term_id);
            }
            $sub_child_terms = get_terms('product_cat',$sub_child_arg);
            // echo "```";
            // print_r($sub_child_terms);
            // echo "```";
        endforeach;
    endforeach;
?>
</code>```

Title: Get List of subcategory

Body:
I have this category on my wordpress:

Test1
  - Sub1OfTest1
  - Sub2OfTest1
Test2
  - Sub1OfTest2
  - Sub2OfTest2

Now iam at url: http://localhost/wordpress/category/test1
I write the following code on file category-test1.php

<?php
$categories =  get_categories('child_of=2');

print_r($categories);
foreach ($categories as $category) : ?>

            <a href="<?php get_category_link( $category->term_id ); ?>" title="<?php echo $category->name; ?>">
                <?php echo $category->name; ?>

                    <?php echo $category->name; ?>

                    <?php echo $category->description; ?>

<?php
endforeach;
?>

I'm trying to show sub category of Test1 but the code only return array(). What did I miss?

Body:
//This is coding of getting sub category and sub-sub category

    $args = array
    (
        'number'     => $number,
        'orderby'    => 'title',
        'order'      => 'ASC',
        'hide_empty' => false,
        'include'    => array(11,281,28,51,99,93,33,55,107,20),
        'exclude'    => array(32,29),
    );
    $product_categories = get_terms( 'product_cat', $args );
    // echo '<pre>';
    // print_r($product_categories);
    // echo '</pre>';

    foreach($product_categories as $data):
        if($data->slug = 'cooking')
        {
            $child_arg = array('hide_empty'=>false,'parent'=>$data->term_id,'exclude'=>array(32,29));
        }
        else
        {
            $child_arg = array('hide_empty'=>false,'parent'=>$data->term_id);
        }
        $child_terms = get_terms('product_cat',$child_arg);
        // echo "<pre>";
        // print_r($child_terms);
        // echo "</pre>";
        foreach($child_terms as $data1):
            if($data1->slug = 'cooking')
            {
                $sub_child_arg = array('hide_empty'=>false,'parent'=>$data1->term_id,'exclude'=>array(32,29));
            }
            else
            {
                $sub_child_arg = array('hide_empty'=>false,'parent'=>$data1->term_id);
            }
            $sub_child_terms = get_terms('product_cat',$sub_child_arg);
            // echo "<pre>";
            // print_r($sub_child_terms);
            // echo "</pre>";
        endforeach;
    endforeach;
?>


问:
in eclipse, how to distinguish "run configurations" and "debug configurations" when adding self-define UI
I'm a eclipse plugin developer. I have added a new tab in both "Run Configurations" and "Debug Configurations" (code is at one place for the two configurations). But I want to make a textbox invisible in "Run Configurations" and visible in "Debug Configurations". Right now, I have found one way: "parent.getShell().getText()" can return "Run Configuraions" or "Debug Configuratios" Strings for me. But are there any better ways to distinguish whether I'm in "Run Configurations" or "Debug Congurations"? The "getText()" way seems to be very not formal.</p>

答:
This is the current 'mode' of the configuration represented by an id (and also by the ILaunchMode interface).

You can get the current mode id string from the ILaunchConfigurationDialog by calling the getMode() method. For debug the value will be the string defined by ILaunchManager.DEBUG_STRING.

In a launch configuration tab extending AbstractLaunchConfigurationTab you get the launch configuration dialog by calling getLaunchConfigurationDialog.


问:
Restart Delphi Application Programmatically
It should not be possible to run multiple instances of my application. Therefore the project source contains:

```<code>CreateMutex (nil, False, PChar (ID));
if (GetLastError = ERROR_ALREADY_EXISTS) then
  Halt;
</code>```

Now I want to restart my application programmatically. The usual way would be:

```<code>AppName := PChar(Application.ExeName) ;
ShellExecute(Handle,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
Application.Terminate;
</code>```

But this won't work in my case because of the mutex. Even if I release the mutex before starting the second instace it won't work because shutdown takes some time and two instance cannot run in parallel (because of common resources and other effects).

Is there a way to restart an application with such characteristics? (If possible without an additional executable)

Thanks in advance.

答:
You could pass a command line argument like "restart" and run a Sleep() before you try to acquire the Mutex or try to acquire the mutex in a loop that sleeps a while.

Also you could set up communication between both processes, but that might be overkill.

Body:
It should not be possible to run multiple instances of my application. Therefore the project source contains:

CreateMutex (nil, False, PChar (ID));
if (GetLastError = ERROR_ALREADY_EXISTS) then
  Halt;

Now I want to restart my application programmatically. The usual way would be:

AppName := PChar(Application.ExeName) ;
ShellExecute(Handle,'open', AppName, nil, nil, SW_SHOWNORMAL) ;
Application.Terminate;

But this won't work in my case because of the mutex. Even if I release the mutex before starting the second instace it won't work because shutdown takes some time and two instance cannot run in parallel (because of common resources and other effects).

Is there a way to restart an application with such characteristics? (If possible without an additional executable)

Thanks in advance.


答:
Try like below:

$(function(){
$('.main-child').hide();
$('div.main-child').each(function(i){
$(this).delay(i*800).fadeIn('slow');
});
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="main-template">
    <div class="main-child">1</div>
    <div class="main-child">2</div>
    <div class="main-child">3</div>
    <div class="main-child">4</div>
    <div class="main-child">5</div>
    <div class="main-child">6</div>
    <div class="main-child">7</div>
    <div class="main-child">8</div>
    <div class="main-child">9</div>
    <div class="main-child">10</div>
    <div class="main-child">11</div>
    <div class="main-child">12</div>
    <div class="main-child">13</div>
    <div class="main-child">14</div>
    <div class="main-child">15</div>
    <div class="main-child">16</div>
</div></code>```

Title: Load div (fade in) step by step

Body:
Try like below:

$(function(){
$('.main-child').hide();
$('div.main-child').each(function(i){
$(this).delay(i*800).fadeIn('slow');
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="main-template">
    <div class="main-child">1</div>
    <div class="main-child">2</div>
    <div class="main-child">3</div>
    <div class="main-child">4</div>
    <div class="main-child">5</div>
    <div class="main-child">6</div>
    <div class="main-child">7</div>
    <div class="main-child">8</div>
    <div class="main-child">9</div>
    <div class="main-child">10</div>
    <div class="main-child">11</div>
    <div class="main-child">12</div>
    <div class="main-child">13</div>
    <div class="main-child">14</div>
    <div class="main-child">15</div>
    <div class="main-child">16</div>
</div>


问:
How to filter orders for a customer API Woocommerce 2.6
I am filter orders based on the ID of a client, following syntax doesn't working, when i try:

```<code>www.example.com/wp-json/wc/customers/1/orders?
</code>```

Provide me correct syntax

i'm on woocommerce 2.6

答:
If you are using Woocommerce API version 3 (v3), use this format:</p>

```<code>http://<your-domain>/wc-api/v3/orders?filter[customer_id]=<Customer Id>
</code>```

Body:
I am filter orders based on the ID of a client, following syntax doesn't working, when i try:

www.example.com/wp-json/wc/customers/1/orders?

Provide me correct syntax

i'm on woocommerce 2.6

Body:
If you are using Woocommerce API version 3 (v3), use this format:

http://<your-domain>/wc-api/v3/orders?filter[customer_id]=<Customer Id>


问:
How to run javascript code in Visual studio code? /bin/sh: 1: node: not found
I just started learning programming and I installed Visual Studio Code to write javascript in.

I installed the Code Runner extension, to help me run my code.

Whenever I try to run my code it says:

/bin/sh: 1: node: not found

and nothing happens.

How do I fix this? I am trying to make hello world appear, but it just says node not found.

答:
That program looks like running a node for js. Why not just using the built in terminal in the visual studio code with nodejs?

You just need to install the nodejs: https://nodejs.org/en/

Then in visual studio code press ctrl + `
On the terminal you have to say type:

node myapp.js

Then on the terminal it prints out your data.

(that solution is more 'professional like')

Welcome in the world of JavaScript!


问:
Joining 2 Tables (Having 3 common columns) on the basis of only two common columns
I have 2 Tables - Employee and Job_History
and
Both the tables have 3 common columns in it - EMPLOYEE_ID, JOB_ID, DEPARTMENT_ID.

Now, I want to Join both the tables using JOIN but not on the basis of all 3 common columns BUT on the basis of only 2 common columns - EMPLOYEE_ID and JOB_ID.

How can i get the result ?

答:
You can JOIN on as many or as few columns as you'd like. The JOIN conditions tells the database how to merge the data from the tables.

```<code>SELECT EMPLOYEE_ID
FROM EMPLOYEES
JOIN JOB_HISTORY USING (EMPLOYEE_ID, JOB_ID)
</code>```

If the values in DEPARTMENT_ID also match up in both tables where EMPLOYEE_ID and JOB_ID are equivalent, the result set will be the same regardless of whether or not you also include DEPARTMENT_ID.

If I have the following columns in each table:

```<code>Table A
EMPLOYEE_ID  DEPARTMENT_ID  JOB_ID  Other_Column1  Other_Column2
1            1              1       stuff          things
2            2              2       stuff          things
3            3              3       stuff          things

Table B
EMPLOYEE_ID  DEPARTMENT_ID  JOB_ID  Other_Column3  Other_Column4
1            1              1       stuff          things
2            2              2       stuff          things
3            3              3       stuff          things
</code>```

then the joins would be equivalent whether you include DEPARTMENT_ID or not. However if DEPARTMENT_ID were 1, 2, 3 in table A and 2, 3, 4 in table B:

```<code>Table A
EMPLOYEE_ID  DEPARTMENT_ID  JOB_ID  Other_Column1  Other_Column2
1            1              1       stuff          things
2            2              2       stuff          things
3            3              3       stuff          things

Table B
EMPLOYEE_ID  DEPARTMENT_ID  JOB_ID  Other_Column3  Other_Column4
1            2              1       stuff          things
2            3              2       stuff          things
3            4              3       stuff          things
</code>```

the result set would return no results because there are no cases where the three columns, EMPLOYEE_ID, DEPARTMENT_ID, and JOB_ID all match for a given row.

Body:
You can JOIN on as many or as few columns as you'd like. The JOIN conditions tells the database how to merge the data from the tables.

SELECT EMPLOYEE_ID
FROM EMPLOYEES
JOIN JOB_HISTORY USING (EMPLOYEE_ID, JOB_ID)

If the values in DEPARTMENT_ID also match up in both tables where EMPLOYEE_ID and JOB_ID are equivalent, the result set will be the same regardless of whether or not you also include DEPARTMENT_ID.

If I have the following columns in each table:

Table A
EMPLOYEE_ID  DEPARTMENT_ID  JOB_ID  Other_Column1  Other_Column2
1            1              1       stuff          things
2            2              2       stuff          things
3            3              3       stuff          things

Table B
EMPLOYEE_ID  DEPARTMENT_ID  JOB_ID  Other_Column3  Other_Column4
1            1              1       stuff          things
2            2              2       stuff          things
3            3              3       stuff          things

then the joins would be equivalent whether you include DEPARTMENT_ID or not. However if DEPARTMENT_ID were 1, 2, 3 in table A and 2, 3, 4 in table B:

Table A
EMPLOYEE_ID  DEPARTMENT_ID  JOB_ID  Other_Column1  Other_Column2
1            1              1       stuff          things
2            2              2       stuff          things
3            3              3       stuff          things

Table B
EMPLOYEE_ID  DEPARTMENT_ID  JOB_ID  Other_Column3  Other_Column4
1            2              1       stuff          things
2            3              2       stuff          things
3            4              3       stuff          things

the result set would return no results because there are no cases where the three columns, EMPLOYEE_ID, DEPARTMENT_ID, and JOB_ID all match for a given row.


问:
Update on double click of EA Element
We are opening the Customized Form in place of Properties view of EA Element on Double Click of an element in diagram or project browser i.e using EA_OnContextItemDoubleClicked Event (We are using show-dialog to open the customized form and returning false such that properties view should not open on double click). In the customized form we are trying to update the EA Element using the API element.Name and updating it. But the issue is when we update the element name it is getting reflected in project browser but if we open the EA properties view of the updated EA Element and click OK button the update will be reverted back to the old value (Old Name).
Please find the code below.</p>

```<code>public virtual bool EA_OnContextItemDoubleClicked(EA.Repository Repository,string GUID, EA.ObjectType ot)
        {
                  EA.Element ele=  Repository.GetElementByGuid(GUID);
                  ele.Name = "Test";
                  ele.Update();

 repository.AdviseElementChange(ele.ElementID);

            }
</code>```

答: Using this API repository.AdviseElementChange(element.ElementID) the above problem was solved.</p>

Title: Update on double click of EA Element

Body:
We are opening the Customized Form in place of Properties view of EA Element on Double Click of an element in diagram or project browser i.e using EA_OnContextItemDoubleClicked Event (We are using show-dialog to open the customized form and returning false such that properties view should not open on double click). In the customized form we are trying to update the EA Element using the API element.Name and updating it. But the issue is when we update the element name it is getting reflected in project browser but if we open the EA properties view of the updated EA Element and click OK button the update will be reverted back to the old value (Old Name).
Please find the code below.

public virtual bool EA_OnContextItemDoubleClicked(EA.Repository Repository,string GUID, EA.ObjectType ot)
        {
                  EA.Element ele=  Repository.GetElementByGuid(GUID);
                  ele.Name = "Test";
                  ele.Update();

 repository.AdviseElementChange(ele.ElementID);

            }


问:
ASP Core tag helper with inheritance in model
Let's say we have these simplified models:

```<code>public class Person {
   public string Address {set;get;}
}

public class Student: Person {
   public float Grade {set;get;}
}
public class Teacher: Person {
   public string Department {set; get;}
}
</code>```

Now we want to have a create page for student and teacher. my question is how we can use benefits of inheritance to create only one page for student and teacher?

I tried this:

```<code>@model Person

@{
    bool isStudent = Model is Student;
}

<form asp-action="Create">
    <div class="form-horizontal">
    @if (isStudent)
    {
        <div class="form-group">
            <label asp-for="((Student)Model).Grade" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="((Student)Model).Grade" class="form-control" />
                <span asp-validation-for="((Student)Model).Grade" class="text-danger"></span>
            </div>
        </div>
   } else {
        <div class="form-group">
            <label asp-for="((Teacher)Model).Department" class="col-md-2 control-label"></label>
            <div class="col-md-10">
                <input asp-for="((Teacher)Model).Department" class="form-control" />
                <span asp-validation-for="((Teacher)Model).Department" class="text-danger"></span>
            </div>
        </div>
   }
   <div class="form-group">
         <label asp-for="Address" class="col-md-2 control-label"></label>
         <div class="col-md-10">
             <input asp-for="Address" class="form-control" />
             <span asp-validation-for="Address" class="text-danger"></span>
         </div>
   </div>
   <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-success" />
            </div>
        </div>
    </div>
</form>
</code>```

but it does not allow asp-for="((Student)Model).Grade"

答:
Look into this ViewModel with inheritance in ASP .NET Core discussion on github:

It suggests a solution where a subclass tag-helper surround the fields that are specific to each subclass. That fields are rendered either if the model is null or if a specific subclass of that class is passed.

Here is the example: link

Body:
Let's say we have these simplified models:

public class Person {
   public string Address {set;get;}
}

public class Student: Person {
   public float Grade {set;get;}
}
public class Teacher: Person {
   public string Department {set; get;}
}

Now we want to have a create page for student and teacher. my question is how we can use benefits of inheritance to create only one page for student and teacher?

I tried this:

@model Person

@{
    bool isStudent = Model is Student;
}

<form asp-action="Create">

    @if (isStudent)
    {

                <input asp-for="((Student)Model).Grade" class="form-control" />

   } else {

                <input asp-for="((Teacher)Model).Department" class="form-control" />

   }

             <input asp-for="Address" class="form-control" />

                <input type="submit" value="Create" class="btn btn-success" />

</form>

but it does not allow asp-for="((Student)Model).Grade"


问:
Developing a RIA with Django - what technology stack?
I need to develop a web application with the following requirements:

Desktop like UI on the client side

Application deployment

Scalability (i.e. distributing the service on multiple servers)

What I thought of so far (as I love Python but haven't done much web development yet):

Django

Fabric (think I've read somewhere it's suited for this)

What I'm missing is:

How to create rich clients (probably need some javascript libraries for that)?

How to distribute the service?

答: using web browser as your client platform?</p>


问:
compare two generic list containing class objects
How do i compare two generic list(of cSystem) in my cSystemCatalog class? I wanna know if one of the list contains more or fewer class objects, I also want to compare _systemKey and _systemName</p>

```<code>Public Class cSystemCatalog
    Private _systems As List(Of cSystem)

Public Class cSystem
    Private _systemKey As Int32
    Private _systemName As String
</code>```

答:
```<code>If _systems1.Count > _systems2.Count Then
</code>```

Body:
How do i compare two generic list(of cSystem) in my cSystemCatalog class? I wanna know if one of the list contains more or fewer class objects, I also want to compare _systemKey and _systemName

Public Class cSystemCatalog
    Private _systems As List(Of cSystem)

Public Class cSystem
    Private _systemKey As Int32
    Private _systemName As String


问:
how to insert,update delete select with loop in python database
```<code>import MySQLdb conn=MySQLdb.connect("localhost","root","","python")
c=conn.cursor()
city=raw_input("Enter city name :")
c.execute("insert into city (city_name) values (%s)",(city))

c.execute("select * from city")
rows=c.fetchall()
for row in rows:
    print row dno=input("Enter id you want to delete :")
c.execute("delete from city where city_id='%s'",(dno))

eno=input("Enter the id you want to UPDATE :")
cityName=raw_input("Enter name you want to change :");
update=("update city set city_name=%s where city_id=%s")
c.execute(update,(cityName,eno))

c.execute("select * from city")
rows=c.fetchall()
for row in rows:
    print row

conn.commit()
conn.close()
print "Data are finised"
</code>```

答:
This code will work for you.</p>

```<code>import MySQLdb
conn=MySQLdb.connect("128.66.203.247","it1618a14","sumo@123","it1618a14")
c=conn.cursor()
# sudo apt-get install python-mysqldbstrong text
task=1
while(task!=0):
    print "==============================================";
    print "0. Exit";
    print "1. Insert Data";
    print "2. Show Data";
    print "3. Delete Data";
    print "4. Update Data";
    print "==============================================";
    task=input("Enter your choice : ");
    print "==============================================";
    if(task==1):
        # Insert Data Into table
        city=raw_input("Enter city name :")
        c.execute("insert into city (city_name) values (%s)",(city))
        conn.commit()
        # Select Data from Table
        print "===========After Inserting data records are===========";
        c.execute("select * from city")
        rows=c.fetchall()
        for row in rows:
            print row
        print "==============================================";
    elif(task==2):
        # Select Data from Table
        print "===========All Data from table=================";
        c.execute("select * from city")
        rows=c.fetchall()
        for row in rows:
            print row
        print "==============================================";
    elif(task==3):
        # Select Data from Table
        c.execute("select * from city")
        rows=c.fetchall()
        for row in rows:
            print row
        # Delete Data
        print "======Check The data you want to delete===========";
        dno=input("Enter id you want to delete :")
        c.execute("delete from city where city_id='%s'",(dno))
        conn.commit()
        # Select Data from Table
        c.execute("select * from city")
        rows=c.fetchall()
        for row in rows:
            print row
        print "=========After deleted Data=====================";
    elif(task==4):
        # Select Data from Table
        c.execute("select * from city")
        rows=c.fetchall()
        for row in rows:
            print row
        print "=======Check The data you want to update=========";
        # Update Data Code
        eno=input("Enter the id you want to UPDATE :")
        cityName=raw_input("Enter name you want to change :");
        update=("update city set city_name=%s where city_id=%s")
        c.execute(update,(cityName,eno))
        conn.commit()
        print "=========After updated data================";
        # Select Data from Table
        c.execute("select * from city")
        rows=c.fetchall()
        for row in rows:
            print row
    elif(task>4):
        print "Your choice is wrong!! Please Enter right choice";
        print "";
    elif(task<0):
        print "Your choice is wrong!! Please Enter right choice";
        print "";
conn.commit()
conn.close()
print "You have exit the program!!!!"
print "";
</code>```

Body:
This code will work for you.

import MySQLdb
conn=MySQLdb.connect("128.66.203.247","it1618a14","sumo@123","it1618a14")
c=conn.cursor()
# sudo apt-get install python-mysqldbstrong text
task=1
while(task!=0):
    print "==============================================";
    print "0. Exit";
    print "1. Insert Data";
    print "2. Show Data";
    print "3. Delete Data";
    print "4. Update Data";
    print "==============================================";
    task=input("Enter your choice : ");
    print "==============================================";
    if(task==1):
        # Insert Data Into table
        city=raw_input("Enter city name :")
        c.execute("insert into city (city_name) values (%s)",(city))
        conn.commit()
        # Select Data from Table
        print "===========After Inserting data records are===========";
        c.execute("select * from city")
        rows=c.fetchall()
        for row in rows:
            print row
        print "==============================================";
    elif(task==2):
        # Select Data from Table
        print "===========All Data from table=================";
        c.execute("select * from city")
        rows=c.fetchall()
        for row in rows:
            print row
        print "==============================================";
    elif(task==3):
        # Select Data from Table
        c.execute("select * from city")
        rows=c.fetchall()
        for row in rows:
            print row
        # Delete Data
        print "======Check The data you want to delete===========";
        dno=input("Enter id you want to delete :")
        c.execute("delete from city where city_id='%s'",(dno))
        conn.commit()
        # Select Data from Table
        c.execute("select * from city")
        rows=c.fetchall()
        for row in rows:
            print row
        print "=========After deleted Data=====================";
    elif(task==4):
        # Select Data from Table
        c.execute("select * from city")
        rows=c.fetchall()
        for row in rows:
            print row
        print "=======Check The data you want to update=========";
        # Update Data Code
        eno=input("Enter the id you want to UPDATE :")
        cityName=raw_input("Enter name you want to change :");
        update=("update city set city_name=%s where city_id=%s")
        c.execute(update,(cityName,eno))
        conn.commit()
        print "=========After updated data================";
        # Select Data from Table
        c.execute("select * from city")
        rows=c.fetchall()
        for row in rows:
            print row
    elif(task>4):
        print "Your choice is wrong!! Please Enter right choice";
        print "";
    elif(task<0):
        print "Your choice is wrong!! Please Enter right choice";
        print "";
conn.commit()
conn.close()
print "You have exit the program!!!!"
print "";


问:
How to define object variables (javascript like) in Typoscript
I have a list of variables that are something like this:

```<code>pageName = TEXT
pageName.value = "My Name"
pageDescription = TEXT
pageDescription.value = "My Description"
pageID = TEXT
pageID.value = "uhz2773"
pageImg = Text
pageImg.value = "/myPath/to/image.jpg"
..
</code>```

and I use it like

```<code><img src="{pageImg}" />
</code>```

is there a way to put those variables together like:

```<code>myPage = {
    name: "My Name"
    description:"My Description"
    ID: "uhz2773"
    pageImg: "/myPath/to/image.jpg"
}
</code>```

and use it as:

```<code><img src={myPage.img} />
</code>```

I am not sure how to declare this variable in a way that works. Which variable type should I use?

答:
Try to use a COA

```<code>myPage = COA
myPage{
    10 = TEXT
    10.value=my Name
    20 = TEXT
    20.value = My Description
    30 = TEXT
    30.value = uhz2773
    40 = TEXT
    40.value = /myPath/to/image.jpg
}
</code>```

so you should output it as

```<code><img src={myPage.40} />
</code>```

Body:
I have a list of variables that are something like this:

pageName = TEXT
pageName.value = "My Name"
pageDescription = TEXT
pageDescription.value = "My Description"
pageID = TEXT
pageID.value = "uhz2773"
pageImg = Text
pageImg.value = "/myPath/to/image.jpg"
..

and I use it like

is there a way to put those variables together like:

myPage = {
    name: "My Name"
    description:"My Description"
    ID: "uhz2773"
    pageImg: "/myPath/to/image.jpg"
}

and use it as:

I am not sure how to declare this variable in a way that works. Which variable type should I use?

Body:
Try to use a COA

myPage = COA
myPage{
    10 = TEXT
    10.value=my Name
    20 = TEXT
    20.value = My Description
    30 = TEXT
    30.value = uhz2773
    40 = TEXT
    40.value = /myPath/to/image.jpg
}

so you should output it as

<img src={myPage.40} />


问:
How to show additional details in shopify admin order?
I am creating an app in Shopify where I have to add additional fields to Shopify and show these fields in the Shopify order admin page. Please guide me to complete this task.
Please see screenshot http://prntscr.com/fsqiux

Thanks

答: There is no way in Shopify to extend the admin page. If you need to store additional info to an object, for example an order, you can use metafields. What you can do with Metafield and all resources are explained at https://help.shopify.com/api/reference/metafield</p>


问:
Mulesoft flow timeout
I am designing an api using Mulesoft and I would like to have it return a generic response when it takes more than 10 seconds to respond. Currently I am accomplishing this by using an HTTP connector to call another flow within the api.

```<code><http:request-config name="HTTP_Request_Configuration" host="localhost" port="8081" responseTimeout="10000" doc:name="HTTP Request Configuration"/>
<flow name="Incomming-Flow">
    <!-- get request -->
    <http:request config-ref="HTTP_Request_Configuration" path="/validationWithTimeout" method="POST" doc:name="HTTP"/>
    <catch-exception-strategy doc:name="Catch Exception Strategy">
        <!-- Set payload to generic response when http call times out -->
    </catch-exception-strategy>
</flow>
<flow name="Processing-Flow">
    <http:listener config-ref="HTTP_Request_Configuration" path="/validationWithTimeout" allowedMethods="POST" doc:name="HTTP"/>
    <!--
        processing components go here
     -->
</flow>
</code>```

Is there a better way of stopping a flow and returning a generic response when it has taken too long?

答:
As per your configuration, flow will be trying to hit the above url. Please find below a sample HTTP request configuration with response time outs (you can avoid the TLS part, if you are using only HTTP, and not HTTPS):

```<code><configuration defaultTransactionTimeout="300000" defaultResponseTimeout="300000" doc:name="Configuration">
 <default-threading-profile poolExhaustedAction="RUN"/>
</code>```

Hope help you.

Title: Mulesoft flow timeout

Body:
I am designing an api using Mulesoft and I would like to have it return a generic response when it takes more than 10 seconds to respond. Currently I am accomplishing this by using an HTTP connector to call another flow within the api.

<http:request-config name="HTTP_Request_Configuration" host="localhost" port="8081" responseTimeout="10000" doc:name="HTTP Request Configuration"/>
<flow name="Incomming-Flow">

    <http:request config-ref="HTTP_Request_Configuration" path="/validationWithTimeout" method="POST" doc:name="HTTP"/>
    <catch-exception-strategy doc:name="Catch Exception Strategy">

    </catch-exception-strategy>
</flow>
<flow name="Processing-Flow">
    <http:listener config-ref="HTTP_Request_Configuration" path="/validationWithTimeout" allowedMethods="POST" doc:name="HTTP"/>

</flow>

Is there a better way of stopping a flow and returning a generic response when it has taken too long?

Body:
As per your configuration, flow will be trying to hit the above url. Please find below a sample HTTP request configuration with response time outs (you can avoid the TLS part, if you are using only HTTP, and not HTTPS):

<configuration defaultTransactionTimeout="300000" defaultResponseTimeout="300000" doc:name="Configuration">
 <default-threading-profile poolExhaustedAction="RUN"/>

Hope help you.


问:
Asymptotic Complexity for Lazy evaluation
In Strict evaluation its easier to reason about the asymptotic complexity of a program because because the sub expressions that will be evaluated and When they will be evaluated is syntactically apparent. Which is not the case with languages of Lazy evaluation. I find it hard to speculate if an expression is O(n) , O(logn) or O(nlogn)

What would be the best way to tackle asymptotic complexity with Lazy evaluation ?
 Someone who can explain for me to understand would be of great help

答:
With strict evaluation, cost of calculation = cost of use.

If you do xs.map(cos), you pay cost of cos * length(xs).

With lazy evaluation, cost of use < cost of calculation. How specifically it is lower, very much depends on the shape of the computation.

One of the simplest forms of lazy evaluation is short-circuiting of Boolean expressions. Look at (x) => (cheap(x) || expensive(x)).

Its cost of computation greatly depends on how often cheap(x) is true, so that expensive(x) is not invoked. Same applies to other lazy computations, e.g. the use of cache / memoization, use of generators, etc.

To my mind, the big-O approach is not reasonably applicable to problems like these, unless you can find a clear dependency between the size of the problem (which big-O is about) and the rate of lazy computation actually being performed.


问:
How to Pass PHP Session Variable to external JS file in Symfony
Currently I am working in One PHP Symfony Project Regarding the Performance Evaluation of an Employee.
So I need to know how we can get PHP session variable of an employee (Employee Role) Please see the php file ( $role = $_SESSION['empRole']; ) to an external js file.(js file also attached). I am using PHP Symfony framework.

Actually I need to check who is logged in to the website.if it is admin/core members / Hr.
I need to apply validation to some fileds only when the Coremembers login the website.

Here is the code section that I need to pass $role to External JS file(in pastebin)

```<code>    public function executeIndex(sfWebRequest $request) {
        if (isset($_SESSION['empId'])) {
            $role = $_SESSION['empRole'];
            if ($role == "admin") {
                $empId = $this->getUser()->getAttribute('empId');
                $team_members = GroupwareEmployeesPeer::getAllSubordinatesId($empId`enter code here`);
                $nc = new Criteria();
                $nc->add(PeD`enter code here`ates`enter code here`Peer::NAME, 'Dashboard');
                $resultset = PeDatesPeer::doSelect($nc);
</code>```

So Can you guys give me a solution regarding this, since I am stuck with this for a long time.

Please see thepastebin code for php and external js file.

https://pastebin.com/kbkLjSFa - PHP File.

https://pastebin.com/M60Rg64U - JS file

答:
Yes you can get the php variable into the js file.

Method I:

Rename your .js file to .js.php and pass the php variable as a query string to this file where you link this file in your page.

So, if you have some test.js file, rename it to test.js.php and use it in your page like this

```<code><script src="test.js.php?session_var=<?= $your_var_here;?>&any_var=<?= $any_php_var;?>"></script>
</code>```

And in your js file, retrieve the values from query string parameters
So inside test.js.php, you can simply

```<code>var some_var = "<?= $_GET['session_var']";
var any_var = "<?= $_GET['any_var'];?>";
//rest of your logic goes here
</code>```

Method II:

Use an AJAX request.

```<code>var some_var, another_var;
$.ajax({
  url : '/url-which-returns-session-vars', //return the session data in json from this url
  asnyc : false,
  dataType : 'json',
  success : function(res){
     some_var = res.some_var;
     another_var = res.another_var;
  }
});
//rest of the logic goes here.
</code>```

Both of these methods work. But I prefer the first method, since I don't have to write extra code.

Edit:
Suppose the response of the ajax call looks like this

```<code>{
   some_var : 'value here',
   another_var : 'another value here'
}
</code>```

So res in the success function argument contains this response and since the response is a JSON you can access these values using the . notation.
Thus,

```<code>some_var = res.some_var;
another_var = res.another_var;
</code>```

and since these variables are global variables, you can use them anywhere in your code in this file.

Body:
Currently I am working in One PHP Symfony Project Regarding the Performance Evaluation of an Employee.
So I need to know how we can get PHP session variable of an employee (Employee Role) Please see the php file ( $role = $_SESSION['empRole']; ) to an external js file.(js file also attached). I am using PHP Symfony framework.

Actually I need to check who is logged in to the website.if it is admin/core members / Hr.
I need to apply validation to some fileds only when the Coremembers login the website.

Here is the code section that I need to pass $role to External JS file(in pastebin)

    public function executeIndex(sfWebRequest $request) {
        if (isset($_SESSION['empId'])) {
            $role = $_SESSION['empRole'];
            if ($role == "admin") {
                $empId = $this->getUser()->getAttribute('empId');
                $team_members = GroupwareEmployeesPeer::getAllSubordinatesId($empId`enter code here`);
                $nc = new Criteria();
                $nc->add(PeD`enter code here`ates`enter code here`Peer::NAME, 'Dashboard');
                $resultset = PeDatesPeer::doSelect($nc);

So Can you guys give me a solution regarding this, since I am stuck with this for a long time.

Please see thepastebin code for php and external js file.

https://pastebin.com/kbkLjSFa - PHP File.

https://pastebin.com/M60Rg64U - JS file

Body:
Yes you can get the php variable into the js file.

Method I:

Rename your .js file to .js.php and pass the php variable as a query string to this file where you link this file in your page.

So, if you have some test.js file, rename it to test.js.php and use it in your page like this

<script src="test.js.php?session_var=<?= $your_var_here;?>&any_var=<?= $any_php_var;?>"></script>

And in your js file, retrieve the values from query string parameters
So inside test.js.php, you can simply

var some_var = "<?= $_GET['session_var']";
var any_var = "<?= $_GET['any_var'];?>";
//rest of your logic goes here

Method II:

Use an AJAX request.

var some_var, another_var;
$.ajax({
  url : '/url-which-returns-session-vars', //return the session data in json from this url
  asnyc : false,
  dataType : 'json',
  success : function(res){
     some_var = res.some_var;
     another_var = res.another_var;
  }
});
//rest of the logic goes here.

Both of these methods work. But I prefer the first method, since I don't have to write extra code.

Edit:
Suppose the response of the ajax call looks like this

{
   some_var : 'value here',
   another_var : 'another value here'
}

So res in the success function argument contains this response and since the response is a JSON you can access these values using the . notation.
Thus,

some_var = res.some_var;
another_var = res.another_var;

and since these variables are global variables, you can use them anywhere in your code in this file.


问:
Convert php array_sum to java
```<code>$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";  //==20
</code>```

how i can do this in java?

答:
```<code>    long array_sum(int...array)
    {
        long sum = 0;
        for(int value : array)
            sum += value;
        return sum;
    }
</code>```

Example:

```<code>System.out.println(array_sum(1, 2, 3, -1));
System.out.println(array_sum(1, 2));
System.out.println(array_sum(new int[]{1,2,3,4,5}));

5
3
15
</code>```

Title: Convert php array_sum to java

Body:
$a = array(2, 4, 6, 8);
echo "sum(a) = " . array_sum($a) . "\n";  //==20

how i can do this in java?

Body:
    long array_sum(int...array)
    {
        long sum = 0;
        for(int value : array)
            sum += value;
        return sum;
    }

Example:

System.out.println(array_sum(1, 2, 3, -1));
System.out.println(array_sum(1, 2));
System.out.println(array_sum(new int[]{1,2,3,4,5}));

5
3
15


问:
Unable to open file in exported jar
So i have wrote an application that uses 'config.properties' & 'profile.properties' Files.

Anything works fine in Eclipse (Debug), but after exporting Runnable JAR
, this JAR does not include the Properties Files.
so i dragged this two files inside the jar and now i got this exception / error:

```<code>java.io.FileNotFoundException: config.properties (Nie można odnaleźć
określonego pliku)
   at java.io.FileInputStream.open0(Native Method)
   at java.io.FileInputStream.open(Unknown Source)
   at java.io.FileInputStream.<init>(Unknown Source)
   at com.profilemaker.Profiler.<init>(Profiler.java:32)
   at com.main.Main.main(Main.java:7) Exception in thread "main" java.lang.NullPointerException
   at com.profilemaker.Profiler.<init>(Profiler.java:43)
   at com.main.Main.main(Main.java:7)
</code>```

答: @JB Nizet answer is correct. Also make sure that /path/in/the/jar/of/the.properties is added to the classpath when running the application</p>

Title: Unable to open file in exported jar

Body:
So i have wrote an application that uses 'config.properties' & 'profile.properties' Files.

Anything works fine in Eclipse (Debug), but after exporting Runnable JAR
, this JAR does not include the Properties Files.
so i dragged this two files inside the jar and now i got this exception / error:

java.io.FileNotFoundException: config.properties (Nie można odnaleźć
określonego pliku)
   at java.io.FileInputStream.open0(Native Method)
   at java.io.FileInputStream.open(Unknown Source)
   at java.io.FileInputStream.<init>(Unknown Source)
   at com.profilemaker.Profiler.<init>(Profiler.java:32)
   at com.main.Main.main(Main.java:7) Exception in thread "main" java.lang.NullPointerException
   at com.profilemaker.Profiler.<init>(Profiler.java:43)
   at com.main.Main.main(Main.java:7)


问:
ReactDom is not defined?
I am trying to write a basic program in reactjs

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.min.js"></script>
    <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
</head>
<body>
    <div id="example"></div>
    <script type="text/babel">
        ReactDOM.render(
        <h1>Hello, world!</h1>,
        document.getElementById('example')
        );
    </script>
</body>
</html>
</code>```

The above program works fine. But when I move the content inside my script file to a separate app.jsx file it shows error that reactDom is not defined.

```<code><!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8" />
    <title>Hello React!</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.3.2/react-dom.min.js"></script>
    <script src="https://unpkg.com/babel-core@5.8.38/browser.min.js"></script>
</head>
<body>
    <div id="example"></div>
    <script type="text/babel" src="app.jsx">

    </script>
</body>
</html>
</code>```

and my app.jsx looks like:

```<code>ReactDom.render(
    <h1>Hello React!!!</h1>,
    document.getElementById('example')
)
</code>```

答: The global is ReactDOM (note DOM is all uppercase).

Title: ReactDom is not defined?

Body:
I am trying to write a basic program in reactjs

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Hello React!</title>

The above program works fine. But when I move the content inside my script file to a separate app.jsx file it shows error that reactDom is not defined.

<!DOCTYPE html>

    <meta charset="UTF-8" />
    <title>Hello React!</title>

and my app.jsx looks like:

ReactDom.render(

Hello React!!!
,
    document.getElementById('example')
)


问:
How to get the character between a character and a space
I have an application that gets a parameter of a certain SQL query.

How will I get the characters between @ and space?

Example: Select Name From SomeTable Where Id=@ID Group By Name

so the output would be: ID

I am using the following code but it only extract characters after @. In the above example it extracts: ID Group By Name.

```<code>strParamName = sqlQuery.Substring(sqlQuery.IndexOf('@') + 1);
</code>```

答:
This is might be wrong approach in your case.

You can also achieve this via Regex:

```<code>string sql = "Select Name From SomeTable Where Id=@ID Group By Name";

string result = Regex.Match(sql, "(?<=@)[^ ]+").Value;
</code>```

Pattern (?<=@)[^ ]+ means the following:

(?<=@) – positive lookbehind for @ character,

[^ ]+ – matches between one and unlimited times for non-whitespace () character.

Body:
I have an application that gets a parameter of a certain SQL query.

How will I get the characters between @ and space?

Example: Select Name From SomeTable Where Id=@ID Group By Name

so the output would be: ID

I am using the following code but it only extract characters after @. In the above example it extracts: ID Group By Name.

strParamName = sqlQuery.Substring(sqlQuery.IndexOf('@') + 1);

Body:
This is might be wrong approach in your case.

You can also achieve this via Regex:

string sql = "Select Name From SomeTable Where Id=@ID Group By Name";

string result = Regex.Match(sql, "(?<=@)[^ ]+").Value;

Pattern (?<=@)[^ ]+ means the following:

(?<=@) – positive lookbehind for @ character,

[^ ]+ – matches between one and unlimited times for non-whitespace () character.


问:
Displaying data from other table in php while loop
I am trying to display options in select tag from another table while my
 first, while loop continues, this is what I have tried so far !!

```<code><?php
     $query="SELECT * FROM `customerdata` WHERE takenby='$_SESSION[username]'";
     $query_two="SELECT * FROM `vendordriver` WHERE vendoremail='$_SESSION[username]'";
     $run_two=$db->query($query_two);
     $run=$db->query($query);
     while ($row=$run->fetch_assoc()) {
       echo " <tr><td>$row[bookingid]</td>
       <td>$row[drivername]</td>
       <td>$row[cabtype]</td>
       <td>$row[carnumber]</td><td><select>";
  while ($row_two=$run_two->fetch_assoc()) {
    echo "<option>$row_two[drivername]</option>";
  }
echo" </select></td>
       <td><input type='submit' class='btn btn-success' value='SEND '>
       </td>";
     }
    ?>
</code>```

Any Suggestions Please !!!

答:
You can try this code</p>

```<code><?php
$table_1 = null;
$username = $_SESSION['username'];
$query="SELECT * FROM customerdata WHERE takenby='$username'";
$run=$db->query($query);
if ($result->num_rows > 0) {
    while ($row=$run->fetch_assoc()) {
    $table_1 = "<tr><td>$row[bookingid]</td>";
    $table_1 .= "<td>$row[drivername]</td>";
    $table_1 .= "<td>$row[cabtype]</td>";
    $table_1 .= "<td>$row[carnumber]</td><td><select>";

echo $table_1;
$query_two="SELECT * FROM vendordriver WHERE vendoremail='$username'";
$run_two=$db->query($query_two);
        while ($row_two=$run_two->fetch_assoc()) {
            echo "<option>$row_two[drivername]</option>";
        }

        echo" </select></td>
        <td><input type='submit' class='btn btn-success' value='SEND '>
        </td>";
    }
}
?>
</code>```

Body:
I am trying to display options in select tag from another table while my
 first, while loop continues, this is what I have tried so far !!

<?php
     $query="SELECT * FROM `customerdata` WHERE takenby='$_SESSION[username]'";
     $query_two="SELECT * FROM `vendordriver` WHERE vendoremail='$_SESSION[username]'";
     $run_two=$db->query($query_two);
     $run=$db->query($query);
     while ($row=$run->fetch_assoc()) {
       echo "
$row[bookingid]
       $row[drivername]
       $row[cabtype]
       $row[carnumber]	<select>";
  while ($row_two=$run_two->fetch_assoc()) {
    echo "<option>$row_two[drivername]</option>";
  }
echo" </select>
       <input type='submit' class='btn btn-success' value='SEND '>
       	";
     }
    ?>

Any Suggestions Please !!!

Body:
You can try this code

<?php
$table_1 = null;
$username = $_SESSION['username'];
$query="SELECT * FROM customerdata WHERE takenby='$username'";
$run=$db->query($query);
if ($result->num_rows > 0) {
    while ($row=$run->fetch_assoc()) {
    $table_1 = "<tr><td>$row[bookingid]</td>";
    $table_1 .= "<td>$row[drivername]</td>";
    $table_1 .= "<td>$row[cabtype]</td>";
    $table_1 .= "<td>$row[carnumber]</td><td><select>";

echo $table_1;
$query_two="SELECT * FROM vendordriver WHERE vendoremail='$username'";
$run_two=$db->query($query_two);
        while ($row_two=$run_two->fetch_assoc()) {
            echo "<option>$row_two[drivername]</option>";
        }

        echo" </select></td>
        <td><input type='submit' class='btn btn-success' value='SEND '>
        </td>";
    }
}
?>


问:
assigning a variable using a separate module?
I have been learning python for a while now, and thought it was about time to learn more about modules. Specifically, how to write them. I have been working through PyGame for a while now, and have grown annoyed with having to define each color that I use. I thought this would be a good place to start with writing a module, but I ran into an error straight away. What I want is something like this, but I don't know how to assign the tuple of rgb to the color in the main script.

Main script:

```<code>import rgb_color as rgb
red = rgb.red()
</code>```

Module:

```<code>red():
  (255,0,0)
</code>```

答:
As noted in the comments, you should probably spend some more time with the basics, such as functions, before heading into modules.

Still, here you do not need a function, though. A "constant" will do the trick just fine. (Note that there are no true constants in Python, though, just don't modify the values). Just write

```<code>red = (255, 0, 0)
</code>```

in your module file, or perhaps even better

```<code>RED = (255, 0, 0) # All caps
</code>```

to better signal that it is supposed to be a constant value.

Then, when you import your module the constant becomes available. Perhaps it would be a good idea to also look at what __all__ does if you ever think about doing from rgb_color import * even though this is highly discouraged.

Body:
I have been learning python for a while now, and thought it was about time to learn more about modules. Specifically, how to write them. I have been working through PyGame for a while now, and have grown annoyed with having to define each color that I use. I thought this would be a good place to start with writing a module, but I ran into an error straight away. What I want is something like this, but I don't know how to assign the tuple of rgb to the color in the main script.

Main script:

import rgb_color as rgb
red = rgb.red()

Module:

red():
  (255,0,0)

Body:
As noted in the comments, you should probably spend some more time with the basics, such as functions, before heading into modules.

Still, here you do not need a function, though. A "constant" will do the trick just fine. (Note that there are no true constants in Python, though, just don't modify the values). Just write

red = (255, 0, 0)

in your module file, or perhaps even better

RED = (255, 0, 0) # All caps

to better signal that it is supposed to be a constant value.

Then, when you import your module the constant becomes available. Perhaps it would be a good idea to also look at what __all__ does if you ever think about doing from rgb_color import * even though this is highly discouraged.


问:
Comparing a string with the empty string (Java)
I have a question about comparing a string with the empty string in Java. Is there a difference, if I compare a string with the empty string with == or equals? For example:

```<code>String s1 = "hi";

if (s1 == "")
</code>```

or

```<code>if (s1.equals(""))
</code>```

I know that one should compare strings (and objects in general) with equals, and not ==, but I am wondering whether it matters for the empty string.

答: Use String.isEmpty(), or StringUtils.isEmpty(String str) if you need a null check.</p>

Body:
I have a question about comparing a string with the empty string in Java. Is there a difference, if I compare a string with the empty string with == or equals? For example:

String s1 = "hi";

if (s1 == "")

or

if (s1.equals(""))

I know that one should compare strings (and objects in general) with equals, and not ==, but I am wondering whether it matters for the empty string.

LastEditorDisplayName: strager


问:
Ruby on Rails set up
I am currently following the rails guide to create a blog app.

When I run.

```<code>ruby -v #ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin16].
</code>```

I have already ran:

```<code>gem install rails
bundle install
</code>```

I just reached step 4.1, then I ran

```<code>bin/rails server
</code>```

and I am encountering the following error

答:
It's a warning, and not an error. It's clearly suggesting: upgrade to 2.3.1

The server is up and running anyway.

If you are using rvm, rvm install ruby-2.3.1 will do it for you.

Title: Ruby on Rails set up

Body:
I am currently following the rails guide to create a blog app.

When I run.

ruby -v #ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-darwin16].

I have already ran:

gem install rails
bundle install

I just reached step 4.1, then I ran

bin/rails server

and I am encountering the following error


问:
How to identify the input for the server is of InputStream or Output stream
I have a ServerSocket and looking for help.

 I want to identify the request from the client of type InputStream or OutputStream. I am stuck with this point and looking forward to your help

```<code>ServerSocket servsock = new ServerSocket(13267);
while (true) {
     System.out.println("Waiting...");

     Socket sock = servsock.accept();
     System.out.println("Accepted connection : " + sock);

     InputStream is = sock.getInputStream();
     new FileServer().receiveFile(is);
     sock.close();
 }
</code>```

Please tell me how can I put it in a conditional statement to provide the further execution

答:
You need to read from the socket to identify which operation the client socket is performing.

Eg. Client sends PUT Filename

Server reads from the input stream and save the file in the file server

Client sends GET Filename

Server reads Filename from the input stream and writes the file to the outputstream

So it depends on the protocol you are choosing

Body:
I have a ServerSocket and looking for help.

 I want to identify the request from the client of type InputStream or OutputStream. I am stuck with this point and looking forward to your help

ServerSocket servsock = new ServerSocket(13267);
while (true) {
     System.out.println("Waiting...");

     Socket sock = servsock.accept();
     System.out.println("Accepted connection : " + sock);

     InputStream is = sock.getInputStream();
     new FileServer().receiveFile(is);
     sock.close();
 }

Please tell me how can I put it in a conditional statement to provide the further execution


问:
App id does not exit - IONIC
The app is first uploaded by my colleague using ionic upload. When I am trying to upload the same app I am getting the following error.

```<code>An error occurred uploading the build: An error occurred uploading your application - App ID 4af0u3f5 does not exist

An error occurred uploading your application - App ID 4af0u3f5 does not exist (CLI v1.7.15)
</code>```

What I assuming that I am getting this error because we both have different play store id and one app id can be associate with one unique email id.

Is there any way that we can work and upload the app by having two different play store id.

答:
I did the same because l had mistakenly deleted the app from ionic view. i fixed it by deleting .io-config.json and deleting the app id from ionic.config.json to be like { "name": "{{AppName}}", "app_id": "", "v2": true, "typescript": true }

Then l tried to upload again.

Title: App id does not exit - IONIC

Body:
The app is first uploaded by my colleague using ionic upload. When I am trying to upload the same app I am getting the following error.

An error occurred uploading the build: An error occurred uploading your application - App ID 4af0u3f5 does not exist

An error occurred uploading your application - App ID 4af0u3f5 does not exist (CLI v1.7.15)

What I assuming that I am getting this error because we both have different play store id and one app id can be associate with one unique email id.

Is there any way that we can work and upload the app by having two different play store id.


问:
How can I get a full dump of a REST API
I want to have a full dump of a rest API. Now I have to query on everything but I just want to have everything of the API in one file (csv or json).

How can I do this?

Thanks!

答:
There's no one size fits all answer for this. Every API works differently, and some might have a specific feature for this.

If the service you are using is truly RESTful (as in: uses hyperlinks for everything), you might be able to just use a mirror/spider tool to get all the data, but very few services that advertise themselves as REST really are.

Title: How can I get a full dump of a REST API


问:
No module named 'pafy'
```<code>sudo  pip3.6 install  pafy
Collecting pafy
  Downloading pafy-0.5.3.1.tar.gz
Installing collected packages: pafy
  Running setup.py install for pafy ... done
Successfully installed pafy-0.5.3.1
</code>```

It is Successfully installed pafy-0.5.3.1.

```<code>~$ python
Python 3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:09:58)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import pafy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'pafy'
</code>```

Why no module named 'pafy'?

答:
You ran pip as sudo but you're running python as normal user. Programs run as normal user don't have rights to access super-user's content (sudo).

To verify this, you can run python as super-user and try to import pafy.

```<code>$ sudo python
>>> import pafy
</code>```

You should never use sudo pip install; you could overwrite important stuff.

Use pip install --user <packagename> or install and use virtualenv. I prefer virtualenv.

Title: No module named 'pafy'

Body:
sudo  pip3.6 install  pafy
Collecting pafy
  Downloading pafy-0.5.3.1.tar.gz
Installing collected packages: pafy
  Running setup.py install for pafy ... done
Successfully installed pafy-0.5.3.1

It is Successfully installed pafy-0.5.3.1.

~$ python
Python 3.6.1 |Anaconda 4.4.0 (64-bit)| (default, May 11 2017, 13:09:58)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.

>>> import pafy
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ModuleNotFoundError: No module named 'pafy'

Why no module named 'pafy'?

Body:
You ran pip as sudo but you're running python as normal user. Programs run as normal user don't have rights to access super-user's content (sudo).

To verify this, you can run python as super-user and try to import pafy.

$ sudo python
>>> import pafy

You should never use sudo pip install; you could overwrite important stuff.

Use pip install --user <packagename> or install and use virtualenv. I prefer virtualenv.


问:
LinQ Substring Function From the Right
Im new to linQ and I've got a problem

Question: if i have a string Example "MySTring"and I need the characters at positions 5 and 6 counting from the right of the string, ie: "ST"

here's my Query

Dim result = From everyval in AllVals
             where everyval.Substring(5,2)='ST'
             select everyval.Name

Now this wont return the correct values from the database because the default Consideration of positions in the Substring Function is from LEft to Right.
One Solution is maybe to reverse the String and then apply the Substring Function to it.
But how should i be doing this?

can someone tell me..???

答:
This is a rather strange requirement, usually an IndexOf/Contains is good enough for this. However, you could try (conceptually) truncating the value and testing the end using EndsWith.

Something like this perhaps (untested and probably doesn't work):

```<code>Dim result = from everyval in AllVals where everyval.Remove(4).EndsWidth("ST")
</code>```

MSDN nicely lists the string functions that can be safely translated to SQL from LINQ: http://msdn.microsoft.com/en-us/vbasic/bb688085

Title: LinQ Substring Function From the Right

Body:
This is a rather strange requirement, usually an IndexOf/Contains is good enough for this. However, you could try (conceptually) truncating the value and testing the end using EndsWith.

Something like this perhaps (untested and probably doesn't work):

Dim result = from everyval in AllVals where everyval.Remove(4).EndsWidth("ST")

MSDN nicely lists the string functions that can be safely translated to SQL from LINQ: http://msdn.microsoft.com/en-us/vbasic/bb688085


问:
How to make a custom system call in Google Native Client
I have made the necessary changes to the following files
irt_syscalls,
nacl_syscalls,
nacl_syscalls,
nacl_syscalls_common,
nacl_syscalls_handler_gen.py

but I get Undefined reference to NaClSysLibcall (the system call I'm trying to make) while compiling NaCl code

答:
since you are implementing a custom syscall, i'll assume you do not want to run inside of chrome and you just want to run code via sel_ldr.

IIRC the SDK, whether you want newlib or glibc, was built in the chromium tree, and getting the C syscall wrapper to build is probably going to be a pain since you'd need to fetch all of chromium; worse, the SDK source may have already been eradicated from the chromium tree.

an easier way might be to just write your own syscall wrapper that calls the address in the trampoline region that corresponds to the syscall.  you can disassemble an existing syscall wrapper to see what the code ought to look like.


答:
From the server side, the Socket (created by ServerSocket when a client connection is accepted) allows to read(receive) stream from the client with the input stream and to write(send) stream to the client with the output stream.

From the client side, it works with the same logic.

The Socket allows to read(receive) stream from the server with the input stream and to write(send) stream to the server with the output stream.

In your actual code :

```<code> Socket sock = servsock.accept();
 InputStream is = sock.getInputStream();
</code>```

Here you get the input stream of the server.

With it you can read message from the client.

For example to read a byte sent by the client (of course to read lines, using a more featured reader such as BufferedReader is much better):

```<code>int b = is.read();
</code>```

To write to the client one byte, the server can do  :

```<code> OutputStream os = sock.getOutputStream();
 os.write(oneByte);
</code>```

Here, same remark as for InputStream : OutputStream has only raw methods to write bytes.

Using a specific subclass could be better according to your requirements.

You have very good materials and examples on the Oracle site :
http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html

Title: How to identify the input for the server is of InputStream or Output stream

Body:
From the server side, the Socket (created by ServerSocket when a client connection is accepted) allows to read(receive) stream from the client with the input stream and to write(send) stream to the client with the output stream.

From the client side, it works with the same logic.

The Socket allows to read(receive) stream from the server with the input stream and to write(send) stream to the server with the output stream.

In your actual code :

 Socket sock = servsock.accept();
 InputStream is = sock.getInputStream();

Here you get the input stream of the server.

With it you can read message from the client.

For example to read a byte sent by the client (of course to read lines, using a more featured reader such as BufferedReader is much better):

int b = is.read();

To write to the client one byte, the server can do  :

 OutputStream os = sock.getOutputStream();
 os.write(oneByte);

Here, same remark as for InputStream : OutputStream has only raw methods to write bytes.

Using a specific subclass could be better according to your requirements.

You have very good materials and examples on the Oracle site :
http://docs.oracle.com/javase/tutorial/networking/sockets/clientServer.html


问:
pass PHP variable to javascript value
I want to display my PHP variable to JavaScript value
Here is my PHP and javascript code.

```<code><?php
$text = "Rates are subject to change without prior notice";
?>
<script>
    $('#typewriter').typewriter({
        prefix : "*** ",
        text : ["Rates are subject to change without prior notice"],
        typeDelay : 50,
        waitingTime : 1500,
        blinkSpeed : 200
    });
</script>
</code>```

inside the text parameter i want to pass my PHP variable.

答:
```<code><?php
$text = "Rates are subject to change without prior notice";
?>
<script>
    $('#typewriter').typewriter({
        prefix : "*** ",
        text : [<?php echo $text; ?>],
        typeDelay : 50,
        waitingTime : 1500,
        blinkSpeed : 200
    });
</script>
</code>```

Title: pass PHP variable to javascript value

Body:
I want to display my PHP variable to JavaScript value
Here is my PHP and javascript code.

<?php
$text = "Rates are subject to change without prior notice";
?>

inside the text parameter i want to pass my PHP variable.


问:
Write dropdown value to SQL table field
Creating a dropdown into a PHP form where the value of this dropdown should be written to SQL table field.

I'm almost certain the issue is this piece name="txtStatus" value="<?php echo $dataSt['Opt'];?>"> but I can't get it to work.

EDITED
This the code of the edit.php, now I'm able to get the drop-down, down on the page, to work but the values in the $result["Status"] aren't sent to the save.php file and of course neither to the SQL database table field.

```<code><html>
<head>
<title>TEST EDIT</title>
</head>
<style type="text/css">
@import url(http://fonts.googleapis.com/css?family=Roboto:400,500,700,300,100);
body {
  background-color: #576370;
  font-family: "Roboto", helvetica, arial, sans-serif;
  font-size: 16px;
  font-weight: 400;
  text-rendering: optimizeLegibility;
}

div.table-title {
  text-align:center;
  display: block;
  margin: auto;
  width: 100%;
}

.table-title h3 {
   color: #fafafa;
   padding:1px;
   font-size: 25px;
   font-weight: 300;
   font-style:normal;
   font-family: "Roboto", helvetica, arial, sans-serif;
   text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.1);
   text-transform:uppercase;
}

.table-title h2 {
   color: #D8D8D8;
   font-size: 10px;
   font-weight: 50;
   font-style:normal;
   text-transform:uppercase;
}

.table-title h4 {
   color: #F3F781;
   font-size: 10px;
   font-weight: 50;
   font-style:normal;
   text-transform:uppercase;
}

/*** Table Styles **/

.table-fill {
  background: white;
  border-radius:3px;
  border-collapse: collapse;
  height: 15px;
  margin: auto;
  padding:1px;
  width: 100%;
  box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
  animation: float 8s infinite;
}

th {
  color:#D5DDE5;
  text-align:left;
  background:#1b1e24;
  border-right: 1px solid #343a45;
  font-size:14px;
  font-weight: 50;
  padding:8px;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.1);
  vertical-align:middle;
  width: 100px;
}

th:first-child {
  border-top-left-radius:3px;

}

th:last-child {
  border-top-right-radius:3px;
  border-right:none;
}

tr {
  border-top: 1px solid #C1C3D1;
  border-bottom-: 1px solid #C1C3D1;
  color:#666B85;
  font-size:16px;
  font-weight:normal;
  text-shadow: 0 1px 1px rgba(256, 256, 256, 0.1);
}

tr:hover td {
  background:#4E5066;
  color:#FFFFFF;
  border-top: 0px solid #22262e;
  border-bottom: 0px solid #22262e;
}

tr:first-child {
  border-top:none;
}

tr:last-child {
  border-bottom:none;
}

tr:nth-child(odd) td {
  background:#EBEBEB;
}

tr:nth-child(odd):hover td {
  background:#4E5066;

}

tr:last-child td:first-child {
  border-bottom-left-radius:3px;
}

tr:last-child td:last-child {
  border-bottom-right-radius:3px;
}

td {
  background:#FFFFFF;
  padding:8px;
  vertical-align:middle;
  font-weight:300;
  font-size:14px;
  text-shadow: -1px -1px 1px rgba(0, 0, 0, 0.1);
  border-right: 1px solid #C1C3D1;
}

.show {display:block;}
</style>
</head>
<body>
<div class="table-title">
    <h3>SCANIA FINANCE</h3>
<body>

<?php
   ini_set('display_errors', 1);
   error_reporting(~0);

    $serverName = 'localhost';
    $userName = 'user';
    $userPassword = 'password';
    $dbName = 'AdWorks';

   $strBusinessEntityID = null;

   if(isset($_GET["BusinessEntityID"]))
   {
       $strBusinessEntityID = $_GET["BusinessEntityID"];
   }

   $connectionInfo = array("Database"=>$dbName, "UID"=>$userName, "PWD"=>$userPassword, "MultipleActiveResultSets"=>true);

   $conn = sqlsrv_connect( $serverName, $connectionInfo);

   if( $conn === false ) {
      die( print_r( sqlsrv_errors(), true));
   }

    $stmt = "SELECT * FROM tKelvin32 WHERE BusinessEntityID = ? ";
    $params = array($strBusinessEntityID);

    $query = sqlsrv_query( $conn, $stmt, $params);

    $result = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC);

?>
<form action="save_bck.php" name="frmAdd" method="post">
<table align="center">
  <tr>
    <th width="120">BusinessEntityID</th>
    <td><input type="hidden" name="txtBusinessEntityID" value="<?php echo $result["BusinessEntityID"];?>"><?php echo $result["BusinessEntityID"];?></td>
    </tr>
  <tr>
    <th width="120">FirstName</th>
    <td><input type="hidden" name="txtFirstName" value="<?php echo $result["FirstName"];?>"><?php echo $result["FirstName"];?></td>
    </tr>
  <tr>
    <th width="120">LastName</th>
    <td><input type="hidden" name="txtLastName" size="25" value="<?php echo $result["LastName"];?>"><?php echo $result["LastName"];?></td>
    </tr>
  <tr>
    <th width="120">JobTitle</th>
    <td><input type="hidden" name="txtJobTitle" value="<?php echo $result["JobTitle"];?>"><?php echo $result["JobTitle"];?></td>
    </tr>
  <tr>
    <th width="120">PhoneNumber</th>
    <td><input type="hidden" name="txtPhoneNumber" value="<?php echo $result["PhoneNumber"];?>"><?php echo $result["PhoneNumber"];?></td>
    </tr>
  <tr>
    <th width="120">PhoneNumberType</th>
    <td><input type="hidden" name="txtPhoneNumberType" value="<?php echo $result["PhoneNumberType"];?>"><?php echo $result["PhoneNumberType"];?></td>
    </tr>
    <tr>
    <th width="120">EmailAddress</th>
    <td><input type="hidden" name="txtEmailAddress" value="<?php echo $result["EmailAddress"];?>"><?php echo $result["EmailAddress"];?></td>
    </tr>
    <tr>
    <th width="120">AddressLine1</th>
    <td><input type="hidden" name="txtAddressLine1" value="<?php echo $result["AddressLine1"];?>"><?php echo $result["AddressLine1"];?></td>
    </tr>
    <tr>
    <th width="120">City</th>
    <td><input type="hidden" name="txtCity" value="<?php echo $result["City"];?>"><?php echo $result["City"];?></td>
    </tr>
    <tr>
    <th width="120">PostalCode</th>
    <td><input type="hidden" name="txtPostalCode" value="<?php echo $result["PostalCode"];?>"><?php echo $result["PostalCode"];?></td>
    </tr>
    <tr>
    <th width="120">CountryRegionName</th>
    <td><input type="hidden" name="txtCountryRegionName" value="<?php echo $result["CountryRegionName"];?>"><?php echo $result["CountryRegionName"];?></td>
    </tr>
    <tr>
    <th width="120">Status</th>
    <td>
    <input type="hidden" name="txtStatus" value="<?php echo $result["Status"];?>"><select name="TowerSelect"><option> Choose </option>
    <?php
    //STATUS Query
    $sqlSt = "SELECT DISTINCT Opt FROM StatsOptions ORDER BY Opt";
    $resultSt = sqlsrv_query($conn,$sqlSt) or die("Couldn't execut query");
    while ($dataSt=sqlsrv_fetch_array($resultSt, SQLSRV_FETCH_ASSOC)){
    echo '<option value="'.$dataSt['Opt'].'">';
    echo $dataSt['Opt'];
    echo "</option>";
    }
    ?>
    </select>
    </td>
    </tr>
  </table>
  <input type="submit" name="submit" value="submit">
</form>
<?php
sqlsrv_close($conn);
?>
</body>
</html>
</code>```

答:
You forget to close the select tag. Close your select tag after closing php tag.

```<code>...</select>....
</code>```

And see if you get the dropdown value after form submit.

Title: Write dropdown value to SQL table field

Body:
Creating a dropdown into a PHP form where the value of this dropdown should be written to SQL table field.

I'm almost certain the issue is this piece name="txtStatus" value="<?php echo $dataSt['Opt'];?>"> but I can't get it to work.

EDITED
This the code of the edit.php, now I'm able to get the drop-down, down on the page, to work but the values in the $result["Status"] aren't sent to the save.php file and of course neither to the SQL database table field.

<title>TEST EDIT</title>

SCANIA FINANCE

<?php
   ini_set('display_errors', 1);
   error_reporting(~0);

    $serverName = 'localhost';
    $userName = 'user';
    $userPassword = 'password';
    $dbName = 'AdWorks';

   $strBusinessEntityID = null;

   if(isset($_GET["BusinessEntityID"]))
   {
       $strBusinessEntityID = $_GET["BusinessEntityID"];
   }

   $connectionInfo = array("Database"=>$dbName, "UID"=>$userName, "PWD"=>$userPassword, "MultipleActiveResultSets"=>true);

   $conn = sqlsrv_connect( $serverName, $connectionInfo);

   if( $conn === false ) {
      die( print_r( sqlsrv_errors(), true));
   }

    $stmt = "SELECT * FROM tKelvin32 WHERE BusinessEntityID = ? ";
    $params = array($strBusinessEntityID);

    $query = sqlsrv_query( $conn, $stmt, $params);

    $result = sqlsrv_fetch_array($query, SQLSRV_FETCH_ASSOC);

?>
<form action="save_bck.php" name="frmAdd" method="post">

    BusinessEntityID
    <input type="hidden" name="txtBusinessEntityID" value="<?php echo $result["BusinessEntityID"];?>"><?php echo $result["BusinessEntityID"];?>

    FirstName
    <input type="hidden" name="txtFirstName" value="<?php echo $result["FirstName"];?>"><?php echo $result["FirstName"];?>

    LastName
    <input type="hidden" name="txtLastName" size="25" value="<?php echo $result["LastName"];?>"><?php echo $result["LastName"];?>

    JobTitle
    <input type="hidden" name="txtJobTitle" value="<?php echo $result["JobTitle"];?>"><?php echo $result["JobTitle"];?>

    PhoneNumber
    <input type="hidden" name="txtPhoneNumber" value="<?php echo $result["PhoneNumber"];?>"><?php echo $result["PhoneNumber"];?>

    PhoneNumberType
    <input type="hidden" name="txtPhoneNumberType" value="<?php echo $result["PhoneNumberType"];?>"><?php echo $result["PhoneNumberType"];?>

    EmailAddress
    <input type="hidden" name="txtEmailAddress" value="<?php echo $result["EmailAddress"];?>"><?php echo $result["EmailAddress"];?>

    AddressLine1
    <input type="hidden" name="txtAddressLine1" value="<?php echo $result["AddressLine1"];?>"><?php echo $result["AddressLine1"];?>

    City
    <input type="hidden" name="txtCity" value="<?php echo $result["City"];?>"><?php echo $result["City"];?>

    PostalCode
    <input type="hidden" name="txtPostalCode" value="<?php echo $result["PostalCode"];?>"><?php echo $result["PostalCode"];?>

    CountryRegionName
    <input type="hidden" name="txtCountryRegionName" value="<?php echo $result["CountryRegionName"];?>"><?php echo $result["CountryRegionName"];?>

    Status

    <input type="hidden" name="txtStatus" value="<?php echo $result["Status"];?>"><select name="TowerSelect"><option> Choose </option>
    <?php
    //STATUS Query
    $sqlSt = "SELECT DISTINCT Opt FROM StatsOptions ORDER BY Opt";
    $resultSt = sqlsrv_query($conn,$sqlSt) or die("Couldn't execut query");
    while ($dataSt=sqlsrv_fetch_array($resultSt, SQLSRV_FETCH_ASSOC)){
    echo '<option value="'.$dataSt['Opt'].'">';
    echo $dataSt['Opt'];
    echo "</option>";
    }
    ?>
    </select>

  <input type="submit" name="submit" value="submit">
</form>
<?php
sqlsrv_close($conn);
?>

Body:
You forget to close the select tag. Close your select tag after closing php tag.

...</select>....

And see if you get the dropdown value after form submit.


问:
What tools are built using themselves?
I am curious about what tools are used to build the next version of themselves.

For example, Delphi has long claimed that "Delphi is written in Delphi".

I assume Visual Studio is written using Visual Studio.

What are some other examples of tools that written in themselves?

答: It is fairly typical to have a languages compiler written in its own language.  This is called self-hosting or bootstrapping.</p>

OwnerDisplayName: kogus

Title: What tools are built using themselves?

LastEditorDisplayName: kogus

OwnerDisplayName: Simucal


问:
Can I open a dropdownlist using jQuery
For this dropdownlist in HTML:

```<code><select id="countries">
<option value="1">Country</option>
</select>
</code>```

I would like to open the list (the same as left-clicking on it). Is this possible using JavaScript (or more specifically jQuery)?

答:
I was trying to find the same thing and got disappointed.
I ended up changing the attribute size for the select box so it appears to open

```<code>$('#countries').attr('size',6);
</code>```

and then when you're finished

```<code>$('#countries').attr('size',1);
</code>```

OwnerDisplayName: Jon T

Title: Can I open a dropdownlist using jQuery

Body:
For this dropdownlist in HTML:

<select id="countries">
<option value="1">Country</option>
</select>

I would like to open the list (the same as left-clicking on it). Is this possible using JavaScript (or more specifically jQuery)?

Body:
I was trying to find the same thing and got disappointed.
I ended up changing the attribute size for the select box so it appears to open

$('#countries').attr('size',6);

and then when you're finished

$('#countries').attr('size',1);


问:
Cannot use commands 'postgres' or 'pg_ctl'
I am on Unix. I have got postgresql-9.3 installed.

When I want to start the server using pg_ctl or postgres, the terminal gives me:

```
The program 'postgres' is currently not installed. You can install it by typing:
sudo apt-get install postgres-xc
```

Can't I start the server without this postgres-xc?

答:
You must install postgresql-client:

sudo install postgresql-client

Try to enter this command to the console:

sudo -u postgres psql

Body:
I am on Unix. I have got postgresql-9.3 installed.

When I want to start the server using pg_ctl or postgres, the terminal gives me:

The program 'postgres' is currently not installed. You can install it by typing:
sudo apt-get install postgres-xc

Can't I start the server without this postgres-xc?


问:
get line number and filename for a log output
Is it possible to get the line number and file for each log output ?

For example:

```<code>  var winston = require('winston');

  winston.log('info', 'some message!'); // this is at line 4 of myfile.js
</code>```

should specify in log file that 'some message' came from myFile.js line 4.

答:
You can pass the file name as label and you can get the file name from callingModule.

Create logger.js file and code like

```<code>var winston = require('winston');
var getLabel = function (callingModule) {
    var parts = callingModule.filename.split('/');
    return parts[parts.length - 2] + '/' + parts.pop();
};

module.exports = function (callingModule) {
    return new winston.Logger({
        transports: [
            new winston.transports.Console({
                label: getLabel(callingModule),
                json: false,
                timestamp: true,
                depth:true,
                colorize:true
            })
        ]
    });
};
</code>```

Now Here your test file

```<code>var logger = require('./logger')(module);
function test() {
    logger.info('test logger');
}
test();
</code>```

and if you run test file than the output looks like

```<code>2017-07-08T07:15:20.671Z - info: [utils/test.js] test logger
</code>```

Body:
Is it possible to get the line number and file for each log output ?

For example:

  var winston = require('winston');

  winston.log('info', 'some message!'); // this is at line 4 of myfile.js

should specify in log file that 'some message' came from myFile.js line 4.

Body:
You can pass the file name as label and you can get the file name from callingModule.

Create logger.js file and code like

var winston = require('winston');
var getLabel = function (callingModule) {
    var parts = callingModule.filename.split('/');
    return parts[parts.length - 2] + '/' + parts.pop();
};

module.exports = function (callingModule) {
    return new winston.Logger({
        transports: [
            new winston.transports.Console({
                label: getLabel(callingModule),
                json: false,
                timestamp: true,
                depth:true,
                colorize:true
            })
        ]
    });
};

Now Here your test file

var logger = require('./logger')(module);
function test() {
    logger.info('test logger');
}
test();

and if you run test file than the output looks like

2017-07-08T07:15:20.671Z - info: [utils/test.js] test logger