问:
How to parse xml file using XMLReader
I have a "contacts.xml" file, its structure is:

```<code><?xml version="1.0" encoding="UTF-8"?>
<Contacts>
   <Contact>
      <ContactId>1</ContactId>
      <ContactName>Aditya  Kothari</ContactName>
      <MobilePhone1>NA</MobilePhone1>
      <MobilePhone2>NA</MobilePhone2>
      <OfficePhone1>NA</OfficePhone1>
      <OfficePhone2>NA</OfficePhone2>
      <OfficePhone3>NA</OfficePhone3>
      <HomePhone1>999-367-3944</HomePhone1>
      <HomePhone2>NA</HomePhone2>
      <TokenId>mtn</TokenId>
   </Contact>
   <Contact>
      <ContactId>2</ContactId>
      <ContactName>Jai  Mandloi </ContactName>
      <MobilePhone1>NA</MobilePhone1>
      <MobilePhone2>NA</MobilePhone2>
      <OfficePhone1>NA</OfficePhone1>
      <OfficePhone2>NA</OfficePhone2>
      <OfficePhone3>NA</OfficePhone3>
      <HomePhone1>800-742-9678</HomePhone1>
      <HomePhone2>NA</HomePhone2>
      <TokenId>mtn</TokenId>
   </Contact>
</Contacts>
</code>```

Now i am doing this-

```<code>File xmlFile = new File("E:\\contacts.xml");
InputStream is = new FileInputStream(xmlFile);
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(is);
while(reader.hasNext())
{
    if(reader.hasText()
    {
        System.out.println(reader.getText());
    }
    reader.next();
}
</code>```

I do not want values of "ContactId" and "TokenId" elements of xml.
How should i code?

答: You can get lots of information fem here:http://www.ibm.com/developerworks/opensource/library/x-android/</p>

Title: How to parse xml file using XMLReader

Body:
I have a "contacts.xml" file, its structure is:

<?xml version="1.0" encoding="UTF-8"?>
<Contacts>
   <Contact>
      <ContactId>1</ContactId>
      <ContactName>Aditya  Kothari</ContactName>
      <MobilePhone1>NA</MobilePhone1>
      <MobilePhone2>NA</MobilePhone2>
      <OfficePhone1>NA</OfficePhone1>
      <OfficePhone2>NA</OfficePhone2>
      <OfficePhone3>NA</OfficePhone3>
      <HomePhone1>999-367-3944</HomePhone1>
      <HomePhone2>NA</HomePhone2>
      <TokenId>mtn</TokenId>
   </Contact>
   <Contact>
      <ContactId>2</ContactId>
      <ContactName>Jai  Mandloi </ContactName>
      <MobilePhone1>NA</MobilePhone1>
      <MobilePhone2>NA</MobilePhone2>
      <OfficePhone1>NA</OfficePhone1>
      <OfficePhone2>NA</OfficePhone2>
      <OfficePhone3>NA</OfficePhone3>
      <HomePhone1>800-742-9678</HomePhone1>
      <HomePhone2>NA</HomePhone2>
      <TokenId>mtn</TokenId>
   </Contact>
</Contacts>

Now i am doing this-

File xmlFile = new File("E:\\contacts.xml");
InputStream is = new FileInputStream(xmlFile);
XMLInputFactory factory = XMLInputFactory.newInstance();
XMLStreamReader reader = factory.createXMLStreamReader(is);
while(reader.hasNext())
{
    if(reader.hasText()
    {
        System.out.println(reader.getText());
    }
    reader.next();
}

I do not want values of "ContactId" and "TokenId" elements of xml.
How should i code?


来源: stackexchange

问:
Get Guideline percent size in pixels programmatically
I have a GuideLine, 15% off the left of the page.

I can get a percentage of it in this code:

```<code>float percent = ((ConstraintLayout.LayoutParams) guideline.getLayoutParams()).guidePercent;
</code>```

Output: 0.15

How can I get pixel or dpi values?

答:
Am not find any direct conversion percentage to dp formula because phone dp is varied for multiple screen.but i have simple logic to get that value  in dp.

1) Calculate the screen width (500dp)

2) calculate the percentage of your margin (15%) of the layout width

```<code>float  dpvalue=totalwidth * percentage

//500 *(0.15) =75(dpvalue)
</code>```

this logic will  work all devices size.

ContentLicense: CC BY-SA 3.0

Body:
I have a GuideLine, 15% off the left of the page.

I can get a percentage of it in this code:

float percent = ((ConstraintLayout.LayoutParams) guideline.getLayoutParams()).guidePercent;

Output: 0.15

How can I get pixel or dpi values?

Body:
Am not find any direct conversion percentage to dp formula because phone dp is varied for multiple screen.but i have simple logic to get that value  in dp.

1) Calculate the screen width (500dp)

2) calculate the percentage of your margin (15%) of the layout width

float  dpvalue=totalwidth * percentage

//500 *(0.15) =75(dpvalue)

this logic will  work all devices size.


问:
Query with multiple EXIST
I've got a database of rooms and equipments. I want to query the database and return a list of rooms with e.g. tv, radio, sat and fridge (eq1, eq2, eq3, ...., eqN).

I have the following SELECT statement:

```<code>select * from rooms r where
exists (select id from equipments where eq_id='eq1' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq2' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq3' and room_id=r.id)
.......
and
exists (select id from equipments where eq_id='eqN' and room_id=r.id)
</code>```

Is there any way to optimize or making this shorter?

答:
Use an Stored Procedure.

here is the procedure for mysql:

```<code>DELIMITER $$

CREATE DEFINER=`root`@`%` PROCEDURE `GetRooms`(IN roomtable TEXT, IN equipmenttable TEXT, IN equipments TEXT )
BEGIN
    DECLARE statement text;
    DECLARE Pos int;
    DECLARE cond text;
    DECLARE element text;
    DECLARE tmpTxt text;

    set tmpTxt = equipments;
    set cond = "";
    set Pos = instr(tmpTxt,';');
    while Pos <> 0 do
    set element = substring(tmpTxt, 1, Pos-1);

    if cond <> "" then
        set cond = concat(cond,' and ');
    end if;

    set cond = concat(cond,'exists (select id from ' , equipmenttable ,' where eq_id=''' ,  element ,''' and room_id=r.id) ');

    set tmpTxt = replace(tmpTxt, concat(element,';'), '');

    set Pos = instr(tmpTxt,';');
    end while;

    if tmpTxt <> "" then
        if cond <> "" then
            set cond = concat(cond,' and ');
        end if;

        set cond = concat(cond,'exists (select id from ' , equipmenttable ,' where eq_id=''' ,  tmpTxt ,''' and room_id=r.id) ');
    end if;

    SET @statement = concat('Select * FROM ' ,  roomtable , " WHERE " , cond , ";");

    PREPARE stmt FROM @statement;
    EXECUTE stmt;
END
</code>```

Execute it with: CALL GetRooms('RoomTableName','EquipmentTableName','EquipmentIDs')

Example:

```<code>Call GetRooms('rooms','equipemnts','eq1;eq2;eq3');
</code>```

Hope this helps.

ContentLicense: CC BY-SA 2.5

Title: Query with multiple EXIST

Body:
I've got a database of rooms and equipments. I want to query the database and return a list of rooms with e.g. tv, radio, sat and fridge (eq1, eq2, eq3, ...., eqN).

I have the following SELECT statement:

select * from rooms r where
exists (select id from equipments where eq_id='eq1' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq2' and room_id=r.id)
and
exists (select id from equipments where eq_id='eq3' and room_id=r.id)
.......
and
exists (select id from equipments where eq_id='eqN' and room_id=r.id)

Is there any way to optimize or making this shorter?

Body:
Use an Stored Procedure.

here is the procedure for mysql:

DELIMITER $$

CREATE DEFINER=`root`@`%` PROCEDURE `GetRooms`(IN roomtable TEXT, IN equipmenttable TEXT, IN equipments TEXT )
BEGIN
    DECLARE statement text;
    DECLARE Pos int;
    DECLARE cond text;
    DECLARE element text;
    DECLARE tmpTxt text;

    set tmpTxt = equipments;
    set cond = "";
    set Pos = instr(tmpTxt,';');
    while Pos <> 0 do
    set element = substring(tmpTxt, 1, Pos-1);

    if cond <> "" then
        set cond = concat(cond,' and ');
    end if;

    set cond = concat(cond,'exists (select id from ' , equipmenttable ,' where eq_id=''' ,  element ,''' and room_id=r.id) ');

    set tmpTxt = replace(tmpTxt, concat(element,';'), '');

    set Pos = instr(tmpTxt,';');
    end while;

    if tmpTxt <> "" then
        if cond <> "" then
            set cond = concat(cond,' and ');
        end if;

        set cond = concat(cond,'exists (select id from ' , equipmenttable ,' where eq_id=''' ,  tmpTxt ,''' and room_id=r.id) ');
    end if;

    SET @statement = concat('Select * FROM ' ,  roomtable , " WHERE " , cond , ";");

    PREPARE stmt FROM @statement;
    EXECUTE stmt;
END

Execute it with: CALL GetRooms('RoomTableName','EquipmentTableName','EquipmentIDs')

Example:

Call GetRooms('rooms','equipemnts','eq1;eq2;eq3');

Hope this helps.


问:
validation of email with specific domain
This coding on separate page works fine. but if i included in below form not working

<form id="signup" method="post">
    <input type="email" placeholder="Your e-mail." />
    <button>Submit</button>
</form>

```
</div>
</div>
</p>

<p><em>i have an registration page where  all fields are entered,it should check whether email id column should contain @c-e.com domain,if user entered abcd@c-e.com it should proceed or else should pop up a message like need to enter c-e.com domain name,for that i have written a script but for all email id's it is displaying message like not an valid email address.none of the part works.If i paste same code with form of email ,submit button alone in other page,it pops up message ,but in this register.php not works</em></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code><?php
session_start();

if(isset($_SESSION['usr_id'])) {
 header("Location: index.php");
}

include_once 'dbconnect.php';

//set validation error flag as false
$error = false;

//check if form is submitted
if (isset($_POST['signup'])) {
 $name = mysqli_real_escape_string($con, $_POST['name']);
 $email = mysqli_real_escape_string($con, $_POST['email']);
 $password = mysqli_real_escape_string($con, $_POST['password']);
 $cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);

 //name can contain only alpha characters and space
 if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
  $error = true;
  $name_error = "Name must contain only alphabets and space";
 }
 if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
  $error = true;
  $email_error = "Please Enter Valid Email ID";
 }
 if(strlen($password) < 6) {
  $error = true;
  $password_error = "Password must be minimum of 6 characters";
 }
 if($password != $cpassword) {
  $error = true;
  $cpassword_error = "Password and Confirm Password doesn't match";
 }
 if (!$error) {
  if(mysqli_query($con, "INSERT INTO users(name,email,password) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
   $successmsg = "Successfully Registered! Click here to Login";
  } else {
   $errormsg = "Error in registering...Please try again later!";
  }
 }
}
?>

<!DOCTYPE html>
<html>
<head>
 <title>User Registration Script</title>
 <meta content="width=device-width, initial-scale=1.0" name="viewport" >
 <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

 </head>
<body>
</br></br>

<div class="container">
 <div class="row">
  <div class="col-md-4 col-md-offset-4 well">
   <form role="form" id="signup" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="signupform">
    <fieldset>
     <legend>Sign Up</legend>

     <div class="form-group">
      <label for="name">Name</label>
      <input type="text" name="name" placeholder="Enter Full Name" required value="<?php if($error) echo $name; ?>" class="form-control" />
      <span class="text-danger"><?php if (isset($name_error)) echo $name_error; ?></span>
     </div>

     <div class="form-group">
      <label for="name">Email</label>
      <input type="email" name="email" placeholder="Email" required value="<?php if($error) echo $email; ?>" class="form-control" />
      <span class="text-danger"><?php if (isset($email_error)) echo $email_error; ?></span>
     </div>

     <div class="form-group">
      <label for="name">Password</label>
      <input type="password" name="password" placeholder="Password" required class="form-control" />
      <span class="text-danger"><?php if (isset($password_error)) echo $password_error; ?></span>
     </div>

     <div class="form-group">
      <label for="name">Confirm Password</label>
      <input type="password" name="cpassword" placeholder="Confirm Password" required class="form-control" />
      <span class="text-danger"><?php if (isset($cpassword_error)) echo $cpassword_error; ?></span>
     </div>

     <div class="form-group">
      <input type="submit" name="signup" value="Sign Up" class="btn btn-primary" />
     </div>
    </fieldset>
   </form>
   <span class="text-success"><?php if (isset($successmsg)) { echo $successmsg; } ?></span>
   <span class="text-danger"><?php if (isset($errormsg)) { echo $errormsg; } ?></span>
  </div>
 </div>
 <div class="row">
  <div class="col-md-4 col-md-offset-4 text-center">
  Already Registered? Login Here
  </div>
 </div>
</div>

<script type="text/javascript">

$('#signup').submit(function() {
    validateEmail($('input').val());
    return false;
});

function validateEmail(email) {
    var re = /^\s*[\w\-\+_]+(\.[\w\-\+_]+)*\@[\w\-\+_]+\.[\w\-\+_]+(\.[\w\-\+_]+)*\s*$/;
    if (re.test(email)) {
        if (email.indexOf('@c-e.com', email.length - '@c-e.com'.length) !== -1) {
            alert('Submission was successful.');
        } else {
            alert('Email must be a CE e-mail address (your.name@c-e.com).');
        }
    } else {
        alert('Not a valid e-mail address.');
    }
}

</script>

<script src="js/jquery-1.10.2.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html></code>```

答:
You wan't to explode the email and check if it contain what you want like this,</p>

```<code>$explode = explode("@", $email);
if($explode[1] == 'c-e.com'){
    //Email is valid
}else{
    //Email is not valid
}
</code>```

Body:
This coding on separate page works fine. but if i included in below form not working

<form id="signup" method="post">
    <input type="email" placeholder="Your e-mail." />
    <button>Submit</button>
</form>

i have an registration page where  all fields are entered,it should check whether email id column should contain @c-e.com domain,if user entered abcd@c-e.com it should proceed or else should pop up a message like need to enter c-e.com domain name,for that i have written a script but for all email id's it is displaying message like not an valid email address.none of the part works.If i paste same code with form of email ,submit button alone in other page,it pops up message ,but in this register.php not works

<?php
session_start();

if(isset($_SESSION['usr_id'])) {
 header("Location: index.php");
}

include_once 'dbconnect.php';

//set validation error flag as false
$error = false;

//check if form is submitted
if (isset($_POST['signup'])) {
 $name = mysqli_real_escape_string($con, $_POST['name']);
 $email = mysqli_real_escape_string($con, $_POST['email']);
 $password = mysqli_real_escape_string($con, $_POST['password']);
 $cpassword = mysqli_real_escape_string($con, $_POST['cpassword']);

 //name can contain only alpha characters and space
 if (!preg_match("/^[a-zA-Z ]+$/",$name)) {
  $error = true;
  $name_error = "Name must contain only alphabets and space";
 }
 if(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
  $error = true;
  $email_error = "Please Enter Valid Email ID";
 }
 if(strlen($password) < 6) {
  $error = true;
  $password_error = "Password must be minimum of 6 characters";
 }
 if($password != $cpassword) {
  $error = true;
  $cpassword_error = "Password and Confirm Password doesn't match";
 }
 if (!$error) {
  if(mysqli_query($con, "INSERT INTO users(name,email,password) VALUES('" . $name . "', '" . $email . "', '" . md5($password) . "')")) {
   $successmsg = "Successfully Registered! Click here to Login";
  } else {
   $errormsg = "Error in registering...Please try again later!";
  }
 }
}
?>

<!DOCTYPE html>

 <title>User Registration Script</title>
 <meta content="width=device-width, initial-scale=1.0" name="viewport" >
 <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />

   <form role="form" id="signup" action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" name="signupform">
    <fieldset>
     <legend>Sign Up</legend>

      Name
      <input type="text" name="name" placeholder="Enter Full Name" required value="<?php if($error) echo $name; ?>" class="form-control" />
      <?php if (isset($name_error)) echo $name_error; ?>

      Email
      <input type="email" name="email" placeholder="Email" required value="<?php if($error) echo $email; ?>" class="form-control" />
      <?php if (isset($email_error)) echo $email_error; ?>

      Password
      <input type="password" name="password" placeholder="Password" required class="form-control" />
      <?php if (isset($password_error)) echo $password_error; ?>

      Confirm Password
      <input type="password" name="cpassword" placeholder="Confirm Password" required class="form-control" />
      <?php if (isset($cpassword_error)) echo $cpassword_error; ?>

      <input type="submit" name="signup" value="Sign Up" class="btn btn-primary" />

    </fieldset>
   </form>
   <?php if (isset($successmsg)) { echo $successmsg; } ?>
   <?php if (isset($errormsg)) { echo $errormsg; } ?>

  Already Registered? Login Here

Body:
You wan't to explode the email and check if it contain what you want like this,

$explode = explode("@", $email);
if($explode[1] == 'c-e.com'){
    //Email is valid
}else{
    //Email is not valid
}


问:
How to get all sub folders and its files - UWP
I have a fixed folder in desktop called student_names. it contains sub folders and each sub folders contains its files. Now I want to store those sub folders and its corresponding file names in an array list. how is it possible?</p>

答: Unfortunately, that may not be possible. It's been a while since I last worked on UWP apps, but it was not possible to access file system outside a few designated folders (e.g., app folder and a few other special folders like Document, Music, Picture, etc., if your app declares proper permissions). You cannot access folders on Desktop or C:\ folder in general.</p>


问:
How can a function return multiple columns?
I want to create a function that returns multiple varchar2 columns. his is what I have so far, but it errors on the execute immediate call.

```<code>FUNCTION FNC_LST_OUR(p_com_code   varchar2,
                     p_from  varchar2,
                     p_to    varchar2
                     ) return VARCHAR2 is

v_sql VARCHAR2(30000) := '';
v_sql2 VARCHAR2(30000) := '';
error_msg_tmp varchar2(255);

begin
      v_sql := 'select s.com_code, s.p_code, count(*) as Num_SIMRP
                from p_stest s
                where s.com_code = ''' || p_com_code || '''
                and s.s_status = ''ACTIVE''
                and s.s_type like ''H%'' ';
      if p_from is not null then
        v_sql := v_sql || ' and s.p_code between ''' || p_from || ''' and ''' || p_to || '''';
      end if;
        v_sql := v_sql || ' group by s.com_code,s.p_code
                            having count(s.p_code)> 0 ';

      EXECUTE IMMEDIATE v_sql INTO v_sql2 USING p_com_code; --> Error This Line
      return v_sql2;
end;
</code>```

I need it to return multiple columns like:

```<code>com_code | p_code | num_simrp
A        | ADSWQ  | 14
A        | AQWSA  | 8
A        | DEWSQ  | 10
A        | SDERS  | 45
A        | DFDEW  | 80
</code>```

I must create the function in a package and inner join the result as part of a query.

答:
```<code>create or replace type  test_type as object(t_owner varchar2(2000),t_originator varchar2(2000),
t_modify_dat timestamp,t_create_date  timestamp);

create or replace type  test_table is table of test_type;

create or replace function test_fn(table_name varchar2)
return test_table
as
test_var test_table:=test_table();
t_owner varchar2(2000);
t_originator varchar2(2000);
t_modify_date timestamp;
t_create_date timestamp;
begin

      execute immediate 'select  "OWNER","ORIGINATOR","MODIFIED","ORIGINATED"   from '|| table_name ||'
           where  revision = 1 and "TYPE" like ''gecPowder'' and "NAME" like ''GE2009-0653'''
           into t_owner,t_originator,t_modify_date,t_create_date;
           test_var.extend();
           --DBMS_OUTPUT.PUT_line(t_owner||t_originator||t_modify_date||t_create_date);
           select test_type(t_owner,t_originator,t_modify_date,t_create_date) bulk collect into test_var from dual;
           return test_var;
           end;
</code>```

Body:
I want to create a function that returns multiple varchar2 columns. his is what I have so far, but it errors on the execute immediate call.

FUNCTION FNC_LST_OUR(p_com_code   varchar2,
                     p_from  varchar2,
                     p_to    varchar2
                     ) return VARCHAR2 is

v_sql VARCHAR2(30000) := '';
v_sql2 VARCHAR2(30000) := '';
error_msg_tmp varchar2(255);

begin
      v_sql := 'select s.com_code, s.p_code, count(*) as Num_SIMRP
                from p_stest s
                where s.com_code = ''' || p_com_code || '''
                and s.s_status = ''ACTIVE''
                and s.s_type like ''H%'' ';
      if p_from is not null then
        v_sql := v_sql || ' and s.p_code between ''' || p_from || ''' and ''' || p_to || '''';
      end if;
        v_sql := v_sql || ' group by s.com_code,s.p_code
                            having count(s.p_code)> 0 ';

      EXECUTE IMMEDIATE v_sql INTO v_sql2 USING p_com_code; --> Error This Line
      return v_sql2;
end;

I need it to return multiple columns like:

com_code | p_code | num_simrp
A        | ADSWQ  | 14
A        | AQWSA  | 8
A        | DEWSQ  | 10
A        | SDERS  | 45
A        | DFDEW  | 80

I must create the function in a package and inner join the result as part of a query.


问:
Docker copy a file from host to Container?
How to copy a file from host to a Docker Container?
 Docker cp is used to copy from container to host but I am not getting any option to copy from host to Container</p>

答:
Docker cp can be used to copy file from container to host, and host to container as well.

Conteiner to host: sudo docker cp da9230faeb38:/file ./

Host to container: sudo docker cp Desktop/file da9230faeb38:/


问:
input type="number" is not able to delete/clear on selecting the number in Firefox and IE
I have validation to accept the min and max value for an input type="number" field. Once I entered some input it is working according to the max and min value. What is my problem is I could not able to clear/delete an entered value in the number field. In textbox field, it is allowing to clear the value by using backspace and selecting the number and type new number. why number field is not working in that scenario. how to make it clear/delete the number in the number field.

```<code>  <input type="number" name="WorkingDaysPA" id="WorkingDaysPA"
             min="1" max="366" style="text-align: right"

             onkeypress="if(this.value.length==3) return false;return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57"
         />

<input type="text" maxlength="3" min="1" max="366">
</code>```

Here My fiddle: https://jsfiddle.net/MariNithya/fpd2y4f4/

答:
On focus out event, I am assiging null as value;

Hope this helps

document.getElementById("validateNums").addEventListener("focusout", inputOutOfFocus);
function inputOutOfFocus() {
 document.getElementById("validateNums").value = null;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="number" maxlength="3" min="1" max="366" id="validateNums"></code>```

ContentLicense: CC BY-SA 4.0

Body:
I have validation to accept the min and max value for an input type="number" field. Once I entered some input it is working according to the max and min value. What is my problem is I could not able to clear/delete an entered value in the number field. In textbox field, it is allowing to clear the value by using backspace and selecting the number and type new number. why number field is not working in that scenario. how to make it clear/delete the number in the number field.

  <input type="number" name="WorkingDaysPA" id="WorkingDaysPA"
             min="1" max="366" style="text-align: right"

             onkeypress="if(this.value.length==3) return false;return (event.charCode == 8 || event.charCode == 0) ? null : event.charCode >= 48 && event.charCode <= 57"
         />

<input type="text" maxlength="3" min="1" max="366">

Here My fiddle: https://jsfiddle.net/MariNithya/fpd2y4f4/

Body:
On focus out event, I am assiging null as value;

Hope this helps

document.getElementById("validateNums").addEventListener("focusout", inputOutOfFocus);
function inputOutOfFocus() {
 document.getElementById("validateNums").value = null;
}

<input type="number" maxlength="3" min="1" max="366" id="validateNums">


问:
Renaming path helpers in Rails 3 routing
I have a projects controller/model. Instead of listing projects on the #index page, I show a list of drop downs, which submits to projects#select, which finds the right Project (I've made sure there can only be 1 for each combination of options) and forwards the user to the #show page for that Project.

So for my routes I do this...

```<code>resources :projects, :only => [:index, :show] do
  collection do
    get 'select'
  end
end
</code>```

And thats fine, but the helper method for #select is 'select_projects', which is understandable but in my case I really want 'select_project'. And I really don't want to alias this in another file. No problem I can use :as...

```<code>resources :projects, :only => [:index, :show] do
  collection do
    get 'select', :as => 'select_project'
  end
end
</code>```

But now my helper is 'select_project_projects'. So I cheat a little (still better than aliasing in another file)...

```<code>resources :projects, :only => [:index, :show]
match '/projects/select', :to => 'projects#select', :as => 'select_project'
</code>```

This looks like it might work, but it doesn't because /project/select actually matches the route for 'project#show'.  Changing the order of the lines does the trick.

```<code>match '/projects/select', :to => 'projects#select', :as => 'select_project'
resources :projects, :only => [:index, :show]
</code>```

But is there a more elegant way of handling this?  I realize this is borderline OCD, but I'd like to be able to have complete control over the route name within the resources block.

答: use resource instead of resources</p>

Body:
I have a projects controller/model. Instead of listing projects on the #index page, I show a list of drop downs, which submits to projects#select, which finds the right Project (I've made sure there can only be 1 for each combination of options) and forwards the user to the #show page for that Project.

So for my routes I do this...

resources :projects, :only => [:index, :show] do
  collection do
    get 'select'
  end
end

And thats fine, but the helper method for #select is 'select_projects', which is understandable but in my case I really want 'select_project'. And I really don't want to alias this in another file. No problem I can use :as...

resources :projects, :only => [:index, :show] do
  collection do
    get 'select', :as => 'select_project'
  end
end

But now my helper is 'select_project_projects'. So I cheat a little (still better than aliasing in another file)...

resources :projects, :only => [:index, :show]
match '/projects/select', :to => 'projects#select', :as => 'select_project'

This looks like it might work, but it doesn't because /project/select actually matches the route for 'project#show'.  Changing the order of the lines does the trick.

match '/projects/select', :to => 'projects#select', :as => 'select_project'
resources :projects, :only => [:index, :show]

But is there a more elegant way of handling this?  I realize this is borderline OCD, but I'd like to be able to have complete control over the route name within the resources block.

Body: use resource instead of resources


问:
How to change part of HTML 'form action: link' elements using Java script or html ID
I have a link to a database in the server and I'm using an HTML form where the action points to the link and GET the information from the server.

I need to change the 'username' part of the link so that it takes in the username i enter and uses it in the link.
What's the best way to achieve something like this?

```<code><body>

        <form id = "me" action= "http://10.10.10.10/foods/<username>/" target="_blank"  method="GET">
            <h2>Enter Username</h2>
                <input type="text" name="user" placeholder="username" id = "user" >
                <br>
            <button class="button" type="submit" value="Submit" >get</button>
        </form>
        <script>
          var username = //need to get input username;
           document.getElementById('me').action = "http://10.10.10.10/foods/" + username + "/";
</script>
</BODY>
</code>```

this is all i have so far and i am stuck

答:
```<code><script>
    var username = document.getElementById("me").action;
    var updatedStr = username.replace("<username>", "action name");
    document.getElementById("myForm").action = updatedStr;
</script>
</code>```

Body:
I have a link to a database in the server and I'm using an HTML form where the action points to the link and GET the information from the server.

I need to change the 'username' part of the link so that it takes in the username i enter and uses it in the link.
What's the best way to achieve something like this?

        <form id = "me" action= "http://10.10.10.10/foods/<username>/" target="_blank"  method="GET">

Enter Username

                <input type="text" name="user" placeholder="username" id = "user" >

            <button class="button" type="submit" value="Submit" >get</button>
        </form>

this is all i have so far and i am stuck


问:
exec not properly executing php command centos 7
using

xls2csv -x /usr/share/nginx/html/price_list_EN.xls -s cp1252 -d 8859-1 > /usr/share/nginx/html/price_list_EN.csv

in linux commandline it works and exports it correctly, but if I use it on php

```<code>$transf2 = "xls2csv -x /usr/share/nginx/html/price_list_EN.xls -s cp1252 -d 8859-1 > /usr/share/nginx/html/price_list_EN.csv";

exec($transf2);
</code>```

a file named price_list_EN.csv appears but it remains empty...

答:
Try to execute your command like this from shell

```<code>su -s /bin/bash -c "xls2csv -x /usr/share/nginx/html/price_list_EN.xls -s cp1252 -d 8859-1 > /usr/share/nginx/html/price_list_EN.csv" www-data(your webserver user name)
</code>```

then you debug the error

Body:
using

xls2csv -x /usr/share/nginx/html/price_list_EN.xls -s cp1252 -d 8859-1 > /usr/share/nginx/html/price_list_EN.csv

in linux commandline it works and exports it correctly, but if I use it on php

$transf2 = "xls2csv -x /usr/share/nginx/html/price_list_EN.xls -s cp1252 -d 8859-1 > /usr/share/nginx/html/price_list_EN.csv";

exec($transf2);

a file named price_list_EN.csv appears but it remains empty...

Body:
Try to execute your command like this from shell

su -s /bin/bash -c "xls2csv -x /usr/share/nginx/html/price_list_EN.xls -s cp1252 -d 8859-1 > /usr/share/nginx/html/price_list_EN.csv" www-data(your webserver user name)

then you debug the error


问:
make_path does not set mode as specified
When I call make_path (from the core File::Path module, supplying a mode, the directory that is created does not have the mode I requested:

```<code>$ perl -MFile::Path=make_path -e 'make_path("foobar", { mode=>0770 });'
$ ls -ld foobar/
drwxr-x--- 2 itk itkadm 4096 Sep 19 11:10 foobar/
</code>```

I was expecting to see:

```<code>drwxrwx--- 2 itk itkadm 4096 Sep 19 11:07 foobar/
</code>```

答:
Rather than setting the permissions for the directory to 0. Try instead just using the chmod option to File::Path::make_path

```<code>perl -MFile::Path=make_path -e 'make_path("foobar", { chmod=>0770 });'
</code>```

Body:
When I call make_path (from the core File::Path module, supplying a mode, the directory that is created does not have the mode I requested:

$ perl -MFile::Path=make_path -e 'make_path("foobar", { mode=>0770 });'
$ ls -ld foobar/
drwxr-x--- 2 itk itkadm 4096 Sep 19 11:10 foobar/

I was expecting to see:

drwxrwx--- 2 itk itkadm 4096 Sep 19 11:07 foobar/

Body:
Rather than setting the permissions for the directory to 0. Try instead just using the chmod option to File::Path::make_path

perl -MFile::Path=make_path -e 'make_path("foobar", { chmod=>0770 });'


问:
How to convert [0,3,4] into 100110 that is 6 digit string format in SQL Server 2012?
How to convert [0,3,4] into 100110 that is 6 digit string  format in SQL Server  2012 ?

Example

```<code>string  [2,4,5]
</code>```

should be converted into

```<code>string 001011
</code>```

I have to make 6 digit string , and the digit or position in the string 000000 should be convert to 1 suppose in above string [2,4,5] means 2nd ,4th and 5th index of 000000 should be converted to 1. Final string should be 001011

答:
```<code>DECLARE @zero_str VARCHAR(6) = '000000'
-- Generate table alike to yours
DECLARE @yourTable TABLE (
    [value] varchar(max)
)

INSERT INTO @yourTable VALUES ('[2,4,5]'),('[0,3,4]' )
-- convert array to xml
;WITH cte AS (
    SELECT  [value],
            CAST('<a>'+REPLACE(SUBSTRING([value],2,LEN([value]) - 2),',','</a><a>')+'</a>' as xml) as x
    FROM @yourTable
)
-- do the stuff
SELECT  c.[value],
        RIGHT(@zero_str + CAST(SUM(CAST(STUFF(@zero_str,t.c.value('.','tinyint')+1,1,'1') as int)) as varchar(6)),6 )
FROM cte c
CROSS APPLY x.nodes('/a') as t(c)
GROUP BY c.[value]
</code>```

Output:

```<code>value   (No column name)
[0,3,4] 100110
[2,4,5] 001011
</code>```

Explanation:

STUFF(@zero_str,t.c.value('.','tinyint')+1,1,'1') This changes some part of 000000 to 1, after this part we will have:

```<code>[2,4,5] 001000
[2,4,5] 000010
[2,4,5] 000001
[0,3,4] 100000
[0,3,4] 000100
[0,3,4] 000010
</code>```

In the table. Then we do CASTing to int? so we can use SUM, after this data will be like:

```<code>[0,3,4] 100110
[2,4,5] 1011
</code>```

Then we add 000000 string and use RIGHT to get only 6 symbols.

Hope that helps!

Note:

If no id's in a table then use ROW_NUMBER in CTE part.

```<code>DECLARE @zero_str VARCHAR(6) = '000000'
-- Generate table alike to yours
DECLARE @yourTable TABLE (
    [value] varchar(max)
)

INSERT INTO @yourTable VALUES ('[2,4,5]'),('[0,3,4]'),('[2,3,4]'),('[2,4,5]'),('[0,3,4]'),('[2,3,4]')
-- convert array to xml
;WITH cte AS (
    SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as rn,
            [value],
            CAST('<a>'+REPLACE(SUBSTRING([value],2,LEN([value]) - 2),',','</a><a>')+'</a>' as xml) as x
    FROM @yourTable
)
-- do the stuff
SELECT  c.rn,
        c.[value],
        RIGHT(@zero_str + CAST(SUM(CAST(STUFF(@zero_str,t.c.value('.','tinyint')+1,1,'1') as int)) as varchar(6)),6 )
FROM cte c
CROSS APPLY x.nodes('/a') as t(c)
GROUP BY c.rn, c.[value]
</code>```

Output:

```<code>rn  value   (No column name)
2   [0,3,4] 100110
5   [0,3,4] 100110
3   [2,3,4] 001110
6   [2,3,4] 001110
1   [2,4,5] 001011
4   [2,4,5] 001011
</code>```

Body:
How to convert [0,3,4] into 100110 that is 6 digit string  format in SQL Server  2012 ?

Example

string  [2,4,5]

should be converted into

string 001011

I have to make 6 digit string , and the digit or position in the string 000000 should be convert to 1 suppose in above string [2,4,5] means 2nd ,4th and 5th index of 000000 should be converted to 1. Final string should be 001011

Body:
DECLARE @zero_str VARCHAR(6) = '000000'
-- Generate table alike to yours
DECLARE @yourTable TABLE (
    [value] varchar(max)
)

INSERT INTO @yourTable VALUES ('[2,4,5]'),('[0,3,4]' )
-- convert array to xml
;WITH cte AS (
    SELECT  [value],
            CAST('<a>'+REPLACE(SUBSTRING([value],2,LEN([value]) - 2),',','</a><a>')+'</a>' as xml) as x
    FROM @yourTable
)
-- do the stuff
SELECT  c.[value],
        RIGHT(@zero_str + CAST(SUM(CAST(STUFF(@zero_str,t.c.value('.','tinyint')+1,1,'1') as int)) as varchar(6)),6 )
FROM cte c
CROSS APPLY x.nodes('/a') as t(c)
GROUP BY c.[value]

Output:

value   (No column name)
[0,3,4] 100110
[2,4,5] 001011

Explanation:

STUFF(@zero_str,t.c.value('.','tinyint')+1,1,'1') This changes some part of 000000 to 1, after this part we will have:

[2,4,5] 001000
[2,4,5] 000010
[2,4,5] 000001
[0,3,4] 100000
[0,3,4] 000100
[0,3,4] 000010

In the table. Then we do CASTing to int? so we can use SUM, after this data will be like:

[0,3,4] 100110
[2,4,5] 1011

Then we add 000000 string and use RIGHT to get only 6 symbols.

Hope that helps!

Note:

If no id's in a table then use ROW_NUMBER in CTE part.

DECLARE @zero_str VARCHAR(6) = '000000'
-- Generate table alike to yours
DECLARE @yourTable TABLE (
    [value] varchar(max)
)

INSERT INTO @yourTable VALUES ('[2,4,5]'),('[0,3,4]'),('[2,3,4]'),('[2,4,5]'),('[0,3,4]'),('[2,3,4]')
-- convert array to xml
;WITH cte AS (
    SELECT  ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) as rn,
            [value],
            CAST('<a>'+REPLACE(SUBSTRING([value],2,LEN([value]) - 2),',','</a><a>')+'</a>' as xml) as x
    FROM @yourTable
)
-- do the stuff
SELECT  c.rn,
        c.[value],
        RIGHT(@zero_str + CAST(SUM(CAST(STUFF(@zero_str,t.c.value('.','tinyint')+1,1,'1') as int)) as varchar(6)),6 )
FROM cte c
CROSS APPLY x.nodes('/a') as t(c)
GROUP BY c.rn, c.[value]

Output:

rn  value   (No column name)
2   [0,3,4] 100110
5   [0,3,4] 100110
3   [2,3,4] 001110
6   [2,3,4] 001110
1   [2,4,5] 001011
4   [2,4,5] 001011


问:
Error:(52, 14) error: cannot find symbol method onPreExecute() on Android Studio
I'm trying out a login tutorial (Create an Android login system using MySQL) on Android Studio 3.0. I ran into these errors:

import android.os.AsyncTask; (Click here to see the error)

When I hover on it, it says:

Unused import statement

onPreExecute() (Click here to see the error)

The message shows:

Error:(52, 14) error: cannot find symbol method onPreExecute()

Can anybody help me out? I'm new to this. I'm sorry if the question is not that clear.

答: Try Rebuild the project or restart android studio. Android Studio sometimes gives these kinds of issues</p>


问:
Cannot find entry file index.js
I tried to add push notifications to my app with https://github.com/evollu/react-native-fcm module.
I end up with lots of errors and run many react commands on node including uprade commands.
Now on simulator red screen says "Can not find entry file index.js in any of to roots" and when I look at the ReactPackager it says:

```<code>Loading dependency graph, done. Bundlingindex.js[development, non-minified] 0.0% (0/1), failed. error: bundling failed: Error at DependencyGraph._getAbsolutePath (/Users/beratuslu/Desktop/react-native-starter-app/node_modules/metro-bundler/src/node-haste/DependencyGraph.js:305:11) at DependencyGraph.getDependencies (/Users/beratuslu/Desktop/react-native-starter-app/node_modules/metro-bundler/src/node-haste/DependencyGraph.js:283:4236) at Resolver.getDependencies (/Users/beratuslu/Desktop/react-native-starter-app/node_modules/metro-bundler/src/Resolver/index.js:129:5) at /Users/beratuslu/Desktop/react-native-starter-app/node_modules/metro-bundler/src/Bundler/index.js:642:39 at Generator.next (<anonymous>) at step (/Users/beratuslu/Desktop/react-native-starter-app/node_modules/metro-bundler/src/Bundler/index.js:13:1336) at /Users/beratuslu/Desktop/react-native-starter-app/node_modules/metro-bundler/src/Bundler/index.js:13:1496 at process._tickCallback (internal/process/next_tick.js:103:7)
</code>```

Here is my package.json: https://pastebin.com/2CsXCyJt

Any help appreciated...

答:
From react native 0.49.1 there is a breaking change, Merge your index.android.js and index.ios.js into index.js.
For more details see this issue in Github</p>

Title: Cannot find entry file index.js

Body:
I tried to add push notifications to my app with https://github.com/evollu/react-native-fcm module.
I end up with lots of errors and run many react commands on node including uprade commands.
Now on simulator red screen says "Can not find entry file index.js in any of to roots" and when I look at the ReactPackager it says:

Loading dependency graph, done. Bundlingindex.js[development, non-minified] 0.0% (0/1), failed. error: bundling failed: Error at DependencyGraph._getAbsolutePath (/Users/beratuslu/Desktop/react-native-starter-app/node_modules/metro-bundler/src/node-haste/DependencyGraph.js:305:11) at DependencyGraph.getDependencies (/Users/beratuslu/Desktop/react-native-starter-app/node_modules/metro-bundler/src/node-haste/DependencyGraph.js:283:4236) at Resolver.getDependencies (/Users/beratuslu/Desktop/react-native-starter-app/node_modules/metro-bundler/src/Resolver/index.js:129:5) at /Users/beratuslu/Desktop/react-native-starter-app/node_modules/metro-bundler/src/Bundler/index.js:642:39 at Generator.next (<anonymous>) at step (/Users/beratuslu/Desktop/react-native-starter-app/node_modules/metro-bundler/src/Bundler/index.js:13:1336) at /Users/beratuslu/Desktop/react-native-starter-app/node_modules/metro-bundler/src/Bundler/index.js:13:1496 at process._tickCallback (internal/process/next_tick.js:103:7)

Here is my package.json: https://pastebin.com/2CsXCyJt

Any help appreciated...


问:
How to count neurons in a simple Tensorflow program?
I'm new to Tensorflow and hence I'm still finding my way around.

I guess I know what a neuron is according to Tensorflow. (A neuron accepts an input and produces an output)

Now, in case of a simple program with code like

```<code>c = tf.multiply(a, b)
e = tf.add(c,d)
</code>```

Here, does this program contain 2 neurons?

答:
Considering your example:

c is a output neuron where as a and b are input neurons to it.

and e is again a output neuron and input neuron to e are c and d.

Your network would look like.

Total neurons are 5,
3 input, 1 hidden and 1 output.

Hope this helps, feel free to ask any further questions.

Body:
I'm new to Tensorflow and hence I'm still finding my way around.

I guess I know what a neuron is according to Tensorflow. (A neuron accepts an input and produces an output)

Now, in case of a simple program with code like

c = tf.multiply(a, b)
e = tf.add(c,d)

Here, does this program contain 2 neurons?


问:
creating a dictionary with two lists when a key should have two values in python
hi I have two lists,

```<code>list1
['PO', 'NA', 'PO']

list2
['Post Office', 'Not Available', 'Post area']
</code>```

Iam trying to get a dictionary using this two lists
I tried, my_dict=dict(zip(list1,list2))
it gives,

```<code> {'NA': 'Not Available', 'PO': 'Post area'}
</code>```

but my expected output is,

```<code> {'NA': 'Not Available', 'PO': ['Post area','Post Office']}
</code>```

pls help

答:
```<code>list1 = ['PO', 'NA', 'PO']
list2 = ['Post Office', 'Not Available', 'Post area']

my_dict = dict()
for key,value in zip(list1,list2):
    if key not in my_dict:
        my_dict[key] = value
    else:
        my_dict[key] = [my_dict[key]]
        my_dict[key].append(value)

print(my_dict)
</code>```

Body:
hi I have two lists,

list1
['PO', 'NA', 'PO']

list2
['Post Office', 'Not Available', 'Post area']

Iam trying to get a dictionary using this two lists
I tried, my_dict=dict(zip(list1,list2))
it gives,

 {'NA': 'Not Available', 'PO': 'Post area'}

but my expected output is,

 {'NA': 'Not Available', 'PO': ['Post area','Post Office']}

pls help


问:
How to fix "System.Reflection.TargetInvocationException has been thrown"
I'm following a tutorial for making a discord bot, and after following the basics for setting up a bot I keep running into this exception:

System.Reflection.TargetInvocationException has been thrown. Exception has been thrown by the target of an invocation.

This is the code I have:

```<code>using Discord.Commands;
using Discord;
using System;
namespace TestBot
{
    public class MyBot
    {
        DiscordClient discord;

        public MyBot()
        {
            discord = new DiscordClient(x =>
            {
                x.LogLevel = LogSeverity.Info;
                x.LogHandler = Log;
            });
            discord.UsingCommands(x =>
            {
                x.PrefixChar = '!';
                x.AllowMentionPrefix = true;
            });
            var commands = discord.GetService<CommandService>();

            commands.CreateCommand("test")
                    .Do(async (e) =>
            {
                await e.Channel.SendMessage("response");
            });
             discord.ExecuteAndWait(async () =>
            {
                await discord.Connect("BOT_TOKEN", TokenType.Bot);
            });

        }

        private void Log(object sender, LogMessageEventArgs e)
        {
            Console.WriteLine(e.Message);
        }
    }
}
</code>```

MonoDevelop says that the exception is happening with this piece of code:

```<code>discord.ExecuteAndWait(async () =>
            {
                await discord.Connect("BOT_TOKEN", TokenType.Bot);
            });
</code>```

I don't know how to fix this, so any help would be greatly appreciated.

(As this is my first post here, any suggestions on how to improve my posts are also appreciated.)

答:
In my case, it's caused by some exception in some inner code, and the exception was throwed up through the stack, when come to the surface and show exception window, the exception message has been losed so it shows a useless message System.Reflection.TargetInvocationException has been thrown.

The solution is, open Exception Settings Window, and check all items so that it'll break when any type of Exception happens, so you can catch the exception at the most initial position that the error reason can be esaily undederstood.

My idea comes from HERE.

Body:
I'm following a tutorial for making a discord bot, and after following the basics for setting up a bot I keep running into this exception:

System.Reflection.TargetInvocationException has been thrown. Exception has been thrown by the target of an invocation.

This is the code I have:

using Discord.Commands;
using Discord;
using System;
namespace TestBot
{
    public class MyBot
    {
        DiscordClient discord;

        public MyBot()
        {
            discord = new DiscordClient(x =>
            {
                x.LogLevel = LogSeverity.Info;
                x.LogHandler = Log;
            });
            discord.UsingCommands(x =>
            {
                x.PrefixChar = '!';
                x.AllowMentionPrefix = true;
            });
            var commands = discord.GetService<CommandService>();

            commands.CreateCommand("test")
                    .Do(async (e) =>
            {
                await e.Channel.SendMessage("response");
            });
             discord.ExecuteAndWait(async () =>
            {
                await discord.Connect("BOT_TOKEN", TokenType.Bot);
            });

        }

        private void Log(object sender, LogMessageEventArgs e)
        {
            Console.WriteLine(e.Message);
        }
    }
}

MonoDevelop says that the exception is happening with this piece of code:

discord.ExecuteAndWait(async () =>
            {
                await discord.Connect("BOT_TOKEN", TokenType.Bot);
            });

I don't know how to fix this, so any help would be greatly appreciated.

(As this is my first post here, any suggestions on how to improve my posts are also appreciated.)


问:
differences between ModelSerializer.update() and ModelViewSet.update()
I found both ModelSerializer and ModelViewSet have update() method, and I think both are almost same. Is that correct ?

```<code>from rest_framework import serializers
from rest_framework import viewsets

class FooSerializer(serializers.ModelSerializer):
    class Meta:
        model = Foo
        fields = '__all__'

    def update(self, instance, validated_data):
        # update of model instances
        instance.save()
        return instance

class FooModelAPI(viewsets.ModelViewSet):
    serializer_class = MySerializer
    queryset = my_queryset

    def update(self, request, *args, **kwargs):
        # updateds model instances and save
        return Response("OK")
</code>```

In the above snippet, Can I use either ModelSerializer or ModelViewSet without another for updating model instance ?

答:
If you put the update() method in a view, it is bind to the view itself; meaning that you can only use it in a specific url.
However, if you use it in the serializer, you can use it persistently throughout your application's views.</p>

Body:
I found both ModelSerializer and ModelViewSet have update() method, and I think both are almost same. Is that correct ?

from rest_framework import serializers
from rest_framework import viewsets

class FooSerializer(serializers.ModelSerializer):
    class Meta:
        model = Foo
        fields = '__all__'

    def update(self, instance, validated_data):
        # update of model instances
        instance.save()
        return instance

class FooModelAPI(viewsets.ModelViewSet):
    serializer_class = MySerializer
    queryset = my_queryset

    def update(self, request, *args, **kwargs):
        # updateds model instances and save
        return Response("OK")

In the above snippet, Can I use either ModelSerializer or ModelViewSet without another for updating model instance ?


问:
Base Entity and Serializable
Can I create something like

```<code>@Getter
@Setter
@MappedSuperclass
public class BaseEntity  implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
}
</code>```

And use it in children class?

Is it ok use one serialVersionUID for all children entities?

答:
Eclipse advices to declare new serialVersionUID for my Contract entity extended from BaseEntity with serialVersionUID.

So i think it will be good if you declare it for all child entities.

by the way you can use same serialVersionUID for all your classes.

additionally good writing about serialVersionUID

http://javabeginnerstutorial.com/core-java-tutorial/use-serialversionuid/

Title: Base Entity and Serializable

Body:
Can I create something like

@Getter
@Setter
@MappedSuperclass
public class BaseEntity  implements Serializable{

private static final long serialVersionUID = 1L;

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
}

And use it in children class?

Is it ok use one serialVersionUID for all children entities?


问:
Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug' android studio
I create a game on buildbox I export the project but I can't start the game on android studio
My problem is that I can't run the application or produce an apk file

someone can help me please.

The error

Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.
  java.io.IOException: Can't write [C:\Users\youne\Desktop\android2\app\build\intermediates\multi-dex\debug\componentClasses.jar] (Can't read [C:\Users\youne.gradle\caches\transforms-1\files-1.1\support-core-ui-25.2.0.aar\9adfc8649fc899fbc5e371e8bc1c399a\jars\classes.jar(;;;;;;**.class)] (Duplicate zip entry [classes.jar:android/support/v4/view/ViewPager$2.class]))

I am using

Android Studio 3.0

Java version: Java(TM) SE Runtime Environment (build 1.8.0_73-b02).

Gradle Version: com.android.tools.build:gradle:4.1

And i have Multidex enabled

In my app build.gradle file:

```<code>android {
  compileSdkVersion 27
  buildToolsVersion '27.0.1'

  defaultConfig {
    applicationId "com.drh.bird"
    minSdkVersion 14
    targetSdkVersion 23
    aaptOptions.cruncherEnabled = false
    aaptOptions.useNewCruncher = false
    compileOptions.encoding = 'ISO-8859-1'
    multiDexEnabled = true

    ndk {
      moduleName "player_shared"
    }
  }
  android {
    useLibrary 'org.apache.http.legacy'
  }
  sourceSets {
    main {
      jni.srcDirs = []
    }
  }

  buildTypes {}
  android {
    defaultConfig {
      multiDexEnabled true
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
  }

  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
  }
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
  compile 'com.google.android.gms:play-services:+'
  compile files('libs/dagger-1.2.2.jar')
  compile files('libs/javax.inject-1.jar')
  compile files('libs/nineoldandroids-2.4.0.jar')
  compile files('libs/support-v4-19.0.1.jar')
}
</code>```

答:
You are trying to use compile files('libs/support-v4-19.0.1.jar') with compileSdkVersion 27. But support library should have major version equal to compileSdkVersion

Use implementation "com.android.support:support-v4:27.0.1" instead it

Also, never use + in dependencies version. You may get some problems, when dependency has updated

Body:
I create a game on buildbox I export the project but I can't start the game on android studio
My problem is that I can't run the application or produce an apk file

someone can help me please.

The error

Error:Execution failed for task ':app:transformClassesWithMultidexlistForDebug'.
  java.io.IOException: Can't write [C:\Users\youne\Desktop\android2\app\build\intermediates\multi-dex\debug\componentClasses.jar] (Can't read [C:\Users\youne.gradle\caches\transforms-1\files-1.1\support-core-ui-25.2.0.aar\9adfc8649fc899fbc5e371e8bc1c399a\jars\classes.jar(;;;;;;**.class)] (Duplicate zip entry [classes.jar:android/support/v4/view/ViewPager$2.class]))

I am using

Android Studio 3.0

Java version: Java(TM) SE Runtime Environment (build 1.8.0_73-b02).

Gradle Version: com.android.tools.build:gradle:4.1

And i have Multidex enabled

In my app build.gradle file:

android {
  compileSdkVersion 27
  buildToolsVersion '27.0.1'

  defaultConfig {
    applicationId "com.drh.bird"
    minSdkVersion 14
    targetSdkVersion 23
    aaptOptions.cruncherEnabled = false
    aaptOptions.useNewCruncher = false
    compileOptions.encoding = 'ISO-8859-1'
    multiDexEnabled = true

    ndk {
      moduleName "player_shared"
    }
  }
  android {
    useLibrary 'org.apache.http.legacy'
  }
  sourceSets {
    main {
      jni.srcDirs = []
    }
  }

  buildTypes {}
  android {
    defaultConfig {
      multiDexEnabled true
    }
  }
  compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_7
    targetCompatibility JavaVersion.VERSION_1_7
  }

  buildTypes {
    release {
      minifyEnabled false
      proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
    }
  }
}

dependencies {
  compile 'com.android.support:multidex:1.0.1'
  compile 'com.google.android.gms:play-services:+'
  compile files('libs/dagger-1.2.2.jar')
  compile files('libs/javax.inject-1.jar')
  compile files('libs/nineoldandroids-2.4.0.jar')
  compile files('libs/support-v4-19.0.1.jar')
}


问:
Is Kestrel using a single thread for processing requests like Node.js?
Both Kestrel and Node.js are based on libuv.

While Node.js exactly states that it uses an event loop, I can't seem to find if such is the case for Kestrel, or if it utilizes thread pooling / request queue like IIS?

Kestrel behind a web server

Node.js event loop

```<code>    ┌───────────────────────┐
 ┌─>│        timers         │
 │  └──────────┬────────────┘
 │  ┌──────────┴────────────┐
 │  │     I/O callbacks     │
 │  └──────────┬────────────┘
 │  ┌──────────┴────────────┐
 │  │     idle, prepare     │
 │  └──────────┬────────────┘      ┌───────────────┐
 │  ┌──────────┴────────────┐      │   incoming:   │
 │  │         poll          │<─────┤  connections, │
 │  └──────────┬────────────┘      │   data, etc.  │
 │  ┌──────────┴────────────┐      └───────────────┘
 │  │        check          │
 │  └──────────┬────────────┘
 │  ┌──────────┴────────────┐
 └──┤    close callbacks    │
    └───────────────────────┘
</code>```

答:
Threading is transport specific. With the libuv transport (the default in 2.0) as stated in Daniel J.G.'s answer there's a number of event loops based on the number of logical processors on the machine and that's overridable by setting the value on the options. By default each connection is bound to a particular thread and all IO operations take place on that thread. User code is executed on thread pool threads because we don't trust that users won't block IO threads. When you make IO calls on these thread pool threads (i.e. HttpResponse.WriteAsync), kestrel does the work to marshal that back to the appropriate IO thread the socket was bound to. A typical request flow looks like this:

[ read from networking ] dispatch to thread pool -> [ http parsing ], [ execute middleware pipeline ] call to write -> enqueue user work to the IO thread [ write to network ]

Of course you can always tell kestrel you are a pro and will never block the IO thread and run your code on it. But I wouldn't unless I knew what I was doing (and I don't :D).

Body:
Both Kestrel and Node.js are based on libuv.

While Node.js exactly states that it uses an event loop, I can't seem to find if such is the case for Kestrel, or if it utilizes thread pooling / request queue like IIS?

Kestrel behind a web server

Node.js event loop

    ┌───────────────────────┐
 ┌─>│        timers         │
 │  └──────────┬────────────┘
 │  ┌──────────┴────────────┐
 │  │     I/O callbacks     │
 │  └──────────┬────────────┘
 │  ┌──────────┴────────────┐
 │  │     idle, prepare     │
 │  └──────────┬────────────┘      ┌───────────────┐
 │  ┌──────────┴────────────┐      │   incoming:   │
 │  │         poll          │<─────┤  connections, │
 │  └──────────┬────────────┘      │   data, etc.  │
 │  ┌──────────┴────────────┐      └───────────────┘
 │  │        check          │
 │  └──────────┬────────────┘
 │  ┌──────────┴────────────┐
 └──┤    close callbacks    │
    └───────────────────────┘


问:
Host Multiple Domains on One Server/IP
I have phpList already setup and Codeigniter project that I want to add in one server.

The phpList configuration which is located /etc/httpd/conf.d/phplist.conf has:

```<code><VirtualHost *:80>
    ServerName phplist.example.com
    ServerAdmin admin@example.com
    DocumentRoot /var/www/phplist-3.0.5/public_html

    LogLevel warn
    ErrorLog /var/log/httpd/phplist_error.log
    CustomLog /var/log/httpd/phplist_access.log combined
</VirtualHost>
</code>```

Here is my possible setting for the CI project, but I don't know how to create one.

```<code><VirtualHost *:80>
    ServerName listcsv.com
    ServerAdmin admin@listcsv.com
    DocumentRoot /var/www/citest/index.php
</VirtualHost>
</code>```

Below the /etc/httpd/conf/httpd.conf file has a IncludeOptional conf.d/*.conf so I think this would include the configuration file on phplist.

I don't know what settings and where configuration file should I go,
should I edit on /etc/httpd/conf/httpd.conf or just add it together with the phpList configuration at /etc/httpd/conf.d/phplist.conf?

I tried accessing phplist at http://phplist.example.com but the site cannot be reached.

I could access the phpList by going to http://server-ip-address/lists/admin on the browser.

Also, I cannot access the CI project.

答:
I would recommend creating the directory that the virtual hosts will be stored in, as well as the directory that tells Apache that a virtual host is ready to serve the website

```<code>sudo mkdir /etc/httpd/sites-available # vhost files
sudo mkdir /etc/httpd/sites-enabled # symbolic links for vhost enabled
</code>```

Tell Apache where to look for virtual hosts

```<code>sudo vim /etc/httpd/conf/httpd.conf
</code>```

Add this line at the end of the file

```<code>IncludeOptional sites-enabled/*.conf
</code>```

Save and exit.

For each website/domain create its own vhost

```<code>sudo vim /etc/httpd/sites-available/example1.com.conf
sudo vim /etc/httpd/sites-available/example2.com.conf
sudo vim /etc/httpd/sites-available/example3.com.conf
</code>```

Enable the virtualhost

```<code>sudo ln -s /etc/httpd/sites-available/example1.com.conf /etc/httpd/sites-enabled/example1.com.conf
sudo ln -s /etc/httpd/sites-available/example2.com.conf /etc/httpd/sites-enabled/example2.com.conf
sudo ln -s /etc/httpd/sites-available/example3.com.conf /etc/httpd/sites-enabled/example3.com.conf
</code>```

We done, restart your Apache server for the changes to take affect

```<code>sudo apachectl restart
</code>```

Don't forget to point your domains to the web server's public IP address.

Title: Host Multiple Domains on One Server/IP

Body:
I have phpList already setup and Codeigniter project that I want to add in one server.

The phpList configuration which is located /etc/httpd/conf.d/phplist.conf has:

<VirtualHost *:80>
    ServerName phplist.example.com
    ServerAdmin admin@example.com
    DocumentRoot /var/www/phplist-3.0.5/public_html

    LogLevel warn
    ErrorLog /var/log/httpd/phplist_error.log
    CustomLog /var/log/httpd/phplist_access.log combined
</VirtualHost>

Here is my possible setting for the CI project, but I don't know how to create one.

<VirtualHost *:80>
    ServerName listcsv.com
    ServerAdmin admin@listcsv.com
    DocumentRoot /var/www/citest/index.php
</VirtualHost>

Below the /etc/httpd/conf/httpd.conf file has a IncludeOptional conf.d/*.conf so I think this would include the configuration file on phplist.

I don't know what settings and where configuration file should I go,
should I edit on /etc/httpd/conf/httpd.conf or just add it together with the phpList configuration at /etc/httpd/conf.d/phplist.conf?

I tried accessing phplist at http://phplist.example.com but the site cannot be reached.

I could access the phpList by going to http://server-ip-address/lists/admin on the browser.

Also, I cannot access the CI project.

Body:
I would recommend creating the directory that the virtual hosts will be stored in, as well as the directory that tells Apache that a virtual host is ready to serve the website

sudo mkdir /etc/httpd/sites-available # vhost files
sudo mkdir /etc/httpd/sites-enabled # symbolic links for vhost enabled

Tell Apache where to look for virtual hosts

sudo vim /etc/httpd/conf/httpd.conf

Add this line at the end of the file

IncludeOptional sites-enabled/*.conf

Save and exit.

For each website/domain create its own vhost

sudo vim /etc/httpd/sites-available/example1.com.conf
sudo vim /etc/httpd/sites-available/example2.com.conf
sudo vim /etc/httpd/sites-available/example3.com.conf

Enable the virtualhost

sudo ln -s /etc/httpd/sites-available/example1.com.conf /etc/httpd/sites-enabled/example1.com.conf
sudo ln -s /etc/httpd/sites-available/example2.com.conf /etc/httpd/sites-enabled/example2.com.conf
sudo ln -s /etc/httpd/sites-available/example3.com.conf /etc/httpd/sites-enabled/example3.com.conf

We done, restart your Apache server for the changes to take affect

sudo apachectl restart

Don't forget to point your domains to the web server's public IP address.


问:
Toolbar doesn't hide on Scrolling recyclerview in DrawerLayout
hello I'm trying to hide toolbar when i scroll recyclerview which is in fragment, my layout also has an drawerlayout and tablayout. I'm trying just to hide toolbar and move tab bar up.

this is my activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fitsSystemWindows="true"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#e9e7e7"
    tools:context=".MainActivity">

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/cl_dashboard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v4.view.ViewPager
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:id="@+id/viewPager"
            >

        </android.support.v4.view.ViewPager>

        <android.support.design.widget.AppBarLayout
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:id="@+id/appBarLayout">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/ctb_dashboard"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:contentScrim="@color/white"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <android.support.v7.widget.Toolbar
                    xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    android:layout_width="match_parent"
                    android:background="@color/colorPrimary"
                    android:minHeight="?attr/actionBarSize"
                    android:id="@+id/toolBar"
                    app:layout_scrollFlags="scroll|enterAlways"
                    android:layout_height="wrap_content"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                    app:theme="@style/ThemeOverlay.AppCompat.Dark"
                    app:layout_collapseMode="pin">

                </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

            <android.support.design.widget.TabLayout
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:id="@+id/tabLayout"
                app:tabMode="fixed"
                app:tabSelectedTextColor="@color/white"
                app:tabTextColor="@color/colorTab"
                app:tabTextAppearance="@style/MyTabStyle"
                app:tabIndicatorColor="@android:color/white"
                app:tabIndicatorHeight="3dp"
                app:tabGravity="fill">
            </android.support.design.widget.TabLayout>

        </android.support.design.widget.AppBarLayout>

    </android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView
        app:headerLayout="@layout/header"
        app:itemTextAppearance="@style/NavDrawerTextStyle"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/nav_view"
        android:background="#d2d2d2"
        app:itemTextColor="#6c6c6c"
        app:itemIconTint="#6c6c6c"
        app:menu="@menu/drawermenu"
        android:layout_gravity="start">
    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>
</code>```

fragment_home.xml

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".HomeFragment">

    <android.support.v7.widget.RecyclerView
        android:layout_marginTop="100dp"
        android:id="@+id/blog_listt2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

    </android.support.v7.widget.RecyclerView>

    <ProgressBar
        android:id="@+id/progressBar2"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:indeterminateTint="@color/colorPrimaryDark"
        android:visibility="visible"/>

</FrameLayout>
</code>```

I have tried most of the answers which i have found in Stack overflow still i was unable to get it done. Am I doing something wrong? will someone please help me out with this trying to get this done sense 1 week.

答:
Can you elaborate more on what is going wrong? The biggest issue I see here is that you have the exitUntilCollapsed flag set on your CollapsingToolbarLayout's layout_scrollFlags. If you are unable to get the Toolbar to scroll off screen, that is the culprit. Your AppBarLayout needs to be set up like this:

```<code><android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary">

    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="?attr/colorPrimary"
        app:titleEnabled="false"
        app:layout_scrollFlags="scroll">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin" />
    </android.support.design.widget.CollapsingToolbarLayout>

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</android.support.design.widget.AppBarLayout>
</code>```

Can't embed images yet. Click here for gif.

Also, if all you need is to have the Toolbar scroll off-screen, you don't need a CollapsingToolbarLayout. You can just have the Toolbar with app:layout_scrollFlags="scroll", like so:

```<code><android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:layout_scrollFlags="scroll"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</android.support.design.widget.AppBarLayout>
</code>```

This is the best resource I've found for explaining all of the different scroll flags for AppBarLayout and CollapsingToolbarLayout: http://saulmm.github.io/mastering-coordinator

Body:
hello I'm trying to hide toolbar when i scroll recyclerview which is in fragment, my layout also has an drawerlayout and tablayout. I'm trying just to hide toolbar and move tab bar up.

this is my activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:fitsSystemWindows="true"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="#e9e7e7"
    tools:context=".MainActivity">

    <android.support.design.widget.CoordinatorLayout
        android:id="@+id/cl_dashboard"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <android.support.v4.view.ViewPager
            android:layout_height="match_parent"
            android:layout_width="match_parent"
            android:id="@+id/viewPager"
            >

        </android.support.v4.view.ViewPager>

        <android.support.design.widget.AppBarLayout
            android:layout_height="wrap_content"
            android:layout_width="match_parent"
            android:id="@+id/appBarLayout">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/ctb_dashboard"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:fitsSystemWindows="true"
                app:contentScrim="@color/white"
                app:layout_scrollFlags="scroll|exitUntilCollapsed">

                <android.support.v7.widget.Toolbar
                    xmlns:android="http://schemas.android.com/apk/res/android"
                    xmlns:app="http://schemas.android.com/apk/res-auto"
                    android:layout_width="match_parent"
                    android:background="@color/colorPrimary"
                    android:minHeight="?attr/actionBarSize"
                    android:id="@+id/toolBar"
                    app:layout_scrollFlags="scroll|enterAlways"
                    android:layout_height="wrap_content"
                    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
                    app:theme="@style/ThemeOverlay.AppCompat.Dark"
                    app:layout_collapseMode="pin">

                </android.support.v7.widget.Toolbar>

        </android.support.design.widget.CollapsingToolbarLayout>

            <android.support.design.widget.TabLayout
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:id="@+id/tabLayout"
                app:tabMode="fixed"
                app:tabSelectedTextColor="@color/white"
                app:tabTextColor="@color/colorTab"
                app:tabTextAppearance="@style/MyTabStyle"
                app:tabIndicatorColor="@android:color/white"
                app:tabIndicatorHeight="3dp"
                app:tabGravity="fill">
            </android.support.design.widget.TabLayout>

        </android.support.design.widget.AppBarLayout>

    </android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView
        app:headerLayout="@layout/header"
        app:itemTextAppearance="@style/NavDrawerTextStyle"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:id="@+id/nav_view"
        android:background="#d2d2d2"
        app:itemTextColor="#6c6c6c"
        app:itemIconTint="#6c6c6c"
        app:menu="@menu/drawermenu"
        android:layout_gravity="start">
    </android.support.design.widget.NavigationView>

</android.support.v4.widget.DrawerLayout>

fragment_home.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".HomeFragment">

    <android.support.v7.widget.RecyclerView
        android:layout_marginTop="100dp"
        android:id="@+id/blog_listt2"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior">

    </android.support.v7.widget.RecyclerView>

    <ProgressBar
        android:id="@+id/progressBar2"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical|center_horizontal"
        android:indeterminateTint="@color/colorPrimaryDark"
        android:visibility="visible"/>

</FrameLayout>

I have tried most of the answers which i have found in Stack overflow still i was unable to get it done. Am I doing something wrong? will someone please help me out with this trying to get this done sense 1 week.

Body:
Can you elaborate more on what is going wrong? The biggest issue I see here is that you have the exitUntilCollapsed flag set on your CollapsingToolbarLayout's layout_scrollFlags. If you are unable to get the Toolbar to scroll off screen, that is the culprit. Your AppBarLayout needs to be set up like this:

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary">

    <android.support.design.widget.CollapsingToolbarLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:contentScrim="?attr/colorPrimary"
        app:titleEnabled="false"
        app:layout_scrollFlags="scroll">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:layout_collapseMode="pin" />
    </android.support.design.widget.CollapsingToolbarLayout>

    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</android.support.design.widget.AppBarLayout>

Can't embed images yet. Click here for gif.

Also, if all you need is to have the Toolbar scroll off-screen, you don't need a CollapsingToolbarLayout. You can just have the Toolbar with app:layout_scrollFlags="scroll", like so:

<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary">
    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:layout_scrollFlags="scroll"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />

    <android.support.design.widget.TabLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</android.support.design.widget.AppBarLayout>

This is the best resource I've found for explaining all of the different scroll flags for AppBarLayout and CollapsingToolbarLayout: http://saulmm.github.io/mastering-coordinator


问:
How to intercept all read and write access to objects at runtime?
I am working on an aging Java "Swing" application that, unfortunately, uses a non Thread-safe data model. As the number of clients with multi-threading and multi-core PCs grows, so does the number of spurious random errors due to non synchronized access to the data. We have a huge code-base, something like 6000 Java files, most of which are quite large and complicated.

I would like to create a global static ReentrantReadWriteLock to control access to the model. My plan would be to create a dummy ReadWriteLock implementation, which always succeeds and does not do anything, and use it on the productive system, while using the ReentrantReadWriteLock on the test systems, so that the transition can be gradual.

What I need is a way to "intercept" all accesses to the model in the test systems and log an error if the access is not within the scoop of an appropriate lock/unlock block. ReentrantReadWriteLock can tell you if you own a write lock. I am assuming I could track the read lock state myself by using a ThreadLocal or something.

So now comes the real question: How could I, in Java, write code that would intercept at runtime any access to any public method in a well-defined set of classes, and check if the access is within a lock/unlock block, by querying the global lock? Can this be done with AspectJ? Or anything else? And how?

答:
I assume it can be done with AspectJ But I haven't used it enough to know how.

Instead what I would do is use a modified copy of the classes you want to trap and add them to the bootclasspath. e.g. change a copy of FileInputStream and FileOutputStream.

For test systems this work very well in a simple manner. I wouldn't sugegst you do this in production.


问:
Show a toast message after each five seconds in Background Service in Xamarin.android
I have implemented a background service. When I boot my device, the background service is started and toast message is displayed. I want a toast message to appear each 5 seconds while the service in running. The following code does not seem to be doing the job:

```<code>[Service]
    public class BroadcastService : Service
    {
        IBinder mBinder;

        [return: GeneratedEnum]
        public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
        {

            Toast.MakeText(this, "BroadcastService Started...", ToastLength.Long).Show();

            DoWork();

            base.OnStartCommand(intent, flags, startId);
            return StartCommandResult.Sticky;

        }

public void DoWork()
{
    while (true)
    {
        Toast.MakeText(this, "BroadcastService is running at each 5 seconds...", ToastLength.Long).Show();
        Thread.Sleep(5000);
    }
}
</code>```

Can somebody please advise what is wrong above and help to achieve this in Xamarin.android ?

答:
I want a toast message to appear each 5 seconds while the service in running. The following code does not seem to be doing the job

Once OnStartCommand finish executing, DoWork won't execute any more.

According to your requirement, you need to use JobScheduler together with JobInfo to create a periodic task. For how to use JobScheduler, You can refer to the official demo of JobScheduler

Body:
I have implemented a background service. When I boot my device, the background service is started and toast message is displayed. I want a toast message to appear each 5 seconds while the service in running. The following code does not seem to be doing the job:

[Service]
    public class BroadcastService : Service
    {
        IBinder mBinder;

        [return: GeneratedEnum]
        public override StartCommandResult OnStartCommand(Intent intent, [GeneratedEnum] StartCommandFlags flags, int startId)
        {

            Toast.MakeText(this, "BroadcastService Started...", ToastLength.Long).Show();

            DoWork();

            base.OnStartCommand(intent, flags, startId);
            return StartCommandResult.Sticky;

        }

public void DoWork()
{
    while (true)
    {
        Toast.MakeText(this, "BroadcastService is running at each 5 seconds...", ToastLength.Long).Show();
        Thread.Sleep(5000);
    }
}

Can somebody please advise what is wrong above and help to achieve this in Xamarin.android ?


问:
Edit functionality in form using knockout js
Hi i am working on a form using knockout js i have to perform CRUD operation. Out of these i am able to do all except update(edit). I want on click of edit same form will open as open on click on addperson but with the values of person. here is my code</p>

```<code><html>
<head>
    <script type="text/javascript" src="jquery.min.js"></script>
    <script type="text/javascript" src="knockout-3.1.0.js"></script>
</head>
<body>
<a href="#" data-bind="click:addFields">ADDPerson</a>
<a href="#" data-bind="click:resetPerson">Reset</a>
    <div data-bind="foreach:fields,visible:show">
        <div data-bind="text:firstName"></div>
        <div data-bind="text:lastName"></div>
        <a href="#" data-bind="click:$root.remove">Remove</a>
        <a href="#" data-bind="click:$root.edit" >edit</a>
    </div>
<form data-bind="visible:showfields">
    First Name:
    <input data-bind="value:formFirstName"/>
    Last Name:
    <input data-bind="value:formLastName"/>
    <a href="#" data-bind="click:addPerson">ADD</a>
</form>
<body>
<script>
function person(firstName, lastName) {
    var self = this;
    self.firstName = ko.observable(firstName);
    self.lastName = ko.observable(lastName);

}

function personForm(formFirstName, formFirstName) {
    var self = this;
    self.formFirstName = ko.observable("david");
    self.formLastName = ko.observable("rock");
}

function personViewModel() {
    var self = this;
    self.formFirstName = ko.observable("add");
    self.formLastName = ko.observable("Value");
    self.show = ko.observable(true);
    self.showfields = ko.observable(false);
    self.fields = ko.observableArray([
        new person("paul", "kerry"),
        new person("john", "cena")
    ]);
    self.addFields = function() {
        self.show(false);
        self.showfields(true);
    };
    self.addPerson = function() {
        self.fields.push(new person(self.formFirstName(), self.formLastName()));
        self.show(true);
        self.showfields(false);
    }
    self.resetPerson = function() {
        self.fields.removeAll();
        self.fields.push(new person("john", "cena"));
        self.fields.push(new person("abc", "def"));
    }
    self.remove = function(person) {
        self.fields.remove(person);
    }
}

ko.applyBindings(new personViewModel());
</script>
</html>
</code>```

答:
If you want to edit the form in place. Kind of like asp.net webform style.

The simple way is to has the input disabled initially. Then have the edit button to enable the inputs. Hope this helps.

Body:
Hi i am working on a form using knockout js i have to perform CRUD operation. Out of these i am able to do all except update(edit). I want on click of edit same form will open as open on click on addperson but with the values of person. here is my code

ADDPerson
Reset

        Remove
        edit

<form data-bind="visible:showfields">
    First Name:
    <input data-bind="value:formFirstName"/>
    Last Name:
    <input data-bind="value:formLastName"/>
    ADD
</form>


问:
Can you use multiple mutex lock/unlock with non-identical keys within the same function to calculate average in a data structure?
Say I wanted to compute the average of the values in an array X of size N. Let's assume that we use T threads where T is some fraction of N so we are multithreading.

Is it possible to declare two unique mutex keys and execute the following without error?

Edit: any ideas on how to go about computing something like an average, maximum, minimum, etc.?

See below:

```<code>#include <stdio.h>
#include <pthread.h>

void* sum(void* arg);

int sum = 0;
int average = 0;

int x[N];

int main()
{
    int i;
    pthread_t threads[T];

    for(i=0; i<T; i++)
        pthread_create(&x[i], NULL, sum, (void *)i);
    for(i=0; i<T; i++)
        pthread_join(x[i], NULL);
}

void* sum(void* arg)
{
    int counter = 0;
    int *id = (int *) arg;

    pthread_mutex_t key1;
    pthread_mutex_t key2;

    int size = N/T;
    int start = id * size;
    int end = id * size + size;

    for(i=start; i<end; i++)
    {
        counter = counter + x[i];
    }

    pthread_mutex_lock(&key1);
    sum += counter;
    pthread_mutex_unlock(&key1);

    pthread_mutex_lock(&key2);
    average = sum / counter;
    pthread_mutex_lock(&key2);

    return NULL;
}
</code>```

答:
No, this is a disaster. Each thread will call sum and they will each get their own mutex. That means one thread can lock its key2 at the same time another thread locks its key2. So the two threads could access average at the same time.

You need one, and only one, mutex to protect average. Otherwise, it's not actually protected.

(Also, you have both a function and a global called sum. That will lead to pain and confusion.)

You also have another problem. Each thread is taking the shared sum and dividing it by its private counter. That doesn't make any sense at all. The sum variable needs to be divided by the total number of entries it sums to get an average, not the number of entries added by that particular thread.

I would suggest two changes:

Have only one mutex. Make it a global.

Don't have the sum function touch the average variable. After you've joined all the threads, just do average = sum / N;.

Body:
Say I wanted to compute the average of the values in an array X of size N. Let's assume that we use T threads where T is some fraction of N so we are multithreading.

Is it possible to declare two unique mutex keys and execute the following without error?

Edit: any ideas on how to go about computing something like an average, maximum, minimum, etc.?

See below:

#include <stdio.h>
#include <pthread.h>

void* sum(void* arg);

int sum = 0;
int average = 0;

int x[N];

int main()
{
    int i;
    pthread_t threads[T];

    for(i=0; i<T; i++)
        pthread_create(&x[i], NULL, sum, (void *)i);
    for(i=0; i<T; i++)
        pthread_join(x[i], NULL);
}

void* sum(void* arg)
{
    int counter = 0;
    int *id = (int *) arg;

    pthread_mutex_t key1;
    pthread_mutex_t key2;

    int size = N/T;
    int start = id * size;
    int end = id * size + size;

    for(i=start; i<end; i++)
    {
        counter = counter + x[i];
    }

    pthread_mutex_lock(&key1);
    sum += counter;
    pthread_mutex_unlock(&key1);

    pthread_mutex_lock(&key2);
    average = sum / counter;
    pthread_mutex_lock(&key2);

    return NULL;
}


问:
Do I need to lock before read a shared variable?
I'm totally new to multiple processes/threads programming in C, i understand that if one process needs to modify a shared variable, it needs to lock before doing so.

If one process needs to read a shared variable, does it need to lock ?

答: yes . if one variables is shared between multiple process ,u need to do so, as it avoids the errors in Ur result, i.e one process wants to do read/write/modify on the shared variable/data he needs to check is that variable is free or not ,then he need to proceed.if its free then lock it and do process on it or else it has to wait till it free</p>


问:
How to expand tf.data.Dataset with additional example transformations in Tensorflow
I would like to double the size of an existing dataset I'm using to train a neural network in tensorflow on the fly by adding random noise to it. So when I'm done I'll have all the existing examples and also all the examples with noise added to them. I'd also like to interleave these as I transform them, so they come out in this order: example 1 without noise, example 1 with noise, example 2 without noise, example 2 with noise, etc. I'm struggling to accomplish this using the Dataset api. I've tried to use unbatch to accomplish this like so:

```<code>def generate_permutations(features, labels):
    return [
        [features, labels],
        [add_noise(features), labels]
    ]

dataset.map(generate_permutations).apply(tf.contrib.data.unbatch())
</code>```

but I get an error saying Shapes must be equal rank, but are 2 and 1. I'm guessing tensorflow is trying to make a tensor out of that batch I'm returning, but features and labels are different shapes, so that doesn't work. I could probably do this by just making two datasets and concating them together, but I'm worried that would result in very skewed training where I train nicely for half the epoch and suddenly all of the data has this new transformation to it for the second half. How can I accomplish this on the fly without writing these transformations to disk before feeding into tensorflow?

答:
The Dataset.flat_map() transformation is the tool you need: it enables you to map a single input element into multiple elements, then flattens the result. Your code would look something like the following:

```<code>def generate_permutations(features, labels):
    regular_ds = tf.data.Dataset.from_tensors((features, labels))
    noisy_ds = tf.data.Dataset.from_tensors((add_noise(features), labels))
    return regular_ds.concatenate(noisy_ds)

dataset = dataset.flat_map(generate_permutations)
</code>```

Body:
I would like to double the size of an existing dataset I'm using to train a neural network in tensorflow on the fly by adding random noise to it. So when I'm done I'll have all the existing examples and also all the examples with noise added to them. I'd also like to interleave these as I transform them, so they come out in this order: example 1 without noise, example 1 with noise, example 2 without noise, example 2 with noise, etc. I'm struggling to accomplish this using the Dataset api. I've tried to use unbatch to accomplish this like so:

def generate_permutations(features, labels):
    return [
        [features, labels],
        [add_noise(features), labels]
    ]

dataset.map(generate_permutations).apply(tf.contrib.data.unbatch())

but I get an error saying Shapes must be equal rank, but are 2 and 1. I'm guessing tensorflow is trying to make a tensor out of that batch I'm returning, but features and labels are different shapes, so that doesn't work. I could probably do this by just making two datasets and concating them together, but I'm worried that would result in very skewed training where I train nicely for half the epoch and suddenly all of the data has this new transformation to it for the second half. How can I accomplish this on the fly without writing these transformations to disk before feeding into tensorflow?

Body:
The Dataset.flat_map() transformation is the tool you need: it enables you to map a single input element into multiple elements, then flattens the result. Your code would look something like the following:

def generate_permutations(features, labels):
    regular_ds = tf.data.Dataset.from_tensors((features, labels))
    noisy_ds = tf.data.Dataset.from_tensors((add_noise(features), labels))
    return regular_ds.concatenate(noisy_ds)

dataset = dataset.flat_map(generate_permutations)


问:
Click on current row for expand details in jQuery
I want to click on particular row to expand that row with some data. I tried with this jQuery but it is not working.

could anybody help, where I missed something.

jQuery

this is working fine but I want to do with current row

```<code>$('.item-id-expand').click(function(){
  $('.item-id-close').css("display", "inline-block");
  $('.item-id-expand').hide();
  $('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){
  $('.item-id-close').hide();
  $('.item-id-expand').show();
  $('.order-details-row1-details').hide();
});
</code>```

Here I tried with this but its not working

```<code>$('.item-id-expand', this).click(function(){
  $(this).find('.item-id-close').css("display", "inline-block");
  $(this).find('.item-id-expand').hide();
  $(this).find('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){
  $(this).find('.item-id-close').hide();
  $(this).find('.item-id-expand').show();
  $(this).find('.order-details-row1-details').hide();
});
</code>```

Html

```<code><div class="order-details">
  <ul class="order-details-head">
    <li>Item ID</li>
    <li>Name</li>
    <li>Qty</li>
    <li>Status</li>
  </ul>
  <ul class="order-details-row1">
    <li><div class="item-id-expand">+</div><div class="item-id-close">-</div>123456</li>
    <li>php 11 echo </li>
    <li>php 12 echo </li>
    <li>php 13 echo </li>
  </ul>
  <div class="order-details-row1-details">
    <ul class="order-details-row1-details-head">
      <li>Date</li>
      <li>Description</li>
    </ul>
    <ul class="order-details-row1-details1">
      <li> echo datetrack</li>
      <li>php echo </li>
    </ul>
  </div>
  <ul class="order-details-row1">
    <li><div class="item-id-expand">+</div><div class="item-id-close">-</div>654321</li>
    <li>php 21 echo </li>
    <li>php 22 echo </li>
    <li>php 23 echo </li>
  </ul>
  <div class="order-details-row1-details">
    <ul class="order-details-row1-details-head">
      <li>Date</li>
      <li>Description</li>
    </ul>
    <ul class="order-details-row1-details1">
      <li> echo datetrack</li>
      <li>php echo </li>
    </ul>
  </div>
</div>
</code>```

答:
Try this:-

```<code>$('.item-id-expand').click(function(){
  $(this).closest('li').find('.item-id-close').css("display", "inline-block");
  $(this).hide();
  $(this).closest('ul').next('.order-details-row1-details').show();
});

$('.item-id-close').click(function(){
  $(this).hide();
  $(this).closest('li').find('.item-id-expand').show();
  $(this).closest('ul').next('.order-details-row1-details').hide();
});
</code>```

JSFiddle:- https://jsfiddle.net/g0hter3y/2/

Body:
I want to click on particular row to expand that row with some data. I tried with this jQuery but it is not working.

could anybody help, where I missed something.

jQuery

this is working fine but I want to do with current row

$('.item-id-expand').click(function(){
  $('.item-id-close').css("display", "inline-block");
  $('.item-id-expand').hide();
  $('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){
  $('.item-id-close').hide();
  $('.item-id-expand').show();
  $('.order-details-row1-details').hide();
});

Here I tried with this but its not working

$('.item-id-expand', this).click(function(){
  $(this).find('.item-id-close').css("display", "inline-block");
  $(this).find('.item-id-expand').hide();
  $(this).find('.order-details-row1-details').show();
});
$('.item-id-close').click(function(){
  $(this).find('.item-id-close').hide();
  $(this).find('.item-id-expand').show();
  $(this).find('.order-details-row1-details').hide();
});

Html

Item ID

Name

Qty

Status

+

-
123456

php 11 echo

php 12 echo

php 13 echo

Date

Description

 echo datetrack

php echo

+

-
654321

php 21 echo

php 22 echo

php 23 echo

Date

Description

 echo datetrack

php echo

Body:
Try this:-

$('.item-id-expand').click(function(){
  $(this).closest('li').find('.item-id-close').css("display", "inline-block");
  $(this).hide();
  $(this).closest('ul').next('.order-details-row1-details').show();
});

$('.item-id-close').click(function(){
  $(this).hide();
  $(this).closest('li').find('.item-id-expand').show();
  $(this).closest('ul').next('.order-details-row1-details').hide();
});

JSFiddle:- https://jsfiddle.net/g0hter3y/2/


问:
jsf java asking about time in jsf
my data base have simple date and time but when i pic in UI so time is convert in to GMT .
How to convert origional time(DB) .</p>

答:
Use <f:convertDateTime/>

Example:

```<code><h:outputText value="#{myBean.myDate}">
  <f:convertDateTime pattern="dd/MM/yyyy" />
</h:outputText>
</code>```

More info about <f:convertDateTime/> can be found here.

Title: jsf java asking about time in jsf

Body:
Use <f:convertDateTime/>

Example:

<h:outputText value="#{myBean.myDate}">
  <f:convertDateTime pattern="dd/MM/yyyy" />
</h:outputText>

More info about <f:convertDateTime/> can be found here.