问:
Scripts for printer configuration mono / color - Windows 7
I've been working on this for some time and nearly got it working. Nearly....

I am creating a script under Win7 Ent that's adding 2 network printers (no printer server - just via IP address). For each printer I want it to create a colour and mono queue - so 4 printer queues in total.

Adding works fine with those commands:

```<code>cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Operators_Color"
cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Operators_MOno"
cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Traders_Color"
cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Traders_MOno"
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.116mono
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.116color
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.118mono
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.118color

cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Operators_Color"
cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Operators_MOno"
cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Traders_Color"
cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Traders_MOno"
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.116mono
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.116color
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.118mono
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.118color

cscript "C:\XXXXX\Scripts\Prnport.vbs" -a -r IP_XXX.XXX.XXX.116mono -h XXX.XXX.XXX.116 -o raw -n 9100

cscript "C:\XXXXX\Scripts\Prnport.vbs" -a -r IP_XXX.XXX.XXX.116color -h XXX.XXX.XXX.116 -o raw -n 9100

cscript "C:\XXXXX\Scripts\Prnport.vbs" -a -r IP_XXX.XXX.XXX.118mono -h XXX.XXX.XXX.118 -o raw -n 9100

cscript "C:\XXXXX\Scripts\Prnport.vbs" -a -r IP_XXX.XXX.XXX.118color -h XXX.XXX.XXX.118 -o raw -n 9100

cscript "C:\XXXXX\Scripts\Prndrvr.vbs" -a -m "HP Universal Printing PCL 6" -i C:\XXXXX\Drivers\hpzius23.inf

cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -a -p "XXX_Traders_Color" -m "HP Universal Printing PCL 6" -r IP_XXX.XXX.XXX.116color

cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -a -p "XXX_Traders_MOno" -m "HP Universal Printing PCL 6" -r IP_XXX.XXX.XXX.116mono

cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -a -p "XXX_Operators_Color" -m "HP Universal Printing PCL 6" -r IP_XXX.XXX.XXX.118color

cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -a -p "XXX_Operators_MOno" -m "HP Universal Printing PCL 6" -r IP_XXX.XXX.XXX.118mono'
</code>```

I hit a wall when trying to set the queues with color / mono setting.

Tried two methods:

Via Powershell Set-PrintConfiguration command:

Set-PrintConfiguration –PrinterName "XXX_Traders_Color" -Color "1"

Set-PrintConfiguration –PrinterName "XXX_Traders_MOno" -Color "0"

Set-PrintConfiguration –PrinterName "XXX_Operators_Color" -Color "1"

Set-PrintConfiguration –PrinterName "XXX_Operators_MOno" -Color "0"

I'm getting below (guessing this is not a command present in Win 7 powershell):

The term 'Set-PrintConfiguration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and
try again.

I tried using the RUNDLL32 PRINTUI.DLL,PrintUIEntry commands to

export printer configuration with changed mono / color setting (works fine)
RUNDLL32 PRINTUI.DLL,PrintUIEntry /Ss /n "XXX_Operators_MOno" /a "c:\temp\Mirek1.dat" d g

import the file created above into new queue:
RUNDLL32 PRINTUI.DLL,PrintUIEntry /Sr /n "NewXXX_Operators_MOno" /a "c:\temp\Mirek1.dat"

But the second command doesn't seem to cause the queue to adjust mono / color setting that was exported in the first instance.

I wonder if anyone here has struggled with similar headache?

Any help much appreciated..

答:
I got this to work by using the u switch (instead of d g).  That exports "User DevMode":

```<code>RUNDLL32 PRINTUI.DLL,PrintUIEntry /Ss /n "XXX_Operators_MOno" /a "c:\temp\Mirek1.dat" u
</code>```

Body:
I've been working on this for some time and nearly got it working. Nearly....

I am creating a script under Win7 Ent that's adding 2 network printers (no printer server - just via IP address). For each printer I want it to create a colour and mono queue - so 4 printer queues in total.

Adding works fine with those commands:

cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Operators_Color"
cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Operators_MOno"
cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Traders_Color"
cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Traders_MOno"
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.116mono
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.116color
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.118mono
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.118color

cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Operators_Color"
cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Operators_MOno"
cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Traders_Color"
cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -d -p "XXX_Traders_MOno"
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.116mono
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.116color
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.118mono
cscript "C:\XXXXX\Scripts\Prnport.vbs" -d -r IP_XXX.XXX.XXX.118color

cscript "C:\XXXXX\Scripts\Prnport.vbs" -a -r IP_XXX.XXX.XXX.116mono -h XXX.XXX.XXX.116 -o raw -n 9100

cscript "C:\XXXXX\Scripts\Prnport.vbs" -a -r IP_XXX.XXX.XXX.116color -h XXX.XXX.XXX.116 -o raw -n 9100

cscript "C:\XXXXX\Scripts\Prnport.vbs" -a -r IP_XXX.XXX.XXX.118mono -h XXX.XXX.XXX.118 -o raw -n 9100

cscript "C:\XXXXX\Scripts\Prnport.vbs" -a -r IP_XXX.XXX.XXX.118color -h XXX.XXX.XXX.118 -o raw -n 9100

cscript "C:\XXXXX\Scripts\Prndrvr.vbs" -a -m "HP Universal Printing PCL 6" -i C:\XXXXX\Drivers\hpzius23.inf

cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -a -p "XXX_Traders_Color" -m "HP Universal Printing PCL 6" -r IP_XXX.XXX.XXX.116color

cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -a -p "XXX_Traders_MOno" -m "HP Universal Printing PCL 6" -r IP_XXX.XXX.XXX.116mono

cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -a -p "XXX_Operators_Color" -m "HP Universal Printing PCL 6" -r IP_XXX.XXX.XXX.118color

cscript "C:\XXXXX\Scripts\Prnmngr.vbs" -a -p "XXX_Operators_MOno" -m "HP Universal Printing PCL 6" -r IP_XXX.XXX.XXX.118mono'

I hit a wall when trying to set the queues with color / mono setting.

Tried two methods:

Via Powershell Set-PrintConfiguration command:

Set-PrintConfiguration –PrinterName "XXX_Traders_Color" -Color "1"

Set-PrintConfiguration –PrinterName "XXX_Traders_MOno" -Color "0"

Set-PrintConfiguration –PrinterName "XXX_Operators_Color" -Color "1"

Set-PrintConfiguration –PrinterName "XXX_Operators_MOno" -Color "0"

I'm getting below (guessing this is not a command present in Win 7 powershell):

The term 'Set-PrintConfiguration' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and
try again.

I tried using the RUNDLL32 PRINTUI.DLL,PrintUIEntry commands to

export printer configuration with changed mono / color setting (works fine)
RUNDLL32 PRINTUI.DLL,PrintUIEntry /Ss /n "XXX_Operators_MOno" /a "c:\temp\Mirek1.dat" d g

import the file created above into new queue:
RUNDLL32 PRINTUI.DLL,PrintUIEntry /Sr /n "NewXXX_Operators_MOno" /a "c:\temp\Mirek1.dat"

But the second command doesn't seem to cause the queue to adjust mono / color setting that was exported in the first instance.

I wonder if anyone here has struggled with similar headache?

Any help much appreciated..

Body:
I got this to work by using the u switch (instead of d g).  That exports "User DevMode":

RUNDLL32 PRINTUI.DLL,PrintUIEntry /Ss /n "XXX_Operators_MOno" /a "c:\temp\Mirek1.dat" u


来源: stackexchange

问:
"Cannot find module 'lodash'" when using import *
I am running the latest version of the angular2 cli 1.0.0-rc.4 and I am having a problem with one of my libraries.

When I try to import the lodash library (or any library) with

import * as _ from 'lodash';

I will get the following error when building:

```<code>ERROR in C:/tfsrepos/Nexus/Nexus/my-app/src/app/app.component.ts (2,20): Cannot find module 'lodash
.)
</code>```

If I instead try to import using the line

```<code>import 'lodash';
</code>```

then it builds fine.  However, now I can't use lodash because I haven't gotten it installed in any namespace.  The following line

```<code>_.fill(array, 'a');
</code>```

produces the error

```<code>Cannot find name '_'.
</code>```

What is the issue here?  My code works fine before I started trying to build using angular cli.

None of the solutions mentioned in this thread: Importing lodash into angular2 + typescript application work for me.

答:
Try use _ directly before from.

import _ from 'lodash';

ContentLicense: CC BY-SA 3.0

Body:
I am running the latest version of the angular2 cli 1.0.0-rc.4 and I am having a problem with one of my libraries.

When I try to import the lodash library (or any library) with

import * as _ from 'lodash';

I will get the following error when building:

ERROR in C:/tfsrepos/Nexus/Nexus/my-app/src/app/app.component.ts (2,20): Cannot find module 'lodash
.)

If I instead try to import using the line

import 'lodash';

then it builds fine.  However, now I can't use lodash because I haven't gotten it installed in any namespace.  The following line

_.fill(array, 'a');

produces the error

Cannot find name '_'.

What is the issue here?  My code works fine before I started trying to build using angular cli.

None of the solutions mentioned in this thread: Importing lodash into angular2 + typescript application work for me.


问:
Hide an element when clicking anywhere outside it
I am trying to have an element be hidden when you click anywhere outside of it.

It is a drop down that appears when you click on the CART link in the top left.  The problem I seem to be facing is two fold.

1) When you click on anything in that button other then just CART, it's showing and then hiding the .cart-dropdown DIV.  I am guessing it's because I'm not targeting the correct classes in this piece of code:

```<code>$(document).click (function (e) {
  if (e.target != $('.cart-dropdown')[0] && e.target != $('.cart-nav-item')[0] && e.target != $('.cart-full')[0]) {
    $('.cart-dropdown').hide();
  }
});
</code>```

2) The .cart-dropdown DIV also closes when you click within it, which is what I want to avoid.  Again this must relate to an error in my syntax / logic in the above piece of code.

Can someone please point me in the correct direction?

Thanks.

答:
If you change the way you're checking the classes and elements, it will work.  See this fiddle for a working example, using the code below:

https://jsfiddle.net/freginold/kv44k1uu/

HTML:

```<code><div>
  A div
</div>
<br>
<div id='cart' class='cart-dropdown'>
  Cart
</div>
<br>
<div>
 Another Div
</div>
</code>```

CSS:

```<code>div {
  border: 1px solid blue;
  margin: 5px;
  display: inline-block;
}
</code>```

JavaScript:

```<code>$(document).click (function (e) {
//alert($(e.target).hasClass("cart-dropdown"));
  if (!$(e.target).hasClass('cart-dropdown') && !$(e.target).hasClass('cart-nav-item') && !$(e.target).hasClass('cart-full')) {
    $('.cart-dropdown').hide();
  }
});
</code>```

You were on the right track; you just had to target the element through jQuery like @Our_Benefactors said, and then change the way you checked the element's class.

Body:
I am trying to have an element be hidden when you click anywhere outside of it.

It is a drop down that appears when you click on the CART link in the top left.  The problem I seem to be facing is two fold.

1) When you click on anything in that button other then just CART, it's showing and then hiding the .cart-dropdown DIV.  I am guessing it's because I'm not targeting the correct classes in this piece of code:

$(document).click (function (e) {
  if (e.target != $('.cart-dropdown')[0] && e.target != $('.cart-nav-item')[0] && e.target != $('.cart-full')[0]) {
    $('.cart-dropdown').hide();
  }
});

2) The .cart-dropdown DIV also closes when you click within it, which is what I want to avoid.  Again this must relate to an error in my syntax / logic in the above piece of code.

Can someone please point me in the correct direction?

Thanks.

Body:
If you change the way you're checking the classes and elements, it will work.  See this fiddle for a working example, using the code below:

https://jsfiddle.net/freginold/kv44k1uu/

HTML:

<div>
  A div
</div>
<br>
<div id='cart' class='cart-dropdown'>
  Cart
</div>
<br>
<div>
 Another Div
</div>

CSS:

div {
  border: 1px solid blue;
  margin: 5px;
  display: inline-block;
}

JavaScript:

$(document).click (function (e) {
//alert($(e.target).hasClass("cart-dropdown"));
  if (!$(e.target).hasClass('cart-dropdown') && !$(e.target).hasClass('cart-nav-item') && !$(e.target).hasClass('cart-full')) {
    $('.cart-dropdown').hide();
  }
});

You were on the right track; you just had to target the element through jQuery like @Our_Benefactors said, and then change the way you checked the element's class.


问:
Averaging dates in oracle sql
Is there a way to average multiple dates in oracle? avg doesn't do any good.

Thanks.

答:
SYSDATE + AVG( dt - SYSDATE )

No need to convert a date to a date. Truncate entire expression if you don't want the time included in result. Truncate the date column (dt) if you don't want times to be used in the computation of the average. MEDIAN is not the same as AVG.

Title: Averaging dates in oracle sql


问:
Using an Android Service to handle a network connection
I'm working on an Android app that needs to maintain a network connection to a chat server. I understand that I can create a service to initiate the connection to the server, but how would the service notify an Android Activity of new incoming messages? The Activity would need to update the view to show the new messages. I'm pretty new to Android, so any help is appreciated. Thanks!</p>

答:
One common and useful approach is to register a broadcast receiver in your Activity, and have the Service send out notification events when it has useful data. I find this to be easier to manage than implementing a handler via a callback, mainly because it makes it easier and safer when there is a configuration change. If you pass a direct Activity-reference to the Service then you have to be very careful to clear it when the Activity is destroyed (during rotation, or backgrounding), otherwise you get a leak.

With a Broadcast Receiver you still have to unregister when the Activity is being destroyed, however the Service never has a direct reference to the Activity so if you forget the Activity will not be leaked. It is also easier to have the Activity register to listen to a topic when it is created, since it never has to obtain a direct reference to the Service...

Lars Vogel's article discusses this approach, it is definitely worth reading! http://www.vogella.com/tutorials/AndroidServices/article.html#using-receiver


问:
Visual Studio can't 'see' my included header files
I created an empty 'Demo' project in Visual Studio 2008 and added some existing projects to my solution. Included "MyHeader.h" (other project's header) in main.cpp file which is in 'Demo'. Also added header files' path in "Tools/Option/VC++ Directories/Include files" section. But intellisense says: "File MyHeader.h not found in current source file's directory or in build system paths..."

How the problem can be fixed?

答: If the visual studio says that you miss some file in the current source file folder, there is one solution that i used. Just right click the file you want to add and choose Open Document, if it really doesn't exist, then you should see something like cannot find file in the source file path = "somewhere in your computer", then what you could do is the add your source file into that path first and see if it works.

ContentLicense: CC BY-SA 4.0


问:
Problem with max SQL function
I have this code in PHP

```<code>$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)){
    echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
echo "<br>".$maxnum."hh";
</code>```

then the output be:

The max num is this is it

hh

Why didn't the query get the max number?

The table is called info and it has these fields, ID, num, title, description, and answer.

After editing:

I tried my query in MySQL and it works fine!

"SELECT MAX(num) FROM info"

and this is my complete code if it can help:

```<code><?php
    $answer=$_GET["answerbox"];
    $ID=$_GET["TheID"];

    $host="localhost";
    $username="root";
    $password="";
    $db_name="game";
    mysql_connect("$host","$username","$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");

    $max="SELECT MAX(num) FROM info";
    $maxquery= mysql_query($max) or die (died);
    while($row = mysql_fetch_array($maxquery)) {
        echo "The max num is ". $row['num']."this is it";
    }

    $maxnum= mysql_fetch_array($maxquery);
    $sql="SELECT * FROM info  WHERE ID=".$ID;
    $query = mysql_query($sql) or die(errorquery);
    $row = mysql_fetch_array($query);
    $trueanswer = $row['Answer'];
    $num=$row['num'];
    if ($num<$maxnum)
    {
        $numto= $num +1 ;
        echo "<br>".$maxnum."hh";
    }
?>
</code>```

答:
Then the code will be</p>

```<code>$max="SELECT MAX(num) as num FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_assoc($maxquery)) {
    echo "The max num is ". $row['num']."this is it";
}
</code>```

ContentLicense: CC BY-SA 2.5

Title: Problem with max SQL function

Body:
I have this code in PHP

$max="SELECT MAX(num) FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_array($maxquery)){
    echo "The max num is ". $row['num']."this is it";
}
$maxnum= mysql_fetch_array($maxquery);
echo "
".$maxnum."hh";

then the output be:

The max num is this is it

hh

Why didn't the query get the max number?

The table is called info and it has these fields, ID, num, title, description, and answer.

After editing:

I tried my query in MySQL and it works fine!

"SELECT MAX(num) FROM info"

and this is my complete code if it can help:

<?php
    $answer=$_GET["answerbox"];
    $ID=$_GET["TheID"];

    $host="localhost";
    $username="root";
    $password="";
    $db_name="game";
    mysql_connect("$host","$username","$password")or die("cannot connect");
    mysql_select_db("$db_name")or die("cannot select DB");

    $max="SELECT MAX(num) FROM info";
    $maxquery= mysql_query($max) or die (died);
    while($row = mysql_fetch_array($maxquery)) {
        echo "The max num is ". $row['num']."this is it";
    }

    $maxnum= mysql_fetch_array($maxquery);
    $sql="SELECT * FROM info  WHERE ID=".$ID;
    $query = mysql_query($sql) or die(errorquery);
    $row = mysql_fetch_array($query);
    $trueanswer = $row['Answer'];
    $num=$row['num'];
    if ($num<$maxnum)
    {
        $numto= $num +1 ;
        echo "
".$maxnum."hh";
    }
?>

Body:
Then the code will be

$max="SELECT MAX(num) as num FROM info";
$maxquery= mysql_query($max) or die (died);
while($row = mysql_fetch_assoc($maxquery)) {
    echo "The max num is ". $row['num']."this is it";
}


问:
Issues using Oracle case function
i'm trying to find the create a query that will return a set of staff's last name with their attached grade level (which is in another table with no foreign key relationship available with the staff one).

So far i have this but it is returning a "missing keyword" error on it. What is wrong with it?/ have i got my logic very wrong?

The last name and salary are in the staff/employee table.
The grade level is in a Job grades table.

```<code>    select last_name, salary,
CASE grade_level
WHEN  lowest_sal >= 1000 THEN 'A'
WHEN lowest_sal >= 3000  THEN 'B'
WHEN lowest_sal >= 6000 THEN 'C'
WHEN lowest_sal >= 10000 THEN 'D'
WHEN lowest_sal >= 15000  THEN 'E'
ELSE 'F'
END
FROM employees, job_grades
WHERE department_id > 50;
</code>```

答:
To everyone possibly coming across this. I was slightly stupid in that i didn't need to use a CASE but if you need to then check out the above answer which provides the right answer. </p>

<p>Below is the code that worked for me. It basically is using the JOIN ON clause to join 2 tables without a relationship. </p>

```<code> select last_name, salary, grade_level
FROM employees JOIN job_grades ON (salary BETWEEN lowest_sal AND highest_sal)
WHERE department_id > 50;
</code>```

Title: Issues using Oracle case function

Body:
i'm trying to find the create a query that will return a set of staff's last name with their attached grade level (which is in another table with no foreign key relationship available with the staff one).

So far i have this but it is returning a "missing keyword" error on it. What is wrong with it?/ have i got my logic very wrong?

The last name and salary are in the staff/employee table.
The grade level is in a Job grades table.

    select last_name, salary,
CASE grade_level
WHEN  lowest_sal >= 1000 THEN 'A'
WHEN lowest_sal >= 3000  THEN 'B'
WHEN lowest_sal >= 6000 THEN 'C'
WHEN lowest_sal >= 10000 THEN 'D'
WHEN lowest_sal >= 15000  THEN 'E'
ELSE 'F'
END
FROM employees, job_grades
WHERE department_id > 50;

Body:
To everyone possibly coming across this. I was slightly stupid in that i didn't need to use a CASE but if you need to then check out the above answer which provides the right answer.

Below is the code that worked for me. It basically is using the JOIN ON clause to join 2 tables without a relationship.

 select last_name, salary, grade_level
FROM employees JOIN job_grades ON (salary BETWEEN lowest_sal AND highest_sal)
WHERE department_id > 50;


问:
Kafka State Store low level API persist into ROCKDB ? if yes then is there any documentation for configuration for ROCK DB
Kafka State Store low level API  persist into ROCKDB ? if yes then is there any documentation for configuration for ROCK DB . If no then what is using for low level API
Stores.create().withKeys().withValues().persistent().build(); </p>

答:
You can use provide your custom RocksDB configs by implementing RocksDBConfigSetter interface and add you implementation class to StreamsConifg:

```<code>streamsConfig.put(StreamsConfig.ROCKSDB_CONFIG_SETTER_CLASS_CONFIG, CustomRocksDBConfig.class);
</code>```

See: http://docs.confluent.io/current/streams/developer-guide.html#non-streams-configuration-parameters

Body:
You can use provide your custom RocksDB configs by implementing RocksDBConfigSetter interface and add you implementation class to StreamsConifg:

streamsConfig.put(StreamsConfig.ROCKSDB_CONFIG_SETTER_CLASS_CONFIG, CustomRocksDBConfig.class);

See: http://docs.confluent.io/current/streams/developer-guide.html#non-streams-configuration-parameters


问:
Tensorflow GPU Memory exhausted during mean squared error
I have a Tensorflow model with is a recurrent neural network using long short term memory. The state size is 3000, each time step of input has 300 inputs, there are about 500 time steps, and 1 output for each time step. I am training a sequence-to-sequence model.

It runs fine for inputs with less than 500 time steps, but somewhere around 500 timesteps, it crashes with the following out of memory error:

```<code>ResourceExhaustedError (see above for traceback): OOM when allocating tensor with shape[20375,20375]
     [[Node: gradients/mean_squared_error/Mul_grad/mul_1 = Mul[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](mean_squared_error/Square, gradients/mean_squared_error/Sum_grad/Tile)]]
     [[Node: gradients/MatMul_grad/tuple/control_dependency_1/_225 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_5086_gradients/MatMul_grad/tuple/control_dependency_1", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]
</code>```

And this is running on a GPU with 12gb of memory.

I have tried running it on my laptop cpu, and it seems to use very little memory (about 1 to 2 gb), but it's so slow that it never did get to 500 time steps. I'm working on some changes that will make it skip to 500 time steps to see how much memory it uses when not running on a GPU.

My questions is: Where could Tensorflow possibly want to allocate a tensor of shape [20375, 20375]? It seems to be related to the tf.mean_squared_error function, but that doesn't seem like an operation that should require such exorbitant amounts of memory.

I have tried reducing the batch size, but that just pushes the failure point up to a few more time steps, and I'll need up to a few thousand time steps, so this doesn't seem like a good long-term solution. I'd prefer to get to the root of the problem.

Here is the relevant code for the mean squared error:

```<code>initial_state_tuple = tf.contrib.rnn.LSTMStateTuple(initial_state, initial_hidden_state)

# Create the actual RNN
with tf.variable_scope(VARIABLE_SCOPE, reuse=None):
    cell = tf.contrib.rnn.BasicLSTMCell(STATE_SIZE)
    rnn_outputs, finalstate = tf.nn.dynamic_rnn(cell=cell, inputs=networkinput,
                                                initial_state=initial_state_tuple)

with tf.variable_scope(VARIABLE_SCOPE, reuse=True):
    weights = tf.get_variable(name=WEIGHTS_NAME, shape=[STATE_SIZE, 1], dtype=tf.float32)
    biases = tf.get_variable(name=BIASES_NAME, shape=[1], dtype=tf.float32)

# Build the output layers
rnn_outputs_reshaped = tf.reshape(rnn_outputs, [-1, STATE_SIZE])
network_outputs = tf.sigmoid(tf.matmul(rnn_outputs_reshaped, weights) + biases)
expected_outputs_reshaped = tf.reshape(expected_outputs, [-1, 1])

# Loss mask just cancels out the inputs that are padding characters, since not all inputs have the same number of time steps
loss_mask_reshaped = tf.reshape(loss_mask, shape=[-1])

expected_outputs_reshaped = loss_mask_reshaped * expected_outputs_reshaped
network_outputs = loss_mask_reshaped * network_outputs

loss = tf.losses.mean_squared_error(labels=expected_outputs_reshaped, predictions=network_outputs)
</code>```

If you want all of the code, it can be found here. The relevant functions are buildtower() and buildgraph(). The constants NUM_GPUS and BATCH_SIZE are set to appropriate values when running on the machine with the GPUs.

Update: I replaced the line

```<code>loss = tf.losses.mean_squared_error(labels=expected_outputs_reshaped, predictions=network_outputs)
</code>```

with

```<code>error_squared = tf.pow(expected_outputs_reshaped - network_outputs, 2)
loss = tf.reduce_mean(error_squared)
</code>```

and the same error happened. I reduced the state size to 30 and the batch size to 5, and the error still happened, although it did make it up to about 3000 time steps.

Update: After doing some research, I have found that, when training an RNN with a large number of time steps, truncated backpropagation is often used. This leads me to believe that backpropagation through a large number of time steps inherently takes a lot of memory, and my issue is not that I've constructed my graph wrong, but that I have a fundamental misunderstanding of the resource requirements of gradient calculations. To this end, I am working on changing my code to use truncated backpropagation. I will report back with results.

答:
This project is my first experience with machine learning and Tensorflow, and after doing some research, it seems I had some fundamental misunderstandings.

I had thought that memory usage would scale linearly with the number of time steps in my data. Because every other dimension of my model (Batch size, state size) was small, I expected that I could get up to quite a few time steps before running out of memory. However, it seems that memory usage of computing the gradients scales exponentially with the number of time steps, so no matter how small I made the state size and batch size, it would eventually exhaust all my memory because of the large number of time steps.

To deal with this, I am using truncated backpropagation, in which each batch is broken up into chunks of some fixed number of time steps. This is not perfect, because it means that errors can only be propagated back at most this many time steps. However, based on what I've found online, it seems to work well enough, and there's not too many other ways to get around the memory usage issue.

As I said before, this is all my first experience with machine learning, so if anything in here is blatantly wrong, please tell me.

Body:
I have a Tensorflow model with is a recurrent neural network using long short term memory. The state size is 3000, each time step of input has 300 inputs, there are about 500 time steps, and 1 output for each time step. I am training a sequence-to-sequence model.

It runs fine for inputs with less than 500 time steps, but somewhere around 500 timesteps, it crashes with the following out of memory error:

ResourceExhaustedError (see above for traceback): OOM when allocating tensor with shape[20375,20375]
     [[Node: gradients/mean_squared_error/Mul_grad/mul_1 = Mul[T=DT_FLOAT, _device="/job:localhost/replica:0/task:0/gpu:0"](mean_squared_error/Square, gradients/mean_squared_error/Sum_grad/Tile)]]
     [[Node: gradients/MatMul_grad/tuple/control_dependency_1/_225 = _Recv[client_terminated=false, recv_device="/job:localhost/replica:0/task:0/cpu:0", send_device="/job:localhost/replica:0/task:0/gpu:0", send_device_incarnation=1, tensor_name="edge_5086_gradients/MatMul_grad/tuple/control_dependency_1", tensor_type=DT_FLOAT, _device="/job:localhost/replica:0/task:0/cpu:0"]()]]

And this is running on a GPU with 12gb of memory.

I have tried running it on my laptop cpu, and it seems to use very little memory (about 1 to 2 gb), but it's so slow that it never did get to 500 time steps. I'm working on some changes that will make it skip to 500 time steps to see how much memory it uses when not running on a GPU.

My questions is: Where could Tensorflow possibly want to allocate a tensor of shape [20375, 20375]? It seems to be related to the tf.mean_squared_error function, but that doesn't seem like an operation that should require such exorbitant amounts of memory.

I have tried reducing the batch size, but that just pushes the failure point up to a few more time steps, and I'll need up to a few thousand time steps, so this doesn't seem like a good long-term solution. I'd prefer to get to the root of the problem.

Here is the relevant code for the mean squared error:

initial_state_tuple = tf.contrib.rnn.LSTMStateTuple(initial_state, initial_hidden_state)

# Create the actual RNN
with tf.variable_scope(VARIABLE_SCOPE, reuse=None):
    cell = tf.contrib.rnn.BasicLSTMCell(STATE_SIZE)
    rnn_outputs, finalstate = tf.nn.dynamic_rnn(cell=cell, inputs=networkinput,
                                                initial_state=initial_state_tuple)

with tf.variable_scope(VARIABLE_SCOPE, reuse=True):
    weights = tf.get_variable(name=WEIGHTS_NAME, shape=[STATE_SIZE, 1], dtype=tf.float32)
    biases = tf.get_variable(name=BIASES_NAME, shape=[1], dtype=tf.float32)

# Build the output layers
rnn_outputs_reshaped = tf.reshape(rnn_outputs, [-1, STATE_SIZE])
network_outputs = tf.sigmoid(tf.matmul(rnn_outputs_reshaped, weights) + biases)
expected_outputs_reshaped = tf.reshape(expected_outputs, [-1, 1])

# Loss mask just cancels out the inputs that are padding characters, since not all inputs have the same number of time steps
loss_mask_reshaped = tf.reshape(loss_mask, shape=[-1])

expected_outputs_reshaped = loss_mask_reshaped * expected_outputs_reshaped
network_outputs = loss_mask_reshaped * network_outputs

loss = tf.losses.mean_squared_error(labels=expected_outputs_reshaped, predictions=network_outputs)

If you want all of the code, it can be found here. The relevant functions are buildtower() and buildgraph(). The constants NUM_GPUS and BATCH_SIZE are set to appropriate values when running on the machine with the GPUs.

Update: I replaced the line

loss = tf.losses.mean_squared_error(labels=expected_outputs_reshaped, predictions=network_outputs)

with

error_squared = tf.pow(expected_outputs_reshaped - network_outputs, 2)
loss = tf.reduce_mean(error_squared)

and the same error happened. I reduced the state size to 30 and the batch size to 5, and the error still happened, although it did make it up to about 3000 time steps.

Update: After doing some research, I have found that, when training an RNN with a large number of time steps, truncated backpropagation is often used. This leads me to believe that backpropagation through a large number of time steps inherently takes a lot of memory, and my issue is not that I've constructed my graph wrong, but that I have a fundamental misunderstanding of the resource requirements of gradient calculations. To this end, I am working on changing my code to use truncated backpropagation. I will report back with results.


问:
How to run externally
I have plotted a graph from a CSV file using SPYDER from PYTHON

Here is my code

```<code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv('GM_NB_Replica_Test.csv', skiprows=8)

data = df.ix[:,19:116].T

data.columns=df['SN']
data.plot()
plt.show()`
</code>```

Here is my Output inside the python console:

How do i get this to run externally (Not inside python console, and not in new python console)

I have already tried changing the run settings (See photo below)

However it just gives me a black Python CMD and then no graph.

any thoughts?

current error when running in CMD

答:
From your command prompt (CMD):</p>

```<code>cd C://location_of_your_script
python script.py
</code>```

Title: How to run externally

Body:
I have plotted a graph from a CSV file using SPYDER from PYTHON

Here is my code

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv('GM_NB_Replica_Test.csv', skiprows=8)

data = df.ix[:,19:116].T

data.columns=df['SN']
data.plot()
plt.show()`

Here is my Output inside the python console:

How do i get this to run externally (Not inside python console, and not in new python console)

I have already tried changing the run settings (See photo below)

However it just gives me a black Python CMD and then no graph.

any thoughts?

current error when running in CMD

Body:
From your command prompt (CMD):

cd C://location_of_your_script
python script.py


问:
convert csv file to matrix in R
I have a csv file

```<code> User_name    M_User    Total
    user 1    user 2     7
    user 1    user 3     19
    user 1    user 7     5
    user 3    user 2     1
    user 2    user 7     1
</code>```

and I want to convert it in matrix form

```<code>            user 1  user 2  user 3  user 7
user 1        0        7     19       5
user 3        0        1      0       0
user 2        0        0      0       1
user 7        0        0      0       0
</code>```

what I;m doing right now is something like this

```<code>require(reshape2)
m <- as.matrix(dcast(df, USER_NAME ~ M_USER, value.var = "TOTAL", fill=0))[,1:4]
</code>```

but the answer I get is

```<code> USER_NAME   user 2 user 3 user 7
[1,] "user 1"  "7"    "19"   "5"
[2,] "user 2"  "0"    " 0"   "1"
[3,] "user 3"  "1"    " 0"   "0"
</code>```

How can I modify the code so that I get this matrix

```<code>            user 1 user 2 user 3  user 7
user 1        0        7     19       5
user 3        0        1      0       0
user 2        0        0      0       1
user 7        0        0      0       0
</code>```

答:
We can do this with xtabs from base R

```<code>xtabs(Total ~User_name + M_User, df, drop = FALSE)
#         M_User
#User_name user 1 user 2 user 3 user 7
#  user 1      0      7     19      5
#  user 2      0      0      0      1
#  user 3      0      1      0      0
#  user 7      0      0      0      0
</code>```

Also, there is acast from reshape2 which gives a matrix output

```<code>library(reshape2)
acast(df, User_name ~ M_User, value.var = "Total", fill=0, drop = FALSE)
#       user 1 user 2 user 3 user 7
#user 1      0      7     19      5
#user 2      0      0      0      1
#user 3      0      1      0      0
#user 7      0      0      0      0
</code>```

data

```<code>df <- structure(list(User_name = structure(c(1L, 1L, 1L, 3L, 2L), .Label = c("user 1",
"user 2", "user 3", "user 7"), class = "factor"), M_User = structure(c(2L,
3L, 4L, 2L, 4L), .Label = c("user 1", "user 2", "user 3", "user 7"
), class = "factor"), Total = c(7L, 19L, 5L, 1L, 1L)), .Names = c("User_name",
"M_User", "Total"), row.names = c(NA, -5L), class = "data.frame")
</code>```

Title: convert csv file to matrix in R

Body:
I have a csv file

 User_name    M_User    Total
    user 1    user 2     7
    user 1    user 3     19
    user 1    user 7     5
    user 3    user 2     1
    user 2    user 7     1

and I want to convert it in matrix form

            user 1  user 2  user 3  user 7
user 1        0        7     19       5
user 3        0        1      0       0
user 2        0        0      0       1
user 7        0        0      0       0

what I;m doing right now is something like this

require(reshape2)
m <- as.matrix(dcast(df, USER_NAME ~ M_USER, value.var = "TOTAL", fill=0))[,1:4]

but the answer I get is

 USER_NAME   user 2 user 3 user 7
[1,] "user 1"  "7"    "19"   "5"
[2,] "user 2"  "0"    " 0"   "1"
[3,] "user 3"  "1"    " 0"   "0"

How can I modify the code so that I get this matrix

            user 1 user 2 user 3  user 7
user 1        0        7     19       5
user 3        0        1      0       0
user 2        0        0      0       1
user 7        0        0      0       0

Body:
We can do this with xtabs from base R

xtabs(Total ~User_name + M_User, df, drop = FALSE)
#         M_User
#User_name user 1 user 2 user 3 user 7
#  user 1      0      7     19      5
#  user 2      0      0      0      1
#  user 3      0      1      0      0
#  user 7      0      0      0      0

Also, there is acast from reshape2 which gives a matrix output

library(reshape2)
acast(df, User_name ~ M_User, value.var = "Total", fill=0, drop = FALSE)
#       user 1 user 2 user 3 user 7
#user 1      0      7     19      5
#user 2      0      0      0      1
#user 3      0      1      0      0
#user 7      0      0      0      0

data

df <- structure(list(User_name = structure(c(1L, 1L, 1L, 3L, 2L), .Label = c("user 1",
"user 2", "user 3", "user 7"), class = "factor"), M_User = structure(c(2L,
3L, 4L, 2L, 4L), .Label = c("user 1", "user 2", "user 3", "user 7"
), class = "factor"), Total = c(7L, 19L, 5L, 1L, 1L)), .Names = c("User_name",
"M_User", "Total"), row.names = c(NA, -5L), class = "data.frame")


问:
Is there a way to ensure a specific visual studio project in a visual studio solution is only built on a build server (or a specific server)
Basically I want to block developers from building one of the projects in a solution that only the build server can/should build.

Alternatively, Developers would have a solution with projects A, B, C but not D. However, The build server would add project D to the solution. Then build the solution with projects A,B,C, & D.

Can this be done through code and/or configuration?

Thanks

答:
Not really - if code is available it can be built by developers. One can create project file from source and build it to be able to debug the code for example.

You can use NuGet to import pre-built assemblies - this way you discourage building such code locally.

Note: make sure you understand reasons why one would want to build that code locally - debugging is very common reason and degrading debugging experience will slow your team down.


问:
PHP Script does not seem to work
I run a script on my webspace which is used for an android application. Though, it does not seem to work. On some webspaces I get a blank site when I try reaching it, on others I receive a 500 Internal Server Error. Though this script should work properly because it used to do so.

It is supposed to get all information from a table and echo it after some INNER JOINs. I could not track the error even after some mysqli_error checks and some echos to check variables etc.

The variable $con does exist, the connection should work properly. I just removed it for stack overflow ^^.

```<code> <?php

$subId = 1;

$sql = "SELECT articles.a_id, sciences.science, articles.title, articles.content, login.username, articles.date, articles.viewed, articles.timestamp FROM articles
                INNER JOIN sciences ON articles.s_id = sciences.s_id
                INNER JOIN login ON articles.author = login.id
                WHERE articles.s_id = ".$subId."
                ORDER BY timestamp DESC";

if (!$res = mysqli_query($con,$sql)) {
    echo "FAIL";
    echo mysqli_error($con);
}
else {

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('a_id'=>$row[0],
'science'=>$row[1],
'title'=>$row[2],
'content'=>$row[3],
'author'=>$row[4],
'date'=>$row[5],
'viewed'=>$row[6],
'timestamp'=>$row[7]
));
}

echo json_encode(array("result"=>$result));
}
mysqli_close($con);

?>
</code>```

EDIT: I updated my code:

```<code>    <?php

$subId = 1;

$con = mysqli_connect("HOST", "USER", "PASSWORD", "DATABASE");

if (!$con)
{
echo "Cant't connect to MySQL.<br>";
echo "Debug: " . mysqli_connect_errno()
}

$sql = "SELECT articles.a_id, sciences.science, articles.title, articles.content, login.username, articles.date, articles.viewed, articles.timestamp FROM articles
INNER JOIN sciences ON articles.s_id = sciences.s_id
INNER JOIN login ON articles.author = login.id
WHERE articles.s_id = ".$subId."
ORDER BY timestamp DESC";

if (!$res = $con->query($sql))
{
    echo "FAIL";
}
else
{

    $result = array();

    while($row = $con->fetchArray($res))
    {
        array_push($result); //use the query to rename fields, if needed
    }

    echo json_encode(array("result"=>$result));
}

?>
</code>```

答:
Try using the error reporting in PHP. Enable error reporting by adding the following lines at the start of your code.</p>

```<code>ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);
</code>```

Title: PHP Script does not seem to work

Body:
I run a script on my webspace which is used for an android application. Though, it does not seem to work. On some webspaces I get a blank site when I try reaching it, on others I receive a 500 Internal Server Error. Though this script should work properly because it used to do so.

It is supposed to get all information from a table and echo it after some INNER JOINs. I could not track the error even after some mysqli_error checks and some echos to check variables etc.

The variable $con does exist, the connection should work properly. I just removed it for stack overflow ^^.

 <?php

$subId = 1;

$sql = "SELECT articles.a_id, sciences.science, articles.title, articles.content, login.username, articles.date, articles.viewed, articles.timestamp FROM articles
                INNER JOIN sciences ON articles.s_id = sciences.s_id
                INNER JOIN login ON articles.author = login.id
                WHERE articles.s_id = ".$subId."
                ORDER BY timestamp DESC";

if (!$res = mysqli_query($con,$sql)) {
    echo "FAIL";
    echo mysqli_error($con);
}
else {

$result = array();

while($row = mysqli_fetch_array($res)){
array_push($result,
array('a_id'=>$row[0],
'science'=>$row[1],
'title'=>$row[2],
'content'=>$row[3],
'author'=>$row[4],
'date'=>$row[5],
'viewed'=>$row[6],
'timestamp'=>$row[7]
));
}

echo json_encode(array("result"=>$result));
}
mysqli_close($con);

?>

EDIT: I updated my code:

    <?php

$subId = 1;

$con = mysqli_connect("HOST", "USER", "PASSWORD", "DATABASE");

if (!$con)
{
echo "Cant't connect to MySQL.
";
echo "Debug: " . mysqli_connect_errno()
}

$sql = "SELECT articles.a_id, sciences.science, articles.title, articles.content, login.username, articles.date, articles.viewed, articles.timestamp FROM articles
INNER JOIN sciences ON articles.s_id = sciences.s_id
INNER JOIN login ON articles.author = login.id
WHERE articles.s_id = ".$subId."
ORDER BY timestamp DESC";

if (!$res = $con->query($sql))
{
    echo "FAIL";
}
else
{

    $result = array();

    while($row = $con->fetchArray($res))
    {
        array_push($result); //use the query to rename fields, if needed
    }

    echo json_encode(array("result"=>$result));
}

?>

Body:
Try using the error reporting in PHP. Enable error reporting by adding the following lines at the start of your code.

ini_set('display_startup_errors', 1);
ini_set('display_errors', 1);
error_reporting(-1);


问:
is it considered bad practice to write c code in objective-c / cocoa framework?
I am writing some Objective-C code which will be publicly available. The code mainly consists of well known algorithms which would benefit from optimization. I am planning on writing most of the code in C to reduce the overhead on creating objects and garbage collection. Is this considered bad practice?</p>

答:
Premature optimisation is the root of all evil

Whether it is good practice or not depends entirely upon the application.  In most cases, I would say write it in Objective-C first then use a profiler for optimisation if it is too slow.

However, there are cases where you know you'll be needing to do optimisation, for example if you are writing a language interpreter or a CPU emulation.  In those cases (and in cases where profiling shows a bottleneck) it's perfectly fine to write pure C.


问:
org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='eError']"}
I am trying to validate a login section with all valid and invalid inputs.

here is the code i have tried:

```<code>
    public void login_Valid_Invalid_Combinations() throws BiffException, IOException, InterruptedException
    {
      String FilePath = "D://credentials.xls";
      FileInputStream FIS = new FileInputStream(FilePath);
      Workbook WB = Workbook.getWorkbook(FIS);
      Sheet SH = WB.getSheet(0);
      for(int row =0; row<= SH.getRows()-1; row++)
      {
          String userNAME = SH.getCell(0, row).getContents();
          String passWORD = SH.getCell(1, row).getContents();
          System.out.println("USERMANE : "+userNAME + "  PASSWORD : "+passWORD);
          driver.get("LOGIN PAGE URL");
          driver.findElement(By.id("Email")).sendKeys(userNAME);
          driver.findElement(By.id("Password")).sendKeys(passWORD);
          driver.findElement(By.id("btnlogin")).click();
          System.out.println(driver.findElement(By.xpath("//*[@id='eError']")).getText());
          Thread.sleep(2000);
          String URL = driver.getCurrentUrl();
          System.out.println(URL);
          if (URL.equals("URL AFTER SUCCESFULL LOGIN"))
          {
              System.out.println("Login Successfull");
          }
          else
          {
              System.out.println("Login Failed");
          }
      }
      driver.close();
    }
```

I want to show the error message each time login failed, which is working fine. But when login is successful with valid inputs, it's showing:

"org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='eError']"}"

as the error message is not coming for successful login.

Can you please help me how to handle this.

答:
You can replace the line

```<code>System.out.println(driver.findElement(By.xpath("//*[@id='eError']")).getText());
</code>```

with this:

```<code>try {
    WebElement elem = driver.findElement(By.xpath("//*[@id='eError']"));
    System.out.println(elem.getText());
}
catch(Exception e) {
    // do nothing
}
</code>```

The above code in try block finds the element with the xpath. If it is present, it goes on to next line to print the text. If the element is not present, the exception will be thrown and will be caught in the catch block and continue safely.

Body:
I am trying to validate a login section with all valid and invalid inputs.

here is the code i have tried:

    public void login_Valid_Invalid_Combinations() throws BiffException, IOException, InterruptedException
    {
      String FilePath = "D://credentials.xls";
      FileInputStream FIS = new FileInputStream(FilePath);
      Workbook WB = Workbook.getWorkbook(FIS);
      Sheet SH = WB.getSheet(0);
      for(int row =0; row<= SH.getRows()-1; row++)
      {
          String userNAME = SH.getCell(0, row).getContents();
          String passWORD = SH.getCell(1, row).getContents();
          System.out.println("USERMANE : "+userNAME + "  PASSWORD : "+passWORD);
          driver.get("LOGIN PAGE URL");
          driver.findElement(By.id("Email")).sendKeys(userNAME);
          driver.findElement(By.id("Password")).sendKeys(passWORD);
          driver.findElement(By.id("btnlogin")).click();
          System.out.println(driver.findElement(By.xpath("//*[@id='eError']")).getText());
          Thread.sleep(2000);
          String URL = driver.getCurrentUrl();
          System.out.println(URL);
          if (URL.equals("URL AFTER SUCCESFULL LOGIN"))
          {
              System.out.println("Login Successfull");
          }
          else
          {
              System.out.println("Login Failed");
          }
      }
      driver.close();
    }

I want to show the error message each time login failed, which is working fine. But when login is successful with valid inputs, it's showing:

"org.openqa.selenium.NoSuchElementException: no such element: Unable to locate element: {"method":"xpath","selector":"//*[@id='eError']"}"

as the error message is not coming for successful login.

Can you please help me how to handle this.

Body:
You can replace the line

System.out.println(driver.findElement(By.xpath("//*[@id='eError']")).getText());

with this:

try {
    WebElement elem = driver.findElement(By.xpath("//*[@id='eError']"));
    System.out.println(elem.getText());
}
catch(Exception e) {
    // do nothing
}

The above code in try block finds the element with the xpath. If it is present, it goes on to next line to print the text. If the element is not present, the exception will be thrown and will be caught in the catch block and continue safely.


问:
What is the fastest way to serialize to ByteBuffer?
I would like to write serializer for Ehcache of Optional class. I know, that optional member is seriazizable, so I write:

```<code>@Override
   public ByteBuffer serialize(Optional object) throws SerializerException {

      if( object.isPresent() ) {
         try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            return ByteBuffer.wrap(baos.toByteArray()); // excess copying
         } catch (IOException e) {
            throw new AssertionError(e);
         }

      }
      else {
         return ByteBuffer.wrap(new byte[] {});
      }
   }

   @Override
   public Optional read(ByteBuffer binary) throws ClassNotFoundException, SerializerException {
      if( binary.array().length > 0 ) {
         try {
            byte[] buf = binary.array();
            ByteArrayInputStream bais = new ByteArrayInputStream(buf);
            ObjectInputStream ois = new ObjectInputStream(bais);
            Object object = ois.readObject();
            return Optional.of(object);
         } catch (IOException e) {
            throw new AssertionError(e);
         }
      }
      else {
         return Optional.empty();
      }
   }
</code>```

I confused by commented line, which includes excess copying of data. Can I avoid it and serialize directly with ByteBuffer?

While does Ehcache seriazliers based of ByteBuffer?

答: ByteBuffer.wrap() doesn't actually copy data. As the name implies it wraps the array, so any changes to the original array would also be reflected in the buffer.

Body:
I would like to write serializer for Ehcache of Optional class. I know, that optional member is seriazizable, so I write:

@Override
   public ByteBuffer serialize(Optional object) throws SerializerException {

      if( object.isPresent() ) {
         try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(object);
            return ByteBuffer.wrap(baos.toByteArray()); // excess copying
         } catch (IOException e) {
            throw new AssertionError(e);
         }

      }
      else {
         return ByteBuffer.wrap(new byte[] {});
      }
   }

   @Override
   public Optional read(ByteBuffer binary) throws ClassNotFoundException, SerializerException {
      if( binary.array().length > 0 ) {
         try {
            byte[] buf = binary.array();
            ByteArrayInputStream bais = new ByteArrayInputStream(buf);
            ObjectInputStream ois = new ObjectInputStream(bais);
            Object object = ois.readObject();
            return Optional.of(object);
         } catch (IOException e) {
            throw new AssertionError(e);
         }
      }
      else {
         return Optional.empty();
      }
   }

I confused by commented line, which includes excess copying of data. Can I avoid it and serialize directly with ByteBuffer?

While does Ehcache seriazliers based of ByteBuffer?


问:
SSIS OleDb error redirect fails with flatfile destination
I have an ssis package that reads an OLEDB Source and writes to a Flat File Destination , where I've tried to redirect errors, but it doesn't seem to be working.

The transforms look like this:

The error redirect looks like:

But when I run the package, I get this in the execution results:

So, i have a truncation error, the redirect should capture that, right?

答: So, I was trying to catch a truncation error, and the only way I could find that worked was a conditional output, any csv field values larger that my db table were redirected to a output file that was emailed.


问:
Remove items of list from another lists with criteria
i have a list of writers.

```<code>public class Writers{
    long WriterID { get;set; }
}
</code>```

Also I have two lists of type Article.

```<code>public class Article{
    long ArticleID { get; set; }
    long WriterID { get; set; }
    //and others
}
</code>```

so the code i have is:

```<code>List<Article> ArticleList = GetList(1);
List<Article> AnotherArticleList = AnotherList(2);
List<Writers> listWriters = GetAllForbiddenWriters();
</code>```

I want to remove those records from ArticleList, AnotherArticleList where WriterID matches from listWriters WriterID. How to do this in LINQ?

答: Just a design tip, your class should be called Writer (singular form), not Writers (plural). Each item in your list represents a single writer, correct?

Body:
i have a list of writers.

public class Writers{
    long WriterID { get;set; }
}

Also I have two lists of type Article.

public class Article{
    long ArticleID { get; set; }
    long WriterID { get; set; }
    //and others
}

so the code i have is:

List
 ArticleList = GetList(1);
List
 AnotherArticleList = AnotherList(2);
List<Writers> listWriters = GetAllForbiddenWriters();

I want to remove those records from ArticleList, AnotherArticleList where WriterID matches from listWriters WriterID. How to do this in LINQ?


问:
Swift Repetitive URLSession Creates Massive Memory Leaks
I have an application that (in part) displays the current download speed of a Wi-Fi connection to a user. It does so by opening a URLSession and downloading a moderate-sized (~10MB) file and measuring the time it took.

Here's that URLSession function:

```<code>func testSpeed() {

    Globals.shared.dlStartTime = Date()
    Globals.shared.DownComplete = false

    if Globals.shared.currentSSID == "" {
        Globals.shared.bandwidth = 0
        Globals.shared.DownComplete = true
    } else {

        let url = URL(string: [HIDDEN])
        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
        let task = session.downloadTask(with: url!)

        task.resume()
    }
}

public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {

    Globals.shared.dlFileSize = (Double(totalBytesExpectedToWrite) * 8) / 1000
    let progress = (Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)) * 100.0

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessUpdating"), object: nil, userInfo: ["progress" : progress])
}

public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    let elapsed = Double( Date().timeIntervalSince(Globals.shared.dlStartTime))
    Globals.shared.bandwidth = Int(Globals.shared.dlFileSize / elapsed)
    Globals.shared.DownComplete = true
    Globals.shared.dataUse! += (Globals.shared.dlFileSize! / 8000)
    session.invalidateAndCancel()

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessFinished"), object: nil, userInfo: nil)
}
</code>```

As you can probably tell by the delegate functions, this all exists in a separate class from the view controller, along with some other small networking functions, like getting IP and SSID. The delegates post notifications that are observed by the view controller.

My ViewController has an NSTimer that calls back to this URLSession every 5 seconds to re-test the speed (but only runs it if the previous one completed). Here's the code for that:

reloadTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(rescanNetwork), userInfo: nil, repeats: true)

Which calls this function:

```<code>func backgroundRescan() {
    if Globals.shared.DownComplete {
        Networking().testSpeed()
    }
}
</code>```

Which runs the URL Session again, checking, of course, to ensure that the previous had completed.

For some reason, I'm getting a massive buildup of memory use in testing, until the app reaches 2GB of memory use and gets terminated with the console output Message from debugger: Terminated due to memory issue. This all happens within two minutes of running the app.

I even added session.invalidateAndCancel() to the completion delegate in a desperate attempt to clear that memory. But it didn't work. Am I missing something?

答:
As Rob has said, put URLSessionConfiguration.default as a variable in your class and use that instead.
I had the same problem and finally I solved it by using a singelton class which contains all my communication methods and set URLSessionConfiguration.default to a member variable. All my memory leaks were solved.</p>

Body:
I have an application that (in part) displays the current download speed of a Wi-Fi connection to a user. It does so by opening a URLSession and downloading a moderate-sized (~10MB) file and measuring the time it took.

Here's that URLSession function:

func testSpeed() {

    Globals.shared.dlStartTime = Date()
    Globals.shared.DownComplete = false

    if Globals.shared.currentSSID == "" {
        Globals.shared.bandwidth = 0
        Globals.shared.DownComplete = true
    } else {

        let url = URL(string: [HIDDEN])
        let session = URLSession(configuration: URLSessionConfiguration.default, delegate: self, delegateQueue: nil)
        let task = session.downloadTask(with: url!)

        task.resume()
    }
}

public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64) {

    Globals.shared.dlFileSize = (Double(totalBytesExpectedToWrite) * 8) / 1000
    let progress = (Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)) * 100.0

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessUpdating"), object: nil, userInfo: ["progress" : progress])
}

public func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL) {
    let elapsed = Double( Date().timeIntervalSince(Globals.shared.dlStartTime))
    Globals.shared.bandwidth = Int(Globals.shared.dlFileSize / elapsed)
    Globals.shared.DownComplete = true
    Globals.shared.dataUse! += (Globals.shared.dlFileSize! / 8000)
    session.invalidateAndCancel()

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "ProcessFinished"), object: nil, userInfo: nil)
}

As you can probably tell by the delegate functions, this all exists in a separate class from the view controller, along with some other small networking functions, like getting IP and SSID. The delegates post notifications that are observed by the view controller.

My ViewController has an NSTimer that calls back to this URLSession every 5 seconds to re-test the speed (but only runs it if the previous one completed). Here's the code for that:

reloadTimer = Timer.scheduledTimer(timeInterval: 5.0, target: self, selector: #selector(rescanNetwork), userInfo: nil, repeats: true)

Which calls this function:

func backgroundRescan() {
    if Globals.shared.DownComplete {
        Networking().testSpeed()
    }
}

Which runs the URL Session again, checking, of course, to ensure that the previous had completed.

For some reason, I'm getting a massive buildup of memory use in testing, until the app reaches 2GB of memory use and gets terminated with the console output Message from debugger: Terminated due to memory issue. This all happens within two minutes of running the app.

I even added session.invalidateAndCancel() to the completion delegate in a desperate attempt to clear that memory. But it didn't work. Am I missing something?


问:
How do I properly set up Volley to download images from a URL
I know Volley is supposed to make downloading and caching images mindlessly simple but yet I have been struggling for hours to properly implement it. I've looked around the net as well as the many articles on stackoverflow regarding volley but none of the examples I've found seem to work for me.

I only want to use volley to download and cache images from a given url, not to do any HTTP JSON REST handling. Just to take given urls, download the bitmaps and set them to the imageview then add them to the cache.

This has been my latest attempt so far.
How do I load and cache images with volley correctly?

```<code>if (data.getImageUrl() != null) {
        try {

            holder.thumbnail.setTag(data.getImageUrl());

        Cache cache = ImgController.getInstance().getRequestQueue().getCache();
        Cache.Entry entry = cache.get(data.getImageUrl());

            if (entry != null) {
                try {
                    String cImg = new String(entry.data, "UTF-8");
                    LruBitmapCache bitmapCache = new LruBitmapCache();
                    holder.thumbnail.setImageBitmap(bitmapCache.getBitmap(cImg));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            } else {

                ImageLoader imageLoader = ImgController.getInstance().getImageLoader();

                imageLoader.get(data.getImageUrl(), new ImageListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {

                        holder.thumbnail.setImageResource(R.drawable.filler_icon);

                    }

                    @Override
                    public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
                        if (response.getBitmap() != null) {
                            // load image into imageview
                            holder.thumbnail.setImageBitmap(response.getBitmap());

                        }
                    }
                });
            }

            return convertView;
        } catch (Exception e) {
            e.printStackTrace();
            Log.v(DEBUG_TAG, "no image: ", e);
            holder.thumbnail.setImageResource(R.drawable.filler_icon);

        }
    }else {
        return null;
    }

    return convertView;
}
</code>```

When I run this I get a NullPointerException pointing to this line

```<code>Cache cache = ImgController.getInstance().getRequestQueue().getCache();
</code>```

I've setup the following singleton class to handle requests

```<code>public class ImgController extends Application {

public static final String TAG = ImgController.class.getSimpleName();
private RequestQueue requestQueue;
private ImageLoader imageLoader;

private static ImgController instance;

@Override
public void onCreate() {
    super.onCreate();
    instance = this;

}
public static synchronized ImgController getInstance(){
    return instance;
}
public RequestQueue getRequestQueue(){
    if(requestQueue == null){
        requestQueue = Volley.newRequestQueue(getApplicationContext());
    }
    return this.requestQueue;
}
public ImageLoader getImageLoader(){
    getRequestQueue();
    if(imageLoader ==  null){
        imageLoader = new ImageLoader(this.requestQueue, new LruBitmapCache());
        }

    return this.imageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
    // set the default tag if tag is empty
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (requestQueue != null) {
        requestQueue.cancelAll(tag);
    }
}
</code>```

}

as well as the following LruBitmapCache class

```<code>public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache {

public static int getDefaultLruCacheSize(){
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;

    return cacheSize;
}

public LruBitmapCache() {
    this(getDefaultLruCacheSize());
}
public LruBitmapCache(int maxSize) {
    super(maxSize);
}

@Override
public Bitmap getBitmap(String url) {
    return get(url);
}

@Override
public void putBitmap(String url, Bitmap bitmap) {
    put (url, bitmap);
}
</code>```

}

答:
I have a more simple solution for displaying the image from url and storing it in cache. Without adding additional classes, only MainActivity.
probably it will help somebody...

Here is my XML that displays only ImageView

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.example.natalie.volley.MainActivity">

    <ImageView
        android:id="@+id/ivImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="50dp"/>

</android.support.constraint.ConstraintLayout>
</code>```

And here is my MainAvtivity.java:

```<code>  import android.graphics.Bitmap;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.ImageView;

    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.ImageRequest;
    import com.android.volley.toolbox.Volley;

    public class MainActivity extends AppCompatActivity {

        private String url = "http://kingofwallpapers.com/picture/picture-010.jpg";
        ImageView ivImageView;
        RequestQueue mRequestQueue;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ivImageView = (ImageView)findViewById(R.id.ivImageView);
            mRequestQueue = Volley.newRequestQueue(this.getApplicationContext());
            ImageRequest imageRequest = new ImageRequest(url, new BitmapListener(), 0, 0, null, null, new MyErrorListener());

            mRequestQueue.add(imageRequest);
        }

        private class BitmapListener implements Response.Listener<Bitmap> {
            @Override
            public void onResponse(Bitmap response) {
// response = your url's bitmap
                ivImageView.setImageBitmap(response);

            }
        }

        private class MyErrorListener implements Response.ErrorListener {
            @Override
            public void onErrorResponse(VolleyError error) {
//store a default image if connection failed
                ivImageView.setImageResource(R.drawable.error_icon);
            }
        }
    }
</code>```

Don't forget to add <uses-permission android:name="android.permission.INTERNET" /> in Manifest.xml
and compile 'com.android.volley:volley:1.0.0' in build.gradle dependencies

Body:
I know Volley is supposed to make downloading and caching images mindlessly simple but yet I have been struggling for hours to properly implement it. I've looked around the net as well as the many articles on stackoverflow regarding volley but none of the examples I've found seem to work for me.

I only want to use volley to download and cache images from a given url, not to do any HTTP JSON REST handling. Just to take given urls, download the bitmaps and set them to the imageview then add them to the cache.

This has been my latest attempt so far.
How do I load and cache images with volley correctly?

if (data.getImageUrl() != null) {
        try {

            holder.thumbnail.setTag(data.getImageUrl());

        Cache cache = ImgController.getInstance().getRequestQueue().getCache();
        Cache.Entry entry = cache.get(data.getImageUrl());

            if (entry != null) {
                try {
                    String cImg = new String(entry.data, "UTF-8");
                    LruBitmapCache bitmapCache = new LruBitmapCache();
                    holder.thumbnail.setImageBitmap(bitmapCache.getBitmap(cImg));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }

            } else {

                ImageLoader imageLoader = ImgController.getInstance().getImageLoader();

                imageLoader.get(data.getImageUrl(), new ImageListener() {

                    @Override
                    public void onErrorResponse(VolleyError error) {

                        holder.thumbnail.setImageResource(R.drawable.filler_icon);

                    }

                    @Override
                    public void onResponse(ImageLoader.ImageContainer response, boolean arg1) {
                        if (response.getBitmap() != null) {
                            // load image into imageview
                            holder.thumbnail.setImageBitmap(response.getBitmap());

                        }
                    }
                });
            }

            return convertView;
        } catch (Exception e) {
            e.printStackTrace();
            Log.v(DEBUG_TAG, "no image: ", e);
            holder.thumbnail.setImageResource(R.drawable.filler_icon);

        }
    }else {
        return null;
    }

    return convertView;
}

When I run this I get a NullPointerException pointing to this line

Cache cache = ImgController.getInstance().getRequestQueue().getCache();

I've setup the following singleton class to handle requests

public class ImgController extends Application {

public static final String TAG = ImgController.class.getSimpleName();
private RequestQueue requestQueue;
private ImageLoader imageLoader;

private static ImgController instance;

@Override
public void onCreate() {
    super.onCreate();
    instance = this;

}
public static synchronized ImgController getInstance(){
    return instance;
}
public RequestQueue getRequestQueue(){
    if(requestQueue == null){
        requestQueue = Volley.newRequestQueue(getApplicationContext());
    }
    return this.requestQueue;
}
public ImageLoader getImageLoader(){
    getRequestQueue();
    if(imageLoader ==  null){
        imageLoader = new ImageLoader(this.requestQueue, new LruBitmapCache());
        }

    return this.imageLoader;
}
public <T> void addToRequestQueue(Request<T> req, String tag) {
    // set the default tag if tag is empty
    req.setTag(TextUtils.isEmpty(tag) ? TAG : tag);
    getRequestQueue().add(req);
}

public <T> void addToRequestQueue(Request<T> req) {
    req.setTag(TAG);
    getRequestQueue().add(req);
}

public void cancelPendingRequests(Object tag) {
    if (requestQueue != null) {
        requestQueue.cancelAll(tag);
    }
}

}

as well as the following LruBitmapCache class

public class LruBitmapCache extends LruCache<String, Bitmap> implements ImageLoader.ImageCache {

public static int getDefaultLruCacheSize(){
    final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
    final int cacheSize = maxMemory / 8;

    return cacheSize;
}

public LruBitmapCache() {
    this(getDefaultLruCacheSize());
}
public LruBitmapCache(int maxSize) {
    super(maxSize);
}

@Override
public Bitmap getBitmap(String url) {
    return get(url);
}

@Override
public void putBitmap(String url, Bitmap bitmap) {
    put (url, bitmap);
}

}

Body:
I have a more simple solution for displaying the image from url and storing it in cache. Without adding additional classes, only MainActivity.
probably it will help somebody...

Here is my XML that displays only ImageView

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.example.natalie.volley.MainActivity">

    <ImageView
        android:id="@+id/ivImageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="50dp"/>

</android.support.constraint.ConstraintLayout>

And here is my MainAvtivity.java:

  import android.graphics.Bitmap;
    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;
    import android.widget.ImageView;

    import com.android.volley.RequestQueue;
    import com.android.volley.Response;
    import com.android.volley.VolleyError;
    import com.android.volley.toolbox.ImageRequest;
    import com.android.volley.toolbox.Volley;

    public class MainActivity extends AppCompatActivity {

        private String url = "http://kingofwallpapers.com/picture/picture-010.jpg";
        ImageView ivImageView;
        RequestQueue mRequestQueue;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            ivImageView = (ImageView)findViewById(R.id.ivImageView);
            mRequestQueue = Volley.newRequestQueue(this.getApplicationContext());
            ImageRequest imageRequest = new ImageRequest(url, new BitmapListener(), 0, 0, null, null, new MyErrorListener());

            mRequestQueue.add(imageRequest);
        }

        private class BitmapListener implements Response.Listener<Bitmap> {
            @Override
            public void onResponse(Bitmap response) {
// response = your url's bitmap
                ivImageView.setImageBitmap(response);

            }
        }

        private class MyErrorListener implements Response.ErrorListener {
            @Override
            public void onErrorResponse(VolleyError error) {
//store a default image if connection failed
                ivImageView.setImageResource(R.drawable.error_icon);
            }
        }
    }

Don't forget to add <uses-permission android:name="android.permission.INTERNET" /> in Manifest.xml
and compile 'com.android.volley:volley:1.0.0' in build.gradle dependencies


问:
Improve performance getting or setting values in cells through VBA
I've managed to connect to a web service and retrieve data to finally insert it into a sheet.

Looks like when I perform this final operation, the sheet gets the focus and the screen blinks constantly until this ends, which is a little awkward for the user and it depletes performance. We are talking that inserting about 1000 rows with 4 different parsed columns lasts for about 5 seconds.

Is there a way to do this "on the background"? I noted that basically "every action" I performed (like reading values or setting them) requests the focus on that concrete sheet, so I basically return the focus to the sheet who called the procedure once everything ended.

My code is the following:

```<code>For i = 3 To UBound(Data) - 1
    If (IsNullOrWhiteSpace(Data(i))) Then
        Exit Sub
    End If
    splitted = Split(Data(i), ";")
    For j = 0 To UBound(splitted)

        Cells(i - 1, j + 1).Value = splitted(j)
    Next
Next
</code>```

Many thanks, I'm new into this VBA world.

答:
for starter, place:

```<code>Application.Calculation = xlCalculationManual
</code>```

at the beginning of your Sub and:

```<code>Application.Calculation =xlCalculationAutomatic
</code>```

right before End Sub

then let's see further three steps to speed things up:

a first step could be replacing:

```<code>For j = 0 To UBound(splitted)

    Cells(i - 1, j + 1).Value = splitted(j)
Next
</code>```

with:

```<code>Cells(i - 1, 1).Resize(, UBound(splitted) + 1).Value = Application.Transpose(Application.Transpose(splitted))
</code>```

so that you write a whole row in one shot

a second step could be working with arrays and write the content of a 2D array in one shot:

```<code>Dim Data As Variant
Dim nRows As Long, nCols As Long, i As Long, j As Long

' >>>> here your code code to fill 'Data' variant array <<<<

ReDim notNullData(1 To UBound(Data) - 3) As Variant '<--| size 'notNullData' 1D Variant array to the maximum possible rows

For i = 3 To UBound(Data) - 1
    If IsNullOrWhiteSpace(Data(i)) Then Exit For '<--| exit loop at the first null or empty 'Data' value
    nRows = nRows + 1 '<--| update valid rows counter
    notNullData(nRows) = Split(Data(i), ";") '<--| fill 'notNullData' array with an array from current 'Data' row content
    If UBound(notNullData(nRows)) > nCols Then nCols = UBound(notNullData(nRows)) '<--| update maximum n° of columns to be written
Next

ReDim dataToWrite(1 To nRows, 1 To nCols + 1) As Variant '<--| size 'dataToWrite' 2D Variant array to 'Data' array valid rows number and calculated maximum nr of columns
'fill 2D 'dataToWrite' array processing 'notNullData' 1D array
For i = 1 To nRows
    For j = 0 To UBound(notNullData(i))
        dataToWrite(i, j + 1) = notNullData(i)(j)
    Next
Next

'write 2D 'dataToWrite' array in one shoit
Cells(1, 1).Resize(nRows, nCols + 1).Value = dataToWrite
</code>```

a third step would involve IsNullOrWhiteSpace() function

Body:
I've managed to connect to a web service and retrieve data to finally insert it into a sheet.

Looks like when I perform this final operation, the sheet gets the focus and the screen blinks constantly until this ends, which is a little awkward for the user and it depletes performance. We are talking that inserting about 1000 rows with 4 different parsed columns lasts for about 5 seconds.

Is there a way to do this "on the background"? I noted that basically "every action" I performed (like reading values or setting them) requests the focus on that concrete sheet, so I basically return the focus to the sheet who called the procedure once everything ended.

My code is the following:

For i = 3 To UBound(Data) - 1
    If (IsNullOrWhiteSpace(Data(i))) Then
        Exit Sub
    End If
    splitted = Split(Data(i), ";")
    For j = 0 To UBound(splitted)

        Cells(i - 1, j + 1).Value = splitted(j)
    Next
Next

Many thanks, I'm new into this VBA world.

Body:
for starter, place:

Application.Calculation = xlCalculationManual

at the beginning of your Sub and:

Application.Calculation =xlCalculationAutomatic

right before End Sub

then let's see further three steps to speed things up:

a first step could be replacing:

For j = 0 To UBound(splitted)

    Cells(i - 1, j + 1).Value = splitted(j)
Next

with:

Cells(i - 1, 1).Resize(, UBound(splitted) + 1).Value = Application.Transpose(Application.Transpose(splitted))

so that you write a whole row in one shot

a second step could be working with arrays and write the content of a 2D array in one shot:

Dim Data As Variant
Dim nRows As Long, nCols As Long, i As Long, j As Long

' >>>> here your code code to fill 'Data' variant array <<<<

ReDim notNullData(1 To UBound(Data) - 3) As Variant '<--| size 'notNullData' 1D Variant array to the maximum possible rows

For i = 3 To UBound(Data) - 1
    If IsNullOrWhiteSpace(Data(i)) Then Exit For '<--| exit loop at the first null or empty 'Data' value
    nRows = nRows + 1 '<--| update valid rows counter
    notNullData(nRows) = Split(Data(i), ";") '<--| fill 'notNullData' array with an array from current 'Data' row content
    If UBound(notNullData(nRows)) > nCols Then nCols = UBound(notNullData(nRows)) '<--| update maximum n° of columns to be written
Next

ReDim dataToWrite(1 To nRows, 1 To nCols + 1) As Variant '<--| size 'dataToWrite' 2D Variant array to 'Data' array valid rows number and calculated maximum nr of columns
'fill 2D 'dataToWrite' array processing 'notNullData' 1D array
For i = 1 To nRows
    For j = 0 To UBound(notNullData(i))
        dataToWrite(i, j + 1) = notNullData(i)(j)
    Next
Next

'write 2D 'dataToWrite' array in one shoit
Cells(1, 1).Resize(nRows, nCols + 1).Value = dataToWrite

a third step would involve IsNullOrWhiteSpace() function


问:
Grails. JSON. his methods?
I was up all night looking for information on how to use JSON in Grails. And I found the information that in JSON closure, we can use only one method - array -  no other. is it true?

and next small question:

i find here: http://www.jiramot.info/mini-guide-to-rendering-json-with-grails example:

```<code>render(contentType:‘text/json’){
        collection{
                pair(name:‘value’)
                pair(name:‘value1′)
        }
}
</code>```

Will be rendered as:

```<code>{collection:[{"name":"value"},{"name":"value1"}]
</code>```

but when i try do it, i have this result:

```<code>{"collection":{"pair":{"name":"value1"}}}
</code>```

What conclusion can we do?
i do some wrong or wrong example on site?

答:
JSON rendering in Grails is much easier...

```<code>def foobar = [ fooArray: [ 1, 2, 3 ], bar: [ b: "bbb", a: "aaa", r: "rrr" ] ]
render foobar as JSON
</code>```

results in

```<code>{"fooArray":[1,2,3],"bar":{"b":"bbb","a":"aaa","r":"rrr"}}
</code>```

Just create an appropriate Groovy structure and render it as JSON.

Title: Grails. JSON. his methods?

Body:
I was up all night looking for information on how to use JSON in Grails. And I found the information that in JSON closure, we can use only one method - array -  no other. is it true?

and next small question:

i find here: http://www.jiramot.info/mini-guide-to-rendering-json-with-grails example:

render(contentType:‘text/json’){
        collection{
                pair(name:‘value’)
                pair(name:‘value1′)
        }
}

Will be rendered as:

{collection:[{"name":"value"},{"name":"value1"}]

but when i try do it, i have this result:

{"collection":{"pair":{"name":"value1"}}}

What conclusion can we do?
i do some wrong or wrong example on site?

Body:
JSON rendering in Grails is much easier...

def foobar = [ fooArray: [ 1, 2, 3 ], bar: [ b: "bbb", a: "aaa", r: "rrr" ] ]
render foobar as JSON

results in

{"fooArray":[1,2,3],"bar":{"b":"bbb","a":"aaa","r":"rrr"}}

Just create an appropriate Groovy structure and render it as JSON.


问:
Updating/deleting rows from tables (codeigniter)
Im trying (without success) to update/delete rows from a table.

Note: my database name is "desafio" and table "materias" contains: (id, carrera_id (is the foreign key to the column "id" of the table "carreras") nombre, descripcion, carga_horaria)

I got this 2 errors when clicking buttons "edit" & "delete" respectively:

I cannot upload the image

I cannot upload the image2

Here is the index file:

```<code><tbody>
<?php
    foreach($records as $record) {

        echo "<tr>
                  <td>".$record->id."</td>
                  <td>".$record->carrera."</td>
                  <td>".$record->nombre."</td>
                  <td>".$record->descripcion."</td>
                  <td>".$record->carga_horaria."</td>
                  <td align='center'>
                    <a href='".site_url('Home/edit')."/$record->id'>
                     <button type='button' class='btn btn-primary'>EDITAR</button></a> |
                    <a href='".site_url('Home/delete')."/$record->id'>
                     <button type='button' class='btn btn-danger'>BORRAR</button></a>

              </tr>";
    }
?>
</code>```

Here is the controller file (with functions edit,saveupdate and delete)

```<code>        public function edit($id){

        $data['record']=$this->Crudmodel->get_row_id($id);
        $this->load->view('editar', $data);

    }

    public function saveupdate(){

            $txtcarr=$this->input->post("txtcarr");
            $txtmat=$this->input->post("txtmat");
            $txtdesc=$this->input->post("txtdesc");
            $txtcarga=$this->input->post("txtcarga");

        $this->Crudmodel->save($txtcarr,$txtmat,$txtdesc,$txtcarga);

        redirect('Home/index');

    }

    public function delete($id){

        $this->db->where('id',$id);
        $this->db->delete('desafio');

        redirect('Home/index');

    }
</code>```

The crudmodel (with the function get_row_id)

```<code>        public function get_row_id($id){

      $this->db->where('id',$id);
      $query=$this->db->get('id');
      return $query->row();

    }
</code>```

And the file "editar" which allows me to correct the information written:

```<code>    </head>
</code>```

```<code><div class="container">
<div class="row">
<div class="col-md-12">

    <h2 align="center">UPDATE SUBJECTS</h2>
    <form method="post" action='<?php echo site_url('Home/saveupdate'); ?>'>
    <tr>

        <td>
            <select name="txtcarr">
                <?php foreach($carreras as $item):?>
                <option value="<?php echo $item->id;?>"><?php echo $item->nombre;?></option>
                 <?php endforeach;?>
            </select>
        </td>
    </tr>
    <tr>

        <td>Materia : </td>
        <td><input type="text" name="txtmat" value="<?php echo $record->nombre ?>"/></td>

    </tr>
    <tr>

        <td>Descripcion : </td>
        <td><textarea name="txtdesc" value="<?php echo $record->descripcion ?>"></textarea></td>

    </tr>
    <tr>

        <td>Carga horaria : </td>
        <td><input type="text" name="txtcarga"/></td>

    </tr>
    <tr>

        <td></td>
        <td><input type="submit" value="save"/></td>

    </tr>

        <table class="table table-hover" align="center" border="0" cellspacing="0" cellpadding="0" width="300">

        </table>

    </div>
    </div>
    </div>
</code>```

Do not understand what is going on :S

答:
In your delete function shouldn't you use the table name?

```<code>$this->db->delete('materias');
</code>```

Body:
Im trying (without success) to update/delete rows from a table.

Note: my database name is "desafio" and table "materias" contains: (id, carrera_id (is the foreign key to the column "id" of the table "carreras") nombre, descripcion, carga_horaria)

I got this 2 errors when clicking buttons "edit" & "delete" respectively:

I cannot upload the image

I cannot upload the image2

Here is the index file:

<?php
    foreach($records as $record) {

        echo "

                  ".$record->id."
                  ".$record->carrera."
                  ".$record->nombre."
                  ".$record->descripcion."
                  ".$record->carga_horaria."

                    id'>
                     <button type='button' class='btn btn-primary'>EDITAR</button> |
                    id'>
                     <button type='button' class='btn btn-danger'>BORRAR</button>

";
    }
?>

Here is the controller file (with functions edit,saveupdate and delete)

        public function edit($id){

        $data['record']=$this->Crudmodel->get_row_id($id);
        $this->load->view('editar', $data);

    }

    public function saveupdate(){

            $txtcarr=$this->input->post("txtcarr");
            $txtmat=$this->input->post("txtmat");
            $txtdesc=$this->input->post("txtdesc");
            $txtcarga=$this->input->post("txtcarga");

        $this->Crudmodel->save($txtcarr,$txtmat,$txtdesc,$txtcarga);

        redirect('Home/index');

    }

    public function delete($id){

        $this->db->where('id',$id);
        $this->db->delete('desafio');

        redirect('Home/index');

    }

The crudmodel (with the function get_row_id)

        public function get_row_id($id){

      $this->db->where('id',$id);
      $query=$this->db->get('id');
      return $query->row();

    }

And the file "editar" which allows me to correct the information written:

UPDATE SUBJECTS

    <form method="post" action='<?php echo site_url('Home/saveupdate'); ?>'>

            <select name="txtcarr">
                <?php foreach($carreras as $item):?>
                <option value="<?php echo $item->id;?>"><?php echo $item->nombre;?></option>
                 <?php endforeach;?>
            </select>

        Materia :
        <input type="text" name="txtmat" value="<?php echo $record->nombre ?>"/>

        Descripcion :
        <textarea name="txtdesc" value="<?php echo $record->descripcion ?>"></textarea>

        Carga horaria :
        <input type="text" name="txtcarga"/>

        <input type="submit" value="save"/>

Do not understand what is going on :S

Body:
In your delete function shouldn't you use the table name?

$this->db->delete('materias');


问:
Embedding an Angular Directive in

I'm trying to get an angular directive to repeat inside a
. Without the directive, the code is

```<code><tr *ngFor='let cluster of clusters'>
    <td style='display: flex; flex-direction: column; width: 40%; min-width: 300px;'>
        <span>{{ cluster.Name }}</span>
        <span>{{ cluster.StatusMessage }}</span>
    </td>
    <td style='width: 100%;'>
        ...
    </td>
</tr>
</code>```

And looks like

When I refactor the directive, I lose the
 formatting. The refactored code is

```<code><tr *ngFor='let cluster of clusters'>
    <cluster-row [name]='cluster.Name' [statusMessage]='cluster.StatusMessage'></cluster-row>
</tr>
</code>```

The cluster-row component code is:

```<code><td style='display: flex; flex-direction: column; width: 40%; min-width: 300px;'>
    <span>{{ name }}</span>
    <span>{{ statusMessage }}</span>
</td>
<td style='width: 100%;'>
    ...
</td>
</code>```

It works, but the
 formatting goes away.

The developer tools show a
 with a <cluster-row> nested in it, and two s nested in that, as I would expect.

答:
 can't contain a <cluster-row> element.

You can use an attribute selector instead like

```<code><tr *ngFor='let cluster of clusters'>
    <td cluster-row [name]='cluster.Name' [statusMessage]='cluster.StatusMessage'></cluster-row>
</tr>
</code>```

with

```<code>@Component({
//@Directive({
  selector: '[cluster-row]'
</code>```

The component or directive then is the , therefore you can't repeat it inside the components template

```<code>style='display: flex; flex-direction: column; width: 40%; min-width: 300px;'
</code>```

can just be added to

```<code>@Component({
  selector: '[cluster-row]',
  styles: [...],
</code>```

Title: Embedding an Angular Directive in <tr>

Body:
I'm trying to get an angular directive to repeat inside a
. Without the directive, the code is

        {{ cluster.Name }}
        {{ cluster.StatusMessage }}

        ...

And looks like

When I refactor the directive, I lose the
 formatting. The refactored code is

    <cluster-row [name]='cluster.Name' [statusMessage]='cluster.StatusMessage'></cluster-row>

The cluster-row component code is:

    {{ name }}
    {{ statusMessage }}

    ...

It works, but the
 formatting goes away.

The developer tools show a
 with a <cluster-row> nested in it, and two s nested in that, as I would expect.

Body:
<tr> can't contain a <cluster-row> element.

You can use an attribute selector instead like

<tr *ngFor='let cluster of clusters'>
    <td cluster-row [name]='cluster.Name' [statusMessage]='cluster.StatusMessage'></cluster-row>
</tr>

with

@Component({
//@Directive({
  selector: '[cluster-row]'

The component or directive then is the <td>, therefore you can't repeat it inside the components template

style='display: flex; flex-direction: column; width: 40%; min-width: 300px;'

can just be added to

@Component({
  selector: '[cluster-row]',
  styles: [...],


问:
pinging multi sub nets and saving in external file using bash / linux
Trying to create a script to ping multiple sub nets,
but script do not seems to be working correctly,
it seems I'm missing somthing
any help would be appreciated

function to ping and filter:

```<code>ping_hosts() {
  ping -c 1 $1 > /dev/null
  if [ $? -eq 0 ]; then
  echo -e "server $1 is online"
  echo $1 >> live_ser_list
 fi
}
</code>```

lop to submit IP's to filter:

```<code>for i in '192.168.0.' '10.0.0.' '10.0.1.' '192.168.1.';do
echo "starting $i"0" network"
   for j in $i{1..254};
   do
    ping_hosts $j & disown
   done
done
</code>```

edited
did try $1 and $j
The list file is not getting created...

答:
There were some errors in your script, here's an improved version. Note the quotes around all variables etc.</p>

```<code>ping_hosts() {
    local addr="$1"
    if ping -c 1 "${addr}" &> /dev/null; then
        echo "server ${addr} is online"
        echo "${addr}" >> live_ser_list
    fi
}

subnets=("192.168.0." "10.0.0." "10.0.1." "192.168.1.")

for subnet in "${subnets[@]}"; do
    echo "starting ${subnet}0 network"
    for octet in {1..254}; do
        ping_hosts "${subnet}${octet}" & disown
   done
done
</code>```

Body:
Trying to create a script to ping multiple sub nets,
but script do not seems to be working correctly,
it seems I'm missing somthing
any help would be appreciated

function to ping and filter:

ping_hosts() {
  ping -c 1 $1 > /dev/null
  if [ $? -eq 0 ]; then
  echo -e "server $1 is online"
  echo $1 >> live_ser_list
 fi
}

lop to submit IP's to filter:

for i in '192.168.0.' '10.0.0.' '10.0.1.' '192.168.1.';do
echo "starting $i"0" network"
   for j in $i{1..254};
   do
    ping_hosts $j & disown
   done
done

edited
did try $1 and $j
The list file is not getting created...

Body:
There were some errors in your script, here's an improved version. Note the quotes around all variables etc.

ping_hosts() {
    local addr="$1"
    if ping -c 1 "${addr}" &> /dev/null; then
        echo "server ${addr} is online"
        echo "${addr}" >> live_ser_list
    fi
}

subnets=("192.168.0." "10.0.0." "10.0.1." "192.168.1.")

for subnet in "${subnets[@]}"; do
    echo "starting ${subnet}0 network"
    for octet in {1..254}; do
        ping_hosts "${subnet}${octet}" & disown
   done
done


问:
How to replace string literals back/front slashes in Julia?
In Python, I can do string replacements of slashes as such:

```<code>>>> s = 'ab\c'
>>> s.replace('\\', '\\\\')
'ab\\\\c'
>>> print s.replace('\\', '\\\\')
ab\\c
</code>```

In Julia, when I could do this:

```<code>julia> s = "ab\\c"
"ab\\c"

julia> replace(s, "\\\\", "\\\\\\\\")
"ab\\c"
</code>```

I've tried this but it throws some syntax error:

```<code>julia> replace(s, r"\", r"\\")
ERROR: syntax: "\" is not a unary operator
</code>```

答:
Julia REPL outputs strings in escaped form. It might be best to wrap things with a println as in println(replace(s, "\\", "\\\\")). In this case you get:

```<code>julia> s = "ab\\c"
"ab\\c"

julia> println(s)
ab\c

julia> println(replace(s, "\\", "\\\\"))
ab\\c
</code>```

Regarding the use of regular expressions, the first r"\" is a partial regular expression and the parser continue and generates an error on the following \ after a closing ", and the second regexp is unnecessary as it is the string to be inserted.

UPDATE: More details about Julia vs. Python escaping in the other answer.

Hope this helps!

Body:
In Python, I can do string replacements of slashes as such:

>>> s = 'ab\c'
>>> s.replace('\\', '\\\\')
'ab\\\\c'
>>> print s.replace('\\', '\\\\')
ab\\c

In Julia, when I could do this:

julia> s = "ab\\c"
"ab\\c"

julia> replace(s, "\\\\", "\\\\\\\\")
"ab\\c"

I've tried this but it throws some syntax error:

julia> replace(s, r"\", r"\\")
ERROR: syntax: "\" is not a unary operator

Body:
Julia REPL outputs strings in escaped form. It might be best to wrap things with a println as in println(replace(s, "\\", "\\\\")). In this case you get:

julia> s = "ab\\c"
"ab\\c"

julia> println(s)
ab\c

julia> println(replace(s, "\\", "\\\\"))
ab\\c

Regarding the use of regular expressions, the first r"\" is a partial regular expression and the parser continue and generates an error on the following \ after a closing ", and the second regexp is unnecessary as it is the string to be inserted.

UPDATE: More details about Julia vs. Python escaping in the other answer.

Hope this helps!


问:
Xcode not detecting my device
I upgraded my iPad device OS version recently to 5.1.1 (9B206). From that my Xcode is not detecting my device. Am just getting iOS Device and simulator options in my Xcode. But am getting my device  in older version of Xcode and iTunes. For this i updated my MAC OS version to 10.7.4 and Xcode version to 4.3.3. But still am facing the same problem. Now how to make my Xcode to detect my device?</p>

答:
Most recently, Xcode 8.3 and iOS 10.3 seems to have more security around Xcode accessing the iPad/iPhone. My sequence:

Rebooted the machine,

Attached the iPad,

Gone through a "trust this computer" security cycle on both iMac and iPad

Xcode can now see the device

Title: Xcode not detecting my device