问:
Intel Edison + Ubilinux + USB to UART = USB Device not created
Dear community members,

We are working in the development of a robot autonomous control system running inside an Intel Edison, which -in turn- runs in a PixHawk automatic pilot module . This system uses ROS (Robot Operating System) and therefore we had to install Ubilinux. Our system requires being connected with a 360-degree laser (RPLIDAR-360) that sends data through a serial channel, so we are trying to get laser's data through USB-to-UART adapter (Silicon lab's CP2102) (the PixHawk only has a USB available for data transfer).

In summary, the laser is connected to the USB2UART adapter, and the adapter is connected to Edison's serial port.

However, we are stuck with some kind of driver issue. When tracing 'dmesg' the device is detected (idVendor=10c4, idProduct=ea60):

```<code>[  917.812195] usb usb2: Product: xHCI Host Controller
[  917.812214] usb usb2: Manufacturer: Linux 3.10.17-yocto-standard-r2 dwc-xhci
[  917.812232] usb usb2: SerialNumber: dwc3-host.2
[  917.812858] xHCI xhci_add_endpoint called for root hub
[  917.812878] xHCI xhci_check_bandwidth called for root hub
[  917.813141] hub 2-0:1.0: USB hub found
[  917.813185] hub 2-0:1.0: 1 port detected
[  918.128982] usb 1-1: new full-speed USB device number 2 using dwc3-host
[  918.151786] usb 1-1: New USB device found, idVendor=10c4, idProduct=ea60
[  918.151818] usb 1-1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[  918.151839] usb 1-1: Product: CP2102 USB to UART Bridge Controller
[  918.151857] usb 1-1: Manufacturer: Silicon Labs
[  918.151875] usb 1-1: SerialNumber: 0001
</code>```

With the following details:

```<code>T:  Bus=01 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=12   MxCh= 0
D:  Ver= 1.10 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=10c4 ProdID=ea60 Rev= 1.00
S:  Manufacturer=Silicon Labs
S:  Product=CP2102 USB to UART Bridge Controller
S:  SerialNumber=0001
C:* #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=100mA
I:* If#= 0 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=00 Prot=00 Driver=(none)
E:  Ad=81(I) Atr=02(Bulk) MxPS=  64 Ivl=0ms
E:  Ad=01(O) Atr=02(Bulk) MxPS=  64 Ivl=0ms
</code>```

But no /dev/ttyUSBX device is created, and there are no error messages about missing Drivers or configuration failures.

We are using Ubilinux 3, which reports the following with the 'uname' command:

```<code> **  3.10.17-yocto-standard-r2
</code>```

And the following is the listing of the installed drivers:

```<code>usb
/lib/modules/3.10.17-yocto-standard-r2/kernel/drivers/media/usb:
/lib/modules/3.10.17-yocto-standard-r2/kernel/drivers/media/usb/gspca:
/lib/modules/3.10.17-yocto-standard-r2/kernel/drivers/media/usb/uvc:
/lib/modules/3.10.17-yocto-standard-r2/kernel/drivers/usb:
/lib/modules/3.10.17-yocto-standard-r2/kernel/drivers/usb/gadget:
usb_f_acm.ko
/lib/modules/3.10.17-yocto-standard-r2/kernel/drivers/usb/serial:
usb_wwan.ko
</code>```

Does anyone has had a similar configuration and managed to make work a CP2102 adapter?

As a last resort, we are trying to compile and install the driver by ourselves, using this reference: [url=https://askubuntu.com/questions/941594/installing-cp210x-driver]Installing CP210x Driver?Installing CP210x Driver? - Ask Ubuntu[/url]

The 'make' process crashes due to a lack of headers. We were unable to download the headers through APT, but at the end, we managed to compile the '.ko' module by downloading the headers manually from a Website.

However, after doing:

```<code>insmod cp210x.ko
</code>```

We got:

```<code>Insmod: ERROR: could not insert module cp210x.ko: Invalid module format
</code>```

So, at this point we have several questions... any advice about any of them would be really appreciated:

Does anybody know how to install the Kernel headers in Ubilinux - 3.10.17?

What is the official procedure to upgrade the Kernel in Ubilinux?, we already have ROS working on the board... do you think a kernel upgrade could mess our ROS configuration?

In general, do you have any successful experience in the configuration of a cp210x device?

Thanks in advance,

Héctor

答: The driver for cp2102 already exist in kernel, no need of extra efforts. Just use the correct udev rule file (not present by default in linux distro). An example is here. With this file /dev/ttyUSBX will be created.</p>

Body:
Dear community members,

We are working in the development of a robot autonomous control system running inside an Intel Edison, which -in turn- runs in a PixHawk automatic pilot module . This system uses ROS (Robot Operating System) and therefore we had to install Ubilinux. Our system requires being connected with a 360-degree laser (RPLIDAR-360) that sends data through a serial channel, so we are trying to get laser's data through USB-to-UART adapter (Silicon lab's CP2102) (the PixHawk only has a USB available for data transfer).

In summary, the laser is connected to the USB2UART adapter, and the adapter is connected to Edison's serial port.

However, we are stuck with some kind of driver issue. When tracing 'dmesg' the device is detected (idVendor=10c4, idProduct=ea60):

[  917.812195] usb usb2: Product: xHCI Host Controller
[  917.812214] usb usb2: Manufacturer: Linux 3.10.17-yocto-standard-r2 dwc-xhci
[  917.812232] usb usb2: SerialNumber: dwc3-host.2
[  917.812858] xHCI xhci_add_endpoint called for root hub
[  917.812878] xHCI xhci_check_bandwidth called for root hub
[  917.813141] hub 2-0:1.0: USB hub found
[  917.813185] hub 2-0:1.0: 1 port detected
[  918.128982] usb 1-1: new full-speed USB device number 2 using dwc3-host
[  918.151786] usb 1-1: New USB device found, idVendor=10c4, idProduct=ea60
[  918.151818] usb 1-1: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[  918.151839] usb 1-1: Product: CP2102 USB to UART Bridge Controller
[  918.151857] usb 1-1: Manufacturer: Silicon Labs
[  918.151875] usb 1-1: SerialNumber: 0001

With the following details:

T:  Bus=01 Lev=01 Prnt=01 Port=00 Cnt=01 Dev#=  2 Spd=12   MxCh= 0
D:  Ver= 1.10 Cls=00(>ifc ) Sub=00 Prot=00 MxPS=64 #Cfgs=  1
P:  Vendor=10c4 ProdID=ea60 Rev= 1.00
S:  Manufacturer=Silicon Labs
S:  Product=CP2102 USB to UART Bridge Controller
S:  SerialNumber=0001
C:* #Ifs= 1 Cfg#= 1 Atr=80 MxPwr=100mA
I:* If#= 0 Alt= 0 #EPs= 2 Cls=ff(vend.) Sub=00 Prot=00 Driver=(none)
E:  Ad=81(I) Atr=02(Bulk) MxPS=  64 Ivl=0ms
E:  Ad=01(O) Atr=02(Bulk) MxPS=  64 Ivl=0ms

But no /dev/ttyUSBX device is created, and there are no error messages about missing Drivers or configuration failures.

We are using Ubilinux 3, which reports the following with the 'uname' command:

 **  3.10.17-yocto-standard-r2

And the following is the listing of the installed drivers:

usb
/lib/modules/3.10.17-yocto-standard-r2/kernel/drivers/media/usb:
/lib/modules/3.10.17-yocto-standard-r2/kernel/drivers/media/usb/gspca:
/lib/modules/3.10.17-yocto-standard-r2/kernel/drivers/media/usb/uvc:
/lib/modules/3.10.17-yocto-standard-r2/kernel/drivers/usb:
/lib/modules/3.10.17-yocto-standard-r2/kernel/drivers/usb/gadget:
usb_f_acm.ko
/lib/modules/3.10.17-yocto-standard-r2/kernel/drivers/usb/serial:
usb_wwan.ko

Does anyone has had a similar configuration and managed to make work a CP2102 adapter?

As a last resort, we are trying to compile and install the driver by ourselves, using this reference: [url=https://askubuntu.com/questions/941594/installing-cp210x-driver]Installing CP210x Driver?Installing CP210x Driver? - Ask Ubuntu[/url]

The 'make' process crashes due to a lack of headers. We were unable to download the headers through APT, but at the end, we managed to compile the '.ko' module by downloading the headers manually from a Website.

However, after doing:

insmod cp210x.ko

We got:

Insmod: ERROR: could not insert module cp210x.ko: Invalid module format

So, at this point we have several questions... any advice about any of them would be really appreciated:

Does anybody know how to install the Kernel headers in Ubilinux - 3.10.17?

What is the official procedure to upgrade the Kernel in Ubilinux?, we already have ROS working on the board... do you think a kernel upgrade could mess our ROS configuration?

In general, do you have any successful experience in the configuration of a cp210x device?

Thanks in advance,

Héctor


来源: stackexchange

问:
Angular 4-5 HttpClientModule display data
With HttpModule I used this code to get data from Express.js REST API:

```<code>getArticles() {
  this.http.get('http://localhost:3000/api/articles')
    .map(res => res.json()).subscribe(res => this.articles = res);
}
</code>```

After that I would display the result in the template using binding.

Now, with HttpClientModule, I can't figure out how to do that. The documentation suggests using something like

```<code>this.httpClient.get('http://localhost:3000/api/articles')
  .subscribe(data => { this.results = data['results']; });
</code>```

But it doesn't work.

答: this.httpClient.getArticles().subscribe(data => this.results = data);</p>

ContentLicense: CC BY-SA 3.0

Body:
With HttpModule I used this code to get data from Express.js REST API:

getArticles() {
  this.http.get('http://localhost:3000/api/articles')
    .map(res => res.json()).subscribe(res => this.articles = res);
}

After that I would display the result in the template using binding.

Now, with HttpClientModule, I can't figure out how to do that. The documentation suggests using something like

this.httpClient.get('http://localhost:3000/api/articles')
  .subscribe(data => { this.results = data['results']; });

But it doesn't work.


问:
Solve Do-while loop
```<code>#include <iostream>
using namespace std;
int main()
{
double x = 1;
double y = 2;
int i = 1;
do
{
y /= 2.0;
x+= y;
++i;
cout << i;
}

while (x < 2.4);
}
</code>```

I thought the output would be 2, but that is not correct. Can someone explain why?

答: Have a look at the condition which controls whether or not your loop will execute again. At the end of the first loop, the value of x is 2.0. Since this is less than 2.4, the loop runs a second time. In total that means i is incremented twice raising it to 3.

Title: Solve Do-while loop

Body:
#include <iostream>
using namespace std;
int main()
{
double x = 1;
double y = 2;
int i = 1;
do
{
y /= 2.0;
x+= y;
++i;
cout << i;
}

while (x < 2.4);
}

I thought the output would be 2, but that is not correct. Can someone explain why?


问:
Get File Extension C#
I have a dropdown with list of file names. When a file name is selected in the dropdown I do the following

```<code>string filename = ddl.SelectedItem.Text;
string path = "F:\\WorkingCopy\\files\\" + filename +".docx";
DownloadFile(path,filename);
</code>```

In the file folder files may contain any extension . Since i have hard coded ".docx" in string path everything works fine. But I need to get the extension of the file name with the ddl.SelectedItem.Text alone. Can you tell me how to do this?

Things  I have
1.) File name without extension in

```<code>string filename = ddl.SelectedItem.Text;
</code>```

2.) Path where the file is located

```<code>string path = "F:\\WorkingCopy\\files\\" + filename
</code>```

I am trying to get the file extension with these . Can any one suggest on this?

答:
You can use Directory.GetFiles Method:

```<code>string result =  Directory.GetFiles(path, filename + ".*").FirstOrDefault();
</code>```

see here

here " * " is the WildCard and will search for the Filename starts with YourFileName.

Title: Get File Extension C#

Body:
I have a dropdown with list of file names. When a file name is selected in the dropdown I do the following

string filename = ddl.SelectedItem.Text;
string path = "F:\\WorkingCopy\\files\\" + filename +".docx";
DownloadFile(path,filename);

In the file folder files may contain any extension . Since i have hard coded ".docx" in string path everything works fine. But I need to get the extension of the file name with the ddl.SelectedItem.Text alone. Can you tell me how to do this?

Things  I have
1.) File name without extension in

string filename = ddl.SelectedItem.Text;

2.) Path where the file is located

string path = "F:\\WorkingCopy\\files\\" + filename

I am trying to get the file extension with these . Can any one suggest on this?

Body:
You can use Directory.GetFiles Method:

string result =  Directory.GetFiles(path, filename + ".*").FirstOrDefault();

see here

here " * " is the WildCard and will search for the Filename starts with YourFileName.


问:
Bind Listview to ObservableCollection
I am trying to bind a listview to an ObservableCollection.

I took a look at several topics on stack, but cannot find what I am doing wrong :

My XAML looks like that (for GridViewColumn I tried both wih Path=, and without, as I saw both of them) :

```<code><ListView x:Name="ListView1"  ItemsSource="{Binding listeAff}"  Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="4" MouseDoubleClick="ListView_MouseDoubleClick" GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler" >
            <ListView.ContextMenu>
                <ContextMenu x:Name="Context1">
                    <MenuItem Header="{x:Static p:Resources.ContextSupprimer}" Click="Supprimer_Element"/>
                    <MenuItem x:Name="MenuBarNesting" Header="{x:Static p:Resources.ContextMiseEnBarre}" Click="Open_MiseEnBarre"/>
                    <MenuItem x:Name="MenuExportDSTV1" Header="{x:Static  p:Resources.ContextExport}" Click="Export_DSTV"/>
                    <MenuItem x:Name="AjouterAffaire" Header="{x:Static  p:Resources.AjouterAffaire}" Click="AjoutAffaire"/>
                    <MenuItem x:Name="ModifyAffaire" Header="{x:Static  p:Resources.Edit}" Click="ModifierAffaire"/>
                </ContextMenu>
            </ListView.ContextMenu>
            <ListView.View>

                <GridView AllowsColumnReorder="true" x:Name="GridView1">
                    <GridViewColumn DisplayMemberBinding="{Binding Path=ID}" Header="ID" />
                    <GridViewColumn DisplayMemberBinding= "{Binding Nom}" Header="{x:Static p:Resources.Nom}"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Code}" Header="{x:Static p:Resources.Code}"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Comm}" Header="{x:Static p:Resources.Commentaire}"/>

                </GridView>
            </ListView.View>
        </ListView>
</code>```

Then code behind is so :

```<code>public ObservableCollection<Affaire> listeAff { get; set; }
        public MainWindow()
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(Properties.Settings.Default.Langue);
            InitializeComponent();
            Initialisation();
            listeAff = new ObservableCollection<Affaire>();
            DBConnect DataBase = new DBConnect();
            string requete = "SELECT * FROM affaire ORDER BY ID";
            List<Affaire> liste = DataBase.Select_affaire(requete);
            foreach(Affaire aff in liste)
            {
                listeAff.Add(aff);
            }
            DataContext = this;
</code>```

On that part my ListView is shown correctly, but when I want to delete(for example) some objects in list, listview is not updated :

```<code>foreach (Affaire aff in ListView1.SelectedItems)
                    {
                        listeAff.Remove(aff);
                    }
</code>```

What did I miss?

答:
Once you delete or remove something from the collection, the UI has to be notified about it so that it updates itself accordingly. What you have to do is use INotifyPropertyChanged event in your class. You can learn all you want about it here

Happy learning and happy coding !!

Title: Bind Listview to ObservableCollection

Body:
I am trying to bind a listview to an ObservableCollection.

I took a look at several topics on stack, but cannot find what I am doing wrong :

My XAML looks like that (for GridViewColumn I tried both wih Path=, and without, as I saw both of them) :

<ListView x:Name="ListView1"  ItemsSource="{Binding listeAff}"  Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="4" MouseDoubleClick="ListView_MouseDoubleClick" GridViewColumnHeader.Click="GridViewColumnHeaderClickedHandler" >
            <ListView.ContextMenu>
                <ContextMenu x:Name="Context1">
                    <MenuItem Header="{x:Static p:Resources.ContextSupprimer}" Click="Supprimer_Element"/>
                    <MenuItem x:Name="MenuBarNesting" Header="{x:Static p:Resources.ContextMiseEnBarre}" Click="Open_MiseEnBarre"/>
                    <MenuItem x:Name="MenuExportDSTV1" Header="{x:Static  p:Resources.ContextExport}" Click="Export_DSTV"/>
                    <MenuItem x:Name="AjouterAffaire" Header="{x:Static  p:Resources.AjouterAffaire}" Click="AjoutAffaire"/>
                    <MenuItem x:Name="ModifyAffaire" Header="{x:Static  p:Resources.Edit}" Click="ModifierAffaire"/>
                </ContextMenu>
            </ListView.ContextMenu>
            <ListView.View>

                <GridView AllowsColumnReorder="true" x:Name="GridView1">
                    <GridViewColumn DisplayMemberBinding="{Binding Path=ID}" Header="ID" />
                    <GridViewColumn DisplayMemberBinding= "{Binding Nom}" Header="{x:Static p:Resources.Nom}"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Code}" Header="{x:Static p:Resources.Code}"/>
                    <GridViewColumn DisplayMemberBinding="{Binding Comm}" Header="{x:Static p:Resources.Commentaire}"/>

                </GridView>
            </ListView.View>
        </ListView>

Then code behind is so :

public ObservableCollection<Affaire> listeAff { get; set; }
        public MainWindow()
        {
            Thread.CurrentThread.CurrentUICulture = new CultureInfo(Properties.Settings.Default.Langue);
            InitializeComponent();
            Initialisation();
            listeAff = new ObservableCollection<Affaire>();
            DBConnect DataBase = new DBConnect();
            string requete = "SELECT * FROM affaire ORDER BY ID";
            List<Affaire> liste = DataBase.Select_affaire(requete);
            foreach(Affaire aff in liste)
            {
                listeAff.Add(aff);
            }
            DataContext = this;

On that part my ListView is shown correctly, but when I want to delete(for example) some objects in list, listview is not updated :

foreach (Affaire aff in ListView1.SelectedItems)
                    {
                        listeAff.Remove(aff);
                    }

What did I miss?


问:
Is there a way to install the scipy special module without the rest of scipy?
I'm writing some Python numerical code and would like to use some functions from the special module. So far, my code only depends on numpy, which I've found very easy to install in a variety of Python environments. Installing scipy, on the other hand, has generally been an exercise in frustration.  Is there a way to get just the special module?

Note, I see now that there is a downloadable scipy package for the Mac, but that hasn't always been the case

答: The scipy subpackages can usually be installed individually.  Try cd-ing to the "special" directory and running your normal "python setup.py install".  The name space for importing should now be special and now scipy.special.

OwnerDisplayName: Nick

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Jeff Bauer

OwnerDisplayName: Matt


问:
Fetch result from MongoDB without deserialization
I need to fetch lots of data from Mongo, and feed it directly to the client Javascript without processing in the middle, so I don't actually need the data to be deserialized/re-serialized.

I understand that Mongo does not actually store data in JSON (it just looks like it), but is there a way to minimize the amount of time spent serializing/deserializing the data ? With a few hundred thousand objects by query, each one takes a surprisingly huge amount of time.

The most basic way I have found to get JSON is this :

```<code>return this.db.GetCollection<BsonDocument>("mycollection")
            .Find(Builders<BsonDocument>.Filter.Eq("FileId", fileId))
            .Project(Builders<BsonDocument>.Projection.Exclude("_id"))
            .ToList().ToJson(this.jsonWriterSettings);
</code>```

答:
You could use RawBsonDocument (rather than BsonDocument), but I'm not sure that's going to completely solve your problem. You could try to tackle your own custom/specialized deserialization to improve efficiency.

Deserializing is generally a fairly expensive operation. If possible, minimizing the number of documents (perhaps by a schema change) and/or minimizing the number of fields should help.

Body:
I need to fetch lots of data from Mongo, and feed it directly to the client Javascript without processing in the middle, so I don't actually need the data to be deserialized/re-serialized.

I understand that Mongo does not actually store data in JSON (it just looks like it), but is there a way to minimize the amount of time spent serializing/deserializing the data ? With a few hundred thousand objects by query, each one takes a surprisingly huge amount of time.

The most basic way I have found to get JSON is this :

return this.db.GetCollection<BsonDocument>("mycollection")
            .Find(Builders<BsonDocument>.Filter.Eq("FileId", fileId))
            .Project(Builders<BsonDocument>.Projection.Exclude("_id"))
            .ToList().ToJson(this.jsonWriterSettings);


问:
cannot be cast to java.lang.Long Android SharedPreferences
After a fresh install of my APP I am getting the following exception:

```<code>java.lang.RuntimeException: Unable to start activity ...
java.lang.ClassCastException: java.lang.Integer cannot be cast to
java.lang.Long
</code>```

The (Activity) code:

Initialization long (outside of onCreate):

```<code>long spinTimer = 0L;
</code>```

Assign previous long val from pefs- or default to 0L (within onCreate):

```<code>spinTimer = settings.getLong("spinTimer", 0L);
</code>```

Should be a long, where is the int coming from?

Other code references where the sharepref gets its values (all long):

```<code>if (item.equals("Select...")) {editor.putLong("spinTimer", 0L);}
if (item.equals("5 mins")) {editor.putLong("spinTimer", System.currentTimeMillis() + (5 * 60 * 1000));}
if (item.equals("10 mins")) {editor.putLong("spinTimer", System.currentTimeMillis() + (10 * 60 * 1000));}
if (item.equals("15 mins")) {editor.putLong("spinTimer", System.currentTimeMillis() + (15 * 60 * 1000));}
if (item.equals("30 mins")) {editor.putLong("spinTimer", System.currentTimeMillis() + (30 * 60 * 1000));}
if (item.equals("1 hour")) {editor.putLong("spinTimer", System.currentTimeMillis() + (60 * 60 * 1000));}
editor.commit();
spinTimer = settings.getLong("spinTimer", 0L);
</code>```

After clearing APP data, all is good. Which I should not have to do each time I fresh install the APP.

How in the world is an int sneaking in there?

Requested DEBUG INFO - Not standard, but thought this should suffice:

Relevant lines of code (simple Activity) where the crash is occurring:

```<code>log.debug("***Activity Start***");
log.debug("OnCreateEnter");
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
log.debug("spinTimer: {}", spinTimer);
spinTimer = settings.getLong("spinTimer", 0L); // <-- APP crashes right here
</code>```

Output:

```<code>***Activity Start***
OnCreateEnter
spinTimer: 0
</code>```

1) Shouldn't the 2nd argument to .getLong (0L) be assigned to variable  (spinTimer) if nothing is assigned? I also tried '0'.

2) How is an int getting assigned? Both the key 'spinTimer' (0L) and var 'spinTimer' ('long spinTimer = 0L;') are initialized as longs.

3) If I clear the APP data (after the fresh install)- all is well;

4) And if I add the following lines of code before the above statements- all goes well (but this approach skews up my logic):

```<code>editor.putLong("spinTimer", spinTimer);
editor.commit();
</code>```

答:
```<code>java.lang.ClassCastException: java.lang.Integer cannot be cast to
java.lang.Long
</code>```

Due to ClassCastException problem , You should use Long.valueOf.

Returns a Long instance representing the specified long value. If a
  new Long instance is not required, this method should generally be
  used in preference to the constructor Long(long), as this method is
  likely to yield significantly better space and time performance by
  caching frequently requested values. Note that unlike the
  corresponding method in the Integer class, this method is not required
  to cache values within a particular range.

```<code>editor.putLong("spinTimer", Long.valueOf(System.currentTimeMillis() + (5 * 60 * 1000))
</code>```

Body:
After a fresh install of my APP I am getting the following exception:

java.lang.RuntimeException: Unable to start activity ...
java.lang.ClassCastException: java.lang.Integer cannot be cast to
java.lang.Long

The (Activity) code:

Initialization long (outside of onCreate):

long spinTimer = 0L;

Assign previous long val from pefs- or default to 0L (within onCreate):

spinTimer = settings.getLong("spinTimer", 0L);

Should be a long, where is the int coming from?

Other code references where the sharepref gets its values (all long):

if (item.equals("Select...")) {editor.putLong("spinTimer", 0L);}
if (item.equals("5 mins")) {editor.putLong("spinTimer", System.currentTimeMillis() + (5 * 60 * 1000));}
if (item.equals("10 mins")) {editor.putLong("spinTimer", System.currentTimeMillis() + (10 * 60 * 1000));}
if (item.equals("15 mins")) {editor.putLong("spinTimer", System.currentTimeMillis() + (15 * 60 * 1000));}
if (item.equals("30 mins")) {editor.putLong("spinTimer", System.currentTimeMillis() + (30 * 60 * 1000));}
if (item.equals("1 hour")) {editor.putLong("spinTimer", System.currentTimeMillis() + (60 * 60 * 1000));}
editor.commit();
spinTimer = settings.getLong("spinTimer", 0L);

After clearing APP data, all is good. Which I should not have to do each time I fresh install the APP.

How in the world is an int sneaking in there?

Requested DEBUG INFO - Not standard, but thought this should suffice:

Relevant lines of code (simple Activity) where the crash is occurring:

log.debug("***Activity Start***");
log.debug("OnCreateEnter");
SharedPreferences settings =
PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = settings.edit();
log.debug("spinTimer: {}", spinTimer);
spinTimer = settings.getLong("spinTimer", 0L); // <-- APP crashes right here

Output:

***Activity Start***
OnCreateEnter
spinTimer: 0

1) Shouldn't the 2nd argument to .getLong (0L) be assigned to variable  (spinTimer) if nothing is assigned? I also tried '0'.

2) How is an int getting assigned? Both the key 'spinTimer' (0L) and var 'spinTimer' ('long spinTimer = 0L;') are initialized as longs.

3) If I clear the APP data (after the fresh install)- all is well;

4) And if I add the following lines of code before the above statements- all goes well (but this approach skews up my logic):

editor.putLong("spinTimer", spinTimer);
editor.commit();

Body:
java.lang.ClassCastException: java.lang.Integer cannot be cast to
java.lang.Long

Due to ClassCastException problem , You should use Long.valueOf.

Returns a Long instance representing the specified long value. If a
  new Long instance is not required, this method should generally be
  used in preference to the constructor Long(long), as this method is
  likely to yield significantly better space and time performance by
  caching frequently requested values. Note that unlike the
  corresponding method in the Integer class, this method is not required
  to cache values within a particular range.

editor.putLong("spinTimer", Long.valueOf(System.currentTimeMillis() + (5 * 60 * 1000))


问:
Text position got changed after JSON is loaded on canvas in fabricJS
I have observed change in position of text when creating fresh on canvas and when JSON is loaded on canvas. Normally on moving element on canvas values for left and top goes upto 14 decimal places and when JSON is loaded the position comes out to be upto two places.

e.g. In picture1 text left position  is 294.63668348469565 and text top is 202.79140935082407 after saving and loading back JSON, positon slightly got changed but left is 294.63 and top is 202.80 (picture2)
picture1
picture2

I guess upto 14 decimal is for very precision, does less decimal places can govern this change?

答:
So got it fixed, not the best solution but working fine.

First of all thanx to @AndreaBogazzi for the catch on width and height for the text, so re-assigned the values after items get loaded on canvas and rendered it.

But for curvedText element obeserved the same problem so I did some work around to fix it, first I get all the properties of existing curvedText element props = obj.toObject() then var textSample = new fabric.CurvedText(obj.getText(), props) and then  :

canvas.getObjects().splice(key,1) //@ remove the old curved text element

canvas.add(textSample) //@ add the curved  text (will be added in last)

canvas.getObjects().splice(key,0,canvas.getObjects().pop()); //@ reposition it to the old curved object position

and the rendered it and it works.

I believe there might be some other  better way rather than re-creating element and then doing all the steps for fixing.


问:
Information about remote IP addresses
I want to track all IP addresses with which my computer is communicating. I am using C# and Visual Studio. There is one listBox in which I will put all remote IP address. I am new to network programming so I need some direction about that kind of problem.

My question is how to do this? How to get information about remote IP addresses which which my computer make connections?

答:
You could leverage the netstat command to get information about which IP addresses and ports your machine is communicating with. You could run this command on a regular basis and parse the text output.

For example, the following command will list the state of all connections including local and remote connection details:

```<code>C:\Users\chibacity>netstat -a -n

Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    10.0.0.107:32495       209.85.229.125:5222    ESTABLISHED
  TCP    10.0.0.107:32507       209.85.229.125:5222    ESTABLISHED
  TCP    10.0.0.107:32520       209.85.229.18:443      ESTABLISHED
  TCP    10.0.0.107:32755       209.85.227.109:993     ESTABLISHED
  //etc...
</code>```

Or if you have admin privilleges you can get executable details too:

```<code>PS C:\Windows\system32> netstat -a -n -b

Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    10.0.0.107:32495       209.85.229.125:5222    ESTABLISHED
 [googletalk.exe]
  TCP    10.0.0.107:32507       209.85.229.125:5222    ESTABLISHED
 [chrome.exe]
  TCP    10.0.0.107:32520       209.85.229.18:443      ESTABLISHED
 [chrome.exe]
  TCP    10.0.0.107:32755       209.85.227.109:993     ESTABLISHED
  //etc...
</code>```

You can call this command from .Net using System.Diagnostics.Process and parse the text output, e.g:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx

Title: Information about remote IP addresses

Body:
You could leverage the netstat command to get information about which IP addresses and ports your machine is communicating with. You could run this command on a regular basis and parse the text output.

For example, the following command will list the state of all connections including local and remote connection details:

C:\Users\chibacity>netstat -a -n

Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    10.0.0.107:32495       209.85.229.125:5222    ESTABLISHED
  TCP    10.0.0.107:32507       209.85.229.125:5222    ESTABLISHED
  TCP    10.0.0.107:32520       209.85.229.18:443      ESTABLISHED
  TCP    10.0.0.107:32755       209.85.227.109:993     ESTABLISHED
  //etc...

Or if you have admin privilleges you can get executable details too:

PS C:\Windows\system32> netstat -a -n -b

Active Connections

  Proto  Local Address          Foreign Address        State
  TCP    10.0.0.107:32495       209.85.229.125:5222    ESTABLISHED
 [googletalk.exe]
  TCP    10.0.0.107:32507       209.85.229.125:5222    ESTABLISHED
 [chrome.exe]
  TCP    10.0.0.107:32520       209.85.229.18:443      ESTABLISHED
 [chrome.exe]
  TCP    10.0.0.107:32755       209.85.227.109:993     ESTABLISHED
  //etc...

You can call this command from .Net using System.Diagnostics.Process and parse the text output, e.g:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.standardoutput.aspx


答:
Use the Directory.GetFiles() method. Something like this

```<code>string[] files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename+".*");
</code>```

This should get you an array of filenames with the same filename but different extensions. If you have only one, then you can always use the first one.

Title: Get File Extension C#

Body:
Use the Directory.GetFiles() method. Something like this

string[] files = Directory.GetFiles("F:\\WorkingCopy\\files\\", filename+".*");

This should get you an array of filenames with the same filename but different extensions. If you have only one, then you can always use the first one.


问:
TFS: Rolling back package references
I recently committed a changeset which added references to Castle.Core.4.2.1 and Moq.4.7.145. I would like to roll back this changeset.

My workspace contains the latest source code from source control, as you can see in this screenshot:

On my local workspace, the packages are also there:

Using Visual Studio, I navigated to Source Control Explorer, right-clicked on Castle.Core.4.2.1, selected "Rollback...", and entered the number of the changeset in which I first added the reference.

Immediately I saw the following warnings:

On my local workspace, Castle.Core.4.2.1 can no longer be found:

I am unable to commit a rollback of the changeset because of the warnings that you saw -- my local copy of Castle.Core.4.2.1 was deleted immediately after I performed a rollback.

How can I fix this?

答: You got the warnings is because you applied Check-in policy for this team project. Try to go to Settings -- Source Control -- Check-in Policy to disable the policy:

Title: TFS: Rolling back package references


问:
Maven compile successful, but install failed
I am using maven 3.2.2 and jdk-1.7.0_60. I am executing mvn compile for a particular project, the compilation succeeds. But when I run mvn clean install on the same component, I get the following error-

```<code>[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /C:/projects/myProject/src/mainTest.java:[105,56] cannot find symbol
  symbol:   method getIdFromName(java.lang.String)
  location: class java.lang.Object
</code>```

What could be the reason behind this? Doesn't mvn compile actually compile everything? As far as I know, the only difference between mvn compile and mvn clean install is that the latter command copies the required jar.

答:
I was facing same, this started when I added unit test cases, what worked for me is, first run

```<code>mvn clean install -DskipTests=true
</code>```

Then again run

```<code>mvn clean install
</code>```

Body:
I am using maven 3.2.2 and jdk-1.7.0_60. I am executing mvn compile for a particular project, the compilation succeeds. But when I run mvn clean install on the same component, I get the following error-

[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /C:/projects/myProject/src/mainTest.java:[105,56] cannot find symbol
  symbol:   method getIdFromName(java.lang.String)
  location: class java.lang.Object

What could be the reason behind this? Doesn't mvn compile actually compile everything? As far as I know, the only difference between mvn compile and mvn clean install is that the latter command copies the required jar.

Body:
I was facing same, this started when I added unit test cases, what worked for me is, first run

mvn clean install -DskipTests=true

Then again run

mvn clean install


问:
CLI is not showing colors. PHP
this is the issue.

When I use this php code echo "\033[31m some colored text \033[0m some white text \n"; to add some color to text I get [31m some colored text [0m some white text as response instead of colored text.

The CLI is actually showing colors, but not when I use php code.

How can I fix it?

I'm using Windows 10.

Thanks.

Screenshot of the CLI

答:
PHP CLI output is aka plain text and the color depends on settings of the on terminal which is basically monochromatic (white on black, etc.).

The colors in your example \033[31m are color definitions from shell script expected to be running in linux-like terminal. Colored shell script output library

Windows command prompts supports colours however for batch scripts or so colors in the Windows command line

Edit: on your screenshot is PHP output a plaintext white on black as the terminal color schema is. The echo  with red on black is output of shell echo command which is interpreted bash command and it has the power to colorize the output.

Title: CLI is not showing colors. PHP


问:
Echo Class Inside of HTML Tag with PHP
Trying to get this piece of code to run:

```<code><li><a <? if ($tab=='Home') echo 'class="activetab"' ?> href="/">Home</a></li>
</code>```

Right now, my PHP/Apache on EC2 setup spits out

```<code>href="/">Home
</code>```

It looks like the php inside the tag is messing up the rendering, and I'd like the tab to be rendered.

The  site is hosted somewhere else and works, so it seems like a configuration issue with either php or apache.

答:
Try By This Code</p>

```<code><li><a <?php if ($tab=='Home') echo 'class="activetab"' ?> href="/">Home</a></li>
</code>```

Title: Echo Class Inside of HTML Tag with PHP

Body:
Trying to get this piece of code to run:

<a <? if ($tab=='Home') echo 'class="activetab"' ?> href="/">Home

Right now, my PHP/Apache on EC2 setup spits out

href="/">Home

It looks like the php inside the tag is messing up the rendering, and I'd like the tab to be rendered.

The  site is hosted somewhere else and works, so it seems like a configuration issue with either php or apache.

Body:
Try By This Code

<li><a <?php if ($tab=='Home') echo 'class="activetab"' ?> href="/">Home</a></li>


问:
Click on object to do certain function
I'm programming on JavaScript and basically what I'm supposed to do is to draw a face on a canvas and those faces have certain effects.

One of the effects I'm supposed to do is to click on the nose and it will change the face to an angry face. I have created objects for all the face parts (nose, eyes, etc.) and what I'm trying to do is that I want the function "angryFace" to be called when the nose is clicked. The nose is already an object.

Been stuck for a long time on this. Would appreciate it if someone could help! Uploaded the whole code down here. Thanks guys!

```<code><!doctype html>

<html lang="en">

<head>
    <meta charset="utf-8">
    <title>COM1008 Assignment 2</title>
    <link rel="stylesheet" href="main1.css">
</head>

<main>
    <h1>COM 1008 Assignment 2</h1>
    <p>By Samuel Fung Chi Lun</p>
</main>

<body>
    <canvas id="canvasFrame" width="600" height="600"></canvas>
    <p>
        <button name="sadbutton" id="sadFace">Sad</button>
        <button name="angrybutton" id="angryFace">Angry</button>
        <button name="surprisedbutton" id="surprisedFace">Surprised</button>
        <button name="neutralbutton" id="neutralFace">Neutral</button>
    </p>
    <script>
        var canvas = document.getElementById('canvasFrame');
        var context = canvas.getContext('2d');
        //Function to obtain x and y coordinates of mouse positions - Obtained from 20/11/2017 lecture slides
        function getMouseXY(e) {
            var boundingRect = canvas.getBoundingClientRect();
            var offsetX = boundingRect.left;
            var offsetY = boundingRect.top;
            var w = (boundingRect.width - canvas.width);
            var h = (boundingRect.height - canvas.height);
            offsetX += w;
            offsetY += h;
            var mx = Math.round(e.clientX - offsetX);
            var my = Math.round(e.clientY - offsetY);
            return { x: mx, y: my };
        }

        const BROWS_UP = 190;
        const BROWS_DOWN = 170;

        //Creating an object for left eye brow
        var leftEyeB = {
            draw: function (x1,brows_direction1,x2,brows_direction2) {
                context.beginPath();
                context.lineWidth = 18;
                context.moveTo(x1, brows_direction1);
                context.lineTo(x2, brows_direction2)
                context.stroke();
            }
        };
        //Creating an object for right eye brow
        var rightEyeB = {
            draw: function (x1,brows_direction1,x2,brows_direction2) {
                context.beginPath();
                context.lineWidth = 18;
                context.moveTo(x1, brows_direction1);
                context.lineTo(x2, brows_direction2)
                context.stroke();
            }
        };
        //Creating an object for the head
        var faceShape = {
            draw: function() {
                context.beginPath();
                context.fillStyle = "rgb(255,255,0)"
                context.lineWidth = 3;
                context.arc(300, 300, 200, 0, Math.PI * 2, true);
                context.fill();
                context.stroke();
            }
        }
        //Creating an object for the eyes
        var eyes = {
            draw: function() {
                context.beginPath();
                context.fillStyle = "rgb(0,0,0)";
                context.moveTo(255, 250); //LeftEye
                context.arc(220, 250, 40, 0, Math.PI * 2, true);
                context.moveTo(415, 250);//Right Eye
                context.arc(380, 250, 40, 0, Math.PI * 2, true);
                context.fill();
                context.fill();
                context.stroke();
                context.beginPath();
                context.fillStyle = "rgb(255,255,255)";
                context.moveTo(240, 250); //LeftPupil
                context.arc(220, 250, 15, 0, Math.PI * 2, true);
                context.moveTo(400, 250); //Right Pupil
                context.arc(380, 250, 15, 0, Math.PI * 2, true);
                context.fill();
                context.stroke();
            }
        }
        //Creating an object for the nose
        var nose = {
            draw: function() {
                context.beginPath();
                context.fillStyle = "rgb(0,0,0)";
                context.moveTo(300, 275);
                context.lineTo(275, 325);
                context.lineTo(325, 325);
                context.fill();
                context.closePath();
                context.stroke();
            }
        }
        //Creating an object for the mouth
        var mouth = {
            frown: function() {
                context.beginPath();
                context.fillStyle = "rgb(0,0,0)";
                context.moveTo(305, 427);//Mouth
                context.arc(305, 427, 80, 0, Math.PI, true);
                context.fill();
                context.closePath();
                context.stroke();
            },
            circle: function() {
                context.beginPath();
                context.fillStyle = "rgb(0,0,0)";
                context.arc(300, 400, 50, 0, Math.PI * 2, true);
                context.fill();
                context.stroke();
            },
            straight: function() {
                context.beginPath();
                context.fillStyle = "rgb(0,0,0)";
                context.rect(225, 390, 150, 20);//Mouth
                context.fill();
                context.stroke();
            }
        }
        //Drawing the sad face
        function sadFace() {
            faceShape.draw();
            eyes.draw();
            nose.draw();
            mouth.frown();
            leftEyeB.draw(175,BROWS_DOWN,265,BROWS_DOWN);
            rightEyeB.draw(335,BROWS_DOWN,425,BROWS_DOWN);
        }
        //Drawing the angry face
        function angryFace() {
            faceShape.draw();
            eyes.draw();
            nose.draw();
            mouth.frown();
            leftEyeB.draw(175,BROWS_DOWN,265,BROWS_UP);
            rightEyeB.draw(335,BROWS_UP,425,BROWS_DOWN);
        }
        //Drawing the surprised face
        function surprisedFace() {
            faceShape.draw();
            eyes.draw();
            nose.draw();
            mouth.circle();
            leftEyeB.draw(175,BROWS_UP,265,BROWS_DOWN);
            rightEyeB.draw(335,BROWS_DOWN,425,BROWS_UP);
        }
        //Drawing the neutral face
        function neutralFace() {
            faceShape.draw();
            eyes.draw();
            nose.draw();
            mouth.circle();
            leftEyeB.draw(175,BROWS_DOWN,265,BROWS_DOWN);
            rightEyeB.draw(335,BROWS_DOWN,425,BROWS_DOWN);
        }
        //Not sure how to properly do the bottom part. It does not work at all for the eyebrows one so please help!
        function effects() {
            //Click on the eyebrows to raise them
            if (mousePosition.x > x1 && mousePosition.x < x2 && mousePosition.y < BROWS_UP && mousePosition.y > BROWS_DOWN) {
                BROWS_UP += 20;
            }
            //Click on eye to show angry face
            if (mousePosition = on coordinates of the eye) {
                angryFace();
            }
            //Click on nose to show happy face
            if (mousePosition = on coordinates of the nose) {
                smileFace();
            }
        }

        canvas.addEventListener('click', function(evt) {
            effects(evt);
        });

        neutralFace();

        //Linking the face functions to the buttons
        var angryButton = document.getElementById("angryFace");
        var sadButton = document.getElementById("sadFace");
        var surprisedButton = document.getElementById("surprisedFace");
        var neutralButton = document.getElementById("neutralFace");
        sadButton.addEventListener("click", sadFace);
        angryButton.addEventListener("click", angryFace);
        surprisedButton.addEventListener("click", surprisedFace);
        neutralButton.addEventListener("click", neutralFace);
    </script>
</body>
</html>
</code>```

答:
When you make face, for you, there are different objects(say nose, eyes etc). For DOM, there is only 1  object i.e. Canvas. So when you click, you are clicking on canvas and not nose.

So to achieve this, you will have to play with coordinates. You have to assume the position of every container and on click of canvas, check the coordinates. If the coordinates are within range of some object, fire necessary function.

canvas.addEventListener('click', function(event){
  var x = event.clientX, y = event.clientY;
  if(x> 280 && x <335 && y > 280 && y <335) {
    // nose is clicked.
    angryFace();
  }
  else {
    neutralFace();
  }
})
```

<p>Following is a partial sample:</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var canvas = document.getElementById('canvasFrame');
var context = canvas.getContext('2d');
//Function to obtain x and y coordinates of mouse positions - Obtained from 20/11/2017 lecture slides
function getMouseXY(e) {
  var boundingRect = canvas.getBoundingClientRect();
  var offsetX = boundingRect.left;
  var offsetY = boundingRect.top;
  var w = (boundingRect.width - canvas.width);
  var h = (boundingRect.height - canvas.height);
  offsetX += w;
  offsetY += h;
  var mx = Math.round(e.clientX - offsetX);
  var my = Math.round(e.clientY - offsetY);
  return {
    x: mx,
    y: my
  };
}

const BROWS_UP = 190;
const BROWS_DOWN = 170;

//Creating an object for left eye brow
var leftEyeB = {
  draw: function(x1, brows_direction1, x2, brows_direction2) {
    context.beginPath();
    context.lineWidth = 18;
    context.moveTo(x1, brows_direction1);
    context.lineTo(x2, brows_direction2)
    context.stroke();
  }
};
//Creating an object for right eye brow
var rightEyeB = {
  draw: function(x1, brows_direction1, x2, brows_direction2) {
    context.beginPath();
    context.lineWidth = 18;
    context.moveTo(x1, brows_direction1);
    context.lineTo(x2, brows_direction2)
    context.stroke();
  }
};
//Creating an object for the head
var faceShape = {
  draw: function() {
    context.beginPath();
    context.fillStyle = "rgb(255,255,0)"
    context.lineWidth = 3;
    context.arc(300, 300, 200, 0, Math.PI * 2, true);
    context.fill();
    context.stroke();
  }
}
//Creating an object for the eyes
var eyes = {
  draw: function() {
    context.beginPath();
    context.fillStyle = "rgb(0,0,0)";
    context.moveTo(255, 250); //LeftEye
    context.arc(220, 250, 40, 0, Math.PI * 2, true);
    context.moveTo(415, 250); //Right Eye
    context.arc(380, 250, 40, 0, Math.PI * 2, true);
    context.fill();
    context.fill();
    context.stroke();
    context.beginPath();
    context.fillStyle = "rgb(255,255,255)";
    context.moveTo(240, 250); //LeftPupil
    context.arc(220, 250, 15, 0, Math.PI * 2, true);
    context.moveTo(400, 250); //Right Pupil
    context.arc(380, 250, 15, 0, Math.PI * 2, true);
    context.fill();
    context.stroke();
  }
}
//Creating an object for the nose
var nose = {
  draw: function() {
    context.beginPath();
    context.fillStyle = "rgb(0,0,0)";
    context.moveTo(300, 275);
    context.lineTo(275, 325);
    context.lineTo(325, 325);
    context.fill();
    context.closePath();
    context.stroke();
  }
}
//Creating an object for the mouth
var mouth = {
  frown: function() {
    context.beginPath();
    context.fillStyle = "rgb(0,0,0)";
    context.moveTo(305, 427); //Mouth
    context.arc(305, 427, 80, 0, Math.PI, true);
    context.fill();
    context.closePath();
    context.stroke();
  },
  circle: function() {
    context.beginPath();
    context.fillStyle = "rgb(0,0,0)";
    context.arc(300, 400, 50, 0, Math.PI * 2, true);
    context.fill();
    context.stroke();
  },
  straight: function() {
    context.beginPath();
    context.fillStyle = "rgb(0,0,0)";
    context.rect(225, 390, 150, 20); //Mouth
    context.fill();
    context.stroke();
  }
}
//Drawing the sad face
function sadFace() {
  faceShape.draw();
  eyes.draw();
  nose.draw();
  mouth.frown();
  leftEyeB.draw(175, BROWS_DOWN, 265, BROWS_DOWN);
  rightEyeB.draw(335, BROWS_DOWN, 425, BROWS_DOWN);
}
//Drawing the angry face
function angryFace() {
  faceShape.draw();
  eyes.draw();
  nose.draw();
  mouth.frown();
  leftEyeB.draw(175, BROWS_DOWN, 265, BROWS_UP);
  rightEyeB.draw(335, BROWS_UP, 425, BROWS_DOWN);
}
//Drawing the surprised face
function surprisedFace() {
  faceShape.draw();
  eyes.draw();
  nose.draw();
  mouth.circle();
  leftEyeB.draw(175, BROWS_UP, 265, BROWS_DOWN);
  rightEyeB.draw(335, BROWS_DOWN, 425, BROWS_UP);
}
//Drawing the neutral face
function neutralFace() {
  faceShape.draw();
  eyes.draw();
  nose.draw();
  mouth.circle();
  leftEyeB.draw(175, BROWS_DOWN, 265, BROWS_DOWN);
  rightEyeB.draw(335, BROWS_DOWN, 425, BROWS_DOWN);
}

function effects() {
  mousePosition = getMouseXY(e);
  console.log(mousePosition);

}
neutralFace();

canvas.addEventListener('click', function(event){
  var x = event.clientX, y = event.clientY;
  if(x> 280 && x <335 && y > 280 && y <335) {
    // nose is clicked.
    angryFace();
  }
  else {
    neutralFace();
  }
})

//Linking the face functions to the buttons
var angryButton = document.getElementById("angryFace");
var sadButton = document.getElementById("sadFace");
var surprisedButton = document.getElementById("surprisedFace");
var neutralButton = document.getElementById("neutralFace");
sadButton.addEventListener("click", sadFace);
angryButton.addEventListener("click", angryFace);
surprisedButton.addEventListener("click", surprisedFace);
neutralButton.addEventListener("click", neutralFace);</code>```

<canvas id='canvasFrame' width=600 height=600></canvas>

  <button id="angryFace">Angry Face</button>
  <button id="sadFace">Sad Face</button>
  <button id="surprisedFace">Surprised Face</button>
  <button id="neutralFace">Neutral Face</button>

```

Title: Click on object to do certain function

Body:
I'm programming on JavaScript and basically what I'm supposed to do is to draw a face on a canvas and those faces have certain effects.

One of the effects I'm supposed to do is to click on the nose and it will change the face to an angry face. I have created objects for all the face parts (nose, eyes, etc.) and what I'm trying to do is that I want the function "angryFace" to be called when the nose is clicked. The nose is already an object.

Been stuck for a long time on this. Would appreciate it if someone could help! Uploaded the whole code down here. Thanks guys!

<!doctype html>

    <meta charset="utf-8">
    <title>COM1008 Assignment 2</title>
    <link rel="stylesheet" href="main1.css">

COM 1008 Assignment 2

By Samuel Fung Chi Lun

    <canvas id="canvasFrame" width="600" height="600"></canvas>

        <button name="sadbutton" id="sadFace">Sad</button>
        <button name="angrybutton" id="angryFace">Angry</button>
        <button name="surprisedbutton" id="surprisedFace">Surprised</button>
        <button name="neutralbutton" id="neutralFace">Neutral</button>

Body:
When you make face, for you, there are different objects(say nose, eyes etc). For DOM, there is only 1  object i.e. Canvas. So when you click, you are clicking on canvas and not nose.

So to achieve this, you will have to play with coordinates. You have to assume the position of every container and on click of canvas, check the coordinates. If the coordinates are within range of some object, fire necessary function.

canvas.addEventListener('click', function(event){
  var x = event.clientX, y = event.clientY;
  if(x> 280 && x <335 && y > 280 && y <335) {
    // nose is clicked.
    angryFace();
  }
  else {
    neutralFace();
  }
})

Following is a partial sample:

var canvas = document.getElementById('canvasFrame');
var context = canvas.getContext('2d');
//Function to obtain x and y coordinates of mouse positions - Obtained from 20/11/2017 lecture slides
function getMouseXY(e) {
  var boundingRect = canvas.getBoundingClientRect();
  var offsetX = boundingRect.left;
  var offsetY = boundingRect.top;
  var w = (boundingRect.width - canvas.width);
  var h = (boundingRect.height - canvas.height);
  offsetX += w;
  offsetY += h;
  var mx = Math.round(e.clientX - offsetX);
  var my = Math.round(e.clientY - offsetY);
  return {
    x: mx,
    y: my
  };
}

const BROWS_UP = 190;
const BROWS_DOWN = 170;

//Creating an object for left eye brow
var leftEyeB = {
  draw: function(x1, brows_direction1, x2, brows_direction2) {
    context.beginPath();
    context.lineWidth = 18;
    context.moveTo(x1, brows_direction1);
    context.lineTo(x2, brows_direction2)
    context.stroke();
  }
};
//Creating an object for right eye brow
var rightEyeB = {
  draw: function(x1, brows_direction1, x2, brows_direction2) {
    context.beginPath();
    context.lineWidth = 18;
    context.moveTo(x1, brows_direction1);
    context.lineTo(x2, brows_direction2)
    context.stroke();
  }
};
//Creating an object for the head
var faceShape = {
  draw: function() {
    context.beginPath();
    context.fillStyle = "rgb(255,255,0)"
    context.lineWidth = 3;
    context.arc(300, 300, 200, 0, Math.PI * 2, true);
    context.fill();
    context.stroke();
  }
}
//Creating an object for the eyes
var eyes = {
  draw: function() {
    context.beginPath();
    context.fillStyle = "rgb(0,0,0)";
    context.moveTo(255, 250); //LeftEye
    context.arc(220, 250, 40, 0, Math.PI * 2, true);
    context.moveTo(415, 250); //Right Eye
    context.arc(380, 250, 40, 0, Math.PI * 2, true);
    context.fill();
    context.fill();
    context.stroke();
    context.beginPath();
    context.fillStyle = "rgb(255,255,255)";
    context.moveTo(240, 250); //LeftPupil
    context.arc(220, 250, 15, 0, Math.PI * 2, true);
    context.moveTo(400, 250); //Right Pupil
    context.arc(380, 250, 15, 0, Math.PI * 2, true);
    context.fill();
    context.stroke();
  }
}
//Creating an object for the nose
var nose = {
  draw: function() {
    context.beginPath();
    context.fillStyle = "rgb(0,0,0)";
    context.moveTo(300, 275);
    context.lineTo(275, 325);
    context.lineTo(325, 325);
    context.fill();
    context.closePath();
    context.stroke();
  }
}
//Creating an object for the mouth
var mouth = {
  frown: function() {
    context.beginPath();
    context.fillStyle = "rgb(0,0,0)";
    context.moveTo(305, 427); //Mouth
    context.arc(305, 427, 80, 0, Math.PI, true);
    context.fill();
    context.closePath();
    context.stroke();
  },
  circle: function() {
    context.beginPath();
    context.fillStyle = "rgb(0,0,0)";
    context.arc(300, 400, 50, 0, Math.PI * 2, true);
    context.fill();
    context.stroke();
  },
  straight: function() {
    context.beginPath();
    context.fillStyle = "rgb(0,0,0)";
    context.rect(225, 390, 150, 20); //Mouth
    context.fill();
    context.stroke();
  }
}
//Drawing the sad face
function sadFace() {
  faceShape.draw();
  eyes.draw();
  nose.draw();
  mouth.frown();
  leftEyeB.draw(175, BROWS_DOWN, 265, BROWS_DOWN);
  rightEyeB.draw(335, BROWS_DOWN, 425, BROWS_DOWN);
}
//Drawing the angry face
function angryFace() {
  faceShape.draw();
  eyes.draw();
  nose.draw();
  mouth.frown();
  leftEyeB.draw(175, BROWS_DOWN, 265, BROWS_UP);
  rightEyeB.draw(335, BROWS_UP, 425, BROWS_DOWN);
}
//Drawing the surprised face
function surprisedFace() {
  faceShape.draw();
  eyes.draw();
  nose.draw();
  mouth.circle();
  leftEyeB.draw(175, BROWS_UP, 265, BROWS_DOWN);
  rightEyeB.draw(335, BROWS_DOWN, 425, BROWS_UP);
}
//Drawing the neutral face
function neutralFace() {
  faceShape.draw();
  eyes.draw();
  nose.draw();
  mouth.circle();
  leftEyeB.draw(175, BROWS_DOWN, 265, BROWS_DOWN);
  rightEyeB.draw(335, BROWS_DOWN, 425, BROWS_DOWN);
}

function effects() {
  mousePosition = getMouseXY(e);
  console.log(mousePosition);

}
neutralFace();

canvas.addEventListener('click', function(event){
  var x = event.clientX, y = event.clientY;
  if(x> 280 && x <335 && y > 280 && y <335) {
    // nose is clicked.
    angryFace();
  }
  else {
    neutralFace();
  }
})

//Linking the face functions to the buttons
var angryButton = document.getElementById("angryFace");
var sadButton = document.getElementById("sadFace");
var surprisedButton = document.getElementById("surprisedFace");
var neutralButton = document.getElementById("neutralFace");
sadButton.addEventListener("click", sadFace);
angryButton.addEventListener("click", angryFace);
surprisedButton.addEventListener("click", surprisedFace);
neutralButton.addEventListener("click", neutralFace);

<!-- This is not the original markup. This is a part of an edit to make the code executable. -->
<canvas id='canvasFrame' width=600 height=600></canvas>

<div>
  <button id="angryFace">Angry Face</button>
  <button id="sadFace">Sad Face</button>
  <button id="surprisedFace">Surprised Face</button>
  <button id="neutralFace">Neutral Face</button>
</div>


问:
Error while removing the trailing comma using javascript
```<code>var checked1 = JSON.parse(Cookies.get('checkedValues'));
</code>```

Now the checked1 contains:     ,1

I used the following code to remove the trailing comma.

```<code>var checked = checked1.replace(/(^,)|(,$)/g, "");
</code>```

But now i'm getting an error

Uncaught TypeError: checked1.replace is not a function

答:
```<code>var checked1 = JSON.parse(Cookies.get('checkedValues')).toString();
</code>```

It Worked. The question was actually answered by Brian. But he removed his answer.

Body:
var checked1 = JSON.parse(Cookies.get('checkedValues'));

Now the checked1 contains:     ,1

I used the following code to remove the trailing comma.

var checked = checked1.replace(/(^,)|(,$)/g, "");

But now i'm getting an error

Uncaught TypeError: checked1.replace is not a function

Body:
var checked1 = JSON.parse(Cookies.get('checkedValues')).toString();

It Worked. The question was actually answered by Brian. But he removed his answer.


问:
Android: TextView: Remove spacing and padding on top and bottom
When I have a TextView with a \n in the text,, on the right I have two singleLine TextViews, one below the other with no spacing in between. I have set the following for all three TextViews.

```<code>android:lineSpacingMultiplier="1"
android:lineSpacingExtra="0pt"
android:paddingTop="0pt"
android:paddingBottom="0pt"
</code>```

The first line of the left TextView lines up perfectly with the top right TextView.

The second line of the left TextView is a little higher than the second line of the bottom right TextView.

It seems that there is some kind of hidden padding on the top and the bottom of the TextViews. How can I remove that?

答:
To my knowledge this is inherent to most widgets and the amount of "padding" differs among phone manufacturers.  This padding is really white space between the image border and the image in the 9 patch image file.

For example on my Droid X, spinner widgets get extra white space than buttons, which makes it look awkward when you have a spinner inline with a button, yet on my wife's phone the same application doesn't have the same problem and looks great!

The only suggestion I would have is to create your own 9 patch files and use them in your application.

Ahhh the pains that are Android.

Edited: Clarify padding vs white space.

ContentLicense: CC BY-SA 4.0

Body:
When I have a TextView with a \n in the text,, on the right I have two singleLine TextViews, one below the other with no spacing in between. I have set the following for all three TextViews.

android:lineSpacingMultiplier="1"
android:lineSpacingExtra="0pt"
android:paddingTop="0pt"
android:paddingBottom="0pt"

The first line of the left TextView lines up perfectly with the top right TextView.

The second line of the left TextView is a little higher than the second line of the bottom right TextView.

It seems that there is some kind of hidden padding on the top and the bottom of the TextViews. How can I remove that?


问:
Object sql is not a member of package org.apache.spark
I am trying to work with spark-sql but while I importing

```<code>import org.apache.spark.sql.{Row, SparkSession}
</code>```

getting following error:

```<code>object sql is not a member of package org.apache.spark
</code>```

Here are my details:

Spark version: 1.6.2
Scala version: 2.11.8
sbt version: 0.13.16

Here is my build.sbt file:

```<code>name := "sbt_demo"
version := "1.0"
scalaVersion := "2.11.8"

libraryDependencies += "org.apache.spark" %% "spark-core" % "1.6.2"

libraryDependencies += "org.apache.spark" %% "spark-sql" % "1.6.2"
</code>```

Note: there is another question with the same problem in Stack Overflow, but that accepted answer didn't help me. That is the reason why I am asking again.

答:
For sbt you can use

```<code>"org.apache.spark" %% "spark-sql" % "1.6.2" % "provided",
</code>```

For Maven

```<code>    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.10</artifactId>
        <version>1.6.2</version>
    </dependency>
</code>```

Use below import just before when u create dataframe . inside your code

```<code>import sqlContext.implicits._
val df = sqlContext.createDataFrame(rows, schema)
</code>```

Body:
I am trying to work with spark-sql but while I importing

import org.apache.spark.sql.{Row, SparkSession}

getting following error:

object sql is not a member of package org.apache.spark

Here are my details:

Spark version: 1.6.2
Scala version: 2.11.8
sbt version: 0.13.16

Here is my build.sbt file:

name := "sbt_demo"
version := "1.0"
scalaVersion := "2.11.8"

libraryDependencies += "org.apache.spark" %% "spark-core" % "1.6.2"

libraryDependencies += "org.apache.spark" %% "spark-sql" % "1.6.2"

Note: there is another question with the same problem in Stack Overflow, but that accepted answer didn't help me. That is the reason why I am asking again.

Body:
For sbt you can use

"org.apache.spark" %% "spark-sql" % "1.6.2" % "provided",

For Maven

    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.10</artifactId>
        <version>1.6.2</version>
    </dependency>

Use below import just before when u create dataframe . inside your code

import sqlContext.implicits._
val df = sqlContext.createDataFrame(rows, schema)


问:
Regex pattern for EXACTLY HH:MM:SS time String
I want to validate sting time format in EXACTLY hh:mm:ss String.

I mean by EXACTLY that

Each of hours / minutes / seconds MUST be 2 digits

Also
Accept only logical values like

hours [ from 00 to 23 ]

minutes [ from 00 to 59 ]

seconds [ from 00 to 59 ]

When i checked Regex pattern for HH:MM:SS time string

The answer accept hh:mm:ss string but also accepts cases like 2:3:24

Thanks in advance

Body:
The pattern you want is:

(([0-1]?[0-9])|(2[0-3])):[0-5][0-9]:[0-5][0-9]

which is for HH:MM:SS 24 hour format.


问:
Android studio SDK problems with Mac and Windows cross

Sorry for asking but, I have recently been using drive to save my projects in sync from a mac computer to a windows one. My project file on android studio started on my windows file but the sdk location and files were changed to suit the mac. When I try to open it on windows it says it changed the SDK directory as shown in the image but the project still is not functional

答:
Check your local.properties file in your root project. And change it to something like this:

```<code>sdk.dir=F:/ANDROIDSDK
</code>```

You need to remember that in Android Studio, path is using / instead of \.

Body:
Check your local.properties file in your root project. And change it to something like this:

sdk.dir=F:/ANDROIDSDK

You need to remember that in Android Studio, path is using / instead of \.


问:
Capitalize first letter of each word in java
So far after searching the web I can only get the first word to be capitalized.
"Wonder Woman" and "The Avengers" only get the first letter capitalized in the 1st word and not the 2nd.
I'm basically looking for that "java trick" to do the trick and not use a different class like WordUtilize or what ever it is.

Here's my code:

```<code>public class Movie extends Shows{

    private static String title;
    private static HashSet<String> _Movie;
    private static float time;

    public static void main(String[] args) {
        getTitle();
    }

    public static void getTitle() {
        theMovies();
        Scanner _title = new Scanner(System.in);
        System.out.println("Which movie would you like to see?");
        title = _title.nextLine();

        title = title.substring(0,1).toUpperCase() + title.substring(1).toLowerCase();

        _title.close();
        System.out.println("You entered " + title + " movie");

        if(_Movie.contains(title)) {
            System.out.println(title);
        } else {
            System.out.println("Sorry, we only have Batman, Superman, Wonder Woman, and The Avengers");
        }
    }

    public static void theMovies() {
        _Movie = new HashSet<>();
        _Movie.add("Batman");
        _Movie.add("Superman");
        _Movie.add("Wonder Woman");
        _Movie.add("The Avengers");
    }
}
</code>```

Here's the result I get:

Which movie would you like to see?
Wonder Woman
You entered Wonder woman movie
Sorry, we only have Batman, Superman, Wonder Woman, and The Avengers

Thanks for reading!
Edit Sorry for the pictures. Didn't know it was a big deal on here. :/

答:
It would be helpful if you posted the code as text rather than an image, but heres my suggestion:

Split the sentence into words

Capitalize each word (same way you have in your code)

Rejoin the words into a sentence

Heres the java code:

// split into words
String[] words = title.split(" ");

// capitalize each word
for (int i = 0; i < words.length; i++)
{
    words[i] = words[i].substring(0, 1).toUpperCase() + words[i].substring(1).toLowerCase();
}

// rejoin back into a sentence
title = String.join(" ", words);```

Body:
So far after searching the web I can only get the first word to be capitalized.
"Wonder Woman" and "The Avengers" only get the first letter capitalized in the 1st word and not the 2nd.
I'm basically looking for that "java trick" to do the trick and not use a different class like WordUtilize or what ever it is.

Here's my code:

public class Movie extends Shows{

    private static String title;
    private static HashSet<String> _Movie;
    private static float time;

    public static void main(String[] args) {
        getTitle();
    }

    public static void getTitle() {
        theMovies();
        Scanner _title = new Scanner(System.in);
        System.out.println("Which movie would you like to see?");
        title = _title.nextLine();

        title = title.substring(0,1).toUpperCase() + title.substring(1).toLowerCase();

        _title.close();
        System.out.println("You entered " + title + " movie");

        if(_Movie.contains(title)) {
            System.out.println(title);
        } else {
            System.out.println("Sorry, we only have Batman, Superman, Wonder Woman, and The Avengers");
        }
    }

    public static void theMovies() {
        _Movie = new HashSet<>();
        _Movie.add("Batman");
        _Movie.add("Superman");
        _Movie.add("Wonder Woman");
        _Movie.add("The Avengers");
    }
}

Here's the result I get:

Which movie would you like to see?
Wonder Woman
You entered Wonder woman movie
Sorry, we only have Batman, Superman, Wonder Woman, and The Avengers

Thanks for reading!
Edit Sorry for the pictures. Didn't know it was a big deal on here. :/


问:
Div tag's layering question
Suppose i am having two Div layer

```<code><div id="div1"> One </div>
<div id="div2"> Two </div>
</code>```

I want them both to be overlapped

and when i click the Button
i want that the Div1 layer to go in the background and the top layer should become Div2.

How can i achieve it through JavaScript ?

答:
If the z-index is being set with CSS then you need to get the computed style of the element, so getting element.style.zIndex directly won't work.  Since this is implemented differently in IE than in other browsers, let's make a function to get the computed style:

```<code>var getCompStyle = function( id ) {
    var curStyle;
    if (window.getComputedStyle) {
        curStyle = window.getComputedStyle(document.getElementById( id ), null);
    } else {
        curStyle = document.getElementById( id ).currentStyle;
    }
    return curStyle;
};
</code>```

Once we have this function, we can then apply the z-index accordingly attached to a button click handler:

```<code>document.getElementById('switch').onclick = function(e) {
    var div1style = getCompStyle( 'div1' );
    var div2style = getCompStyle( 'div2' );
    var switcher = div1style.zIndex;
    document.getElementById('div1').style.zIndex = div2style.zIndex;
    document.getElementById('div2').style.zIndex = switcher;
};
</code>```

I've created a fiddle example here (link) to demonstrate.

Title: Div tag's layering question

Body:
Suppose i am having two Div layer

 One

 Two

I want them both to be overlapped

and when i click the Button
i want that the Div1 layer to go in the background and the top layer should become Div2.

How can i achieve it through JavaScript ?

Body:
If the z-index is being set with CSS then you need to get the computed style of the element, so getting element.style.zIndex directly won't work.  Since this is implemented differently in IE than in other browsers, let's make a function to get the computed style:

var getCompStyle = function( id ) {
    var curStyle;
    if (window.getComputedStyle) {
        curStyle = window.getComputedStyle(document.getElementById( id ), null);
    } else {
        curStyle = document.getElementById( id ).currentStyle;
    }
    return curStyle;
};

Once we have this function, we can then apply the z-index accordingly attached to a button click handler:

document.getElementById('switch').onclick = function(e) {
    var div1style = getCompStyle( 'div1' );
    var div2style = getCompStyle( 'div2' );
    var switcher = div1style.zIndex;
    document.getElementById('div1').style.zIndex = div2style.zIndex;
    document.getElementById('div2').style.zIndex = switcher;
};

I've created a fiddle example here (link) to demonstrate.


问:
Choosing data structure for resource allocation decision tool
I'm trying to make a small decision making tool.

I have a list of event that occur at preset moments (X always occur at 00:12 for exemple), each event is weighted

I got a list of ressources, each ressource have a duration and a timespan before being available again. Also, each ressource modify in its own way the weight of events that happen when they are active. No ressource spent is also a possibility.

As I thought my thing, tthe optimal ressource allocation is the highest sum of events weights, applying ressource modifiers if event happen during ressource active time.

I got real trouble modeling my problem in terms of data structure. I thought about two possible solutions :

I had the first intuition I should have a tree where each node represent and event (by its timer) and the state of my choice list (which are available, which aren't, which are active). But how do I track changes between nodes then ? I got trouble to see how I would manage such structure.

Is a boolean 2D-array, with each line an event, and each column a choice, then i go through the columns, and where true, get the corresponding event weight, corresponding choice weight modifier, etc... a good step toward a decent solution ?

Any insight ?

答: I would suggest looking into a priority queue where you sort your resources by their event weights, such that the top of the priority queue would be the resource with the highest weight. Once an item is available you can add it to the queue. Since you mention you want to reprioritze item weights I would suggest looking into a fibonacci heap to act as the underlying data structure for the priority queue. </p>


问:
How to handle exception when passing driver into page object in cucumber step file
I've created a Java/Appium/Cucumber project using the page object model.

I have a BaseCapabilities class which creates a driver for me:

```<code>import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.remote.MobileCapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

public class BaseCapabilities {

    public static AndroidDriver<AndroidElement> capabilities() throws MalformedURLException{

    AndroidDriver<AndroidElement> driver;

    File filepath = new File("src");
    File fs = new File(filepath,"ApiDemos-debug.apk");

    DesiredCapabilities cap = new DesiredCapabilities();

    cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Nexus_5_API_25");
    cap.setCapability(MobileCapabilityType.APP, fs.getAbsolutePath());
    driver = new AndroidDriver<AndroidElement>
            (new URL("http://127.0.0.1:4723/wd/hub"),cap);

    return driver;
    }
}
</code>```

I have some page object classes:

```<code>public class LandingPageElements {

    public LandingPageElements(AppiumDriver<AndroidElement> driver) {
    PageFactory.initElements(new AppiumFieldDecorator(driver), this);
    }

    @AndroidFindBy(uiAutomator = "text(\"Media\")")
    private AndroidElement media;

    public void clickOnMediaButton() {
    media.click();
    }
}
</code>```

If I create a simple unit test with Junit, the tests run fine:

public class TestSteps {

```<code>@Test
public void firstTest() throws Throwable{
    AndroidDriver<AndroidElement> driver = capabilities();
    driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

    LandingPageElements l1 = new LandingPageElements(driver);
    MediaElements m1 = new MediaElements(driver);
    AudioFxElements a1 = new AudioFxElements(driver);

    l1.clickOnMediaButton();
    m1.clickOnAudioFxButton();
    a1.check60HzIsDisplayed();
}
</code>```

}

However I'm at a complete loss as to how I will implement these in my "Steps" glue code for Cucumber. For example, if I have a given/when/then, I'm not able to initialise my page objects as I need to pass my driver, however when I do it throws an "unhandled exception" error. There is no way for me to handle this exception as it means I have to contain it within a method then it won't be accessible to each given/when/then step. The "capabilities()" method call below is saying there is an unhandled exception. How do I handle this, but still allow my steps to access the initialised objects?

public class Steps extends BaseCapabilities{

```<code>LandingPageElements l1 = new LandingPageElements(capabilities());
MediaElements m1 = new MediaElements(capabilities());
AudioFxElements a1 = new AudioFxElements(capabilities());

@Given("^I click on Media$")
public void i_click_on_media()throws Throwable{
    l1.clickOnMediaButton();
}

@When("^I click AudioFx$")
public void i_click_audiofx(){
    m1.clickOnAudioFxButton();
}

@Then("^I can see the 60 hz option$")
public void i_can_see_the_60hz_option() throws Throwable{
    Assert.assertTrue(a1.check60HzIsDisplayed());
}
</code>```

}

Thank you!

答:
I would create the driver in the step class. When the step class grows and becomes large or start working with multiple domains, use dependency injection as suggested in the comment.

I wrote the blog post refereed to in the comment.

I would not start there tho, I would start with a simpler solution with one step definition class that is self contained and can handle all its needs.

This is in the spirit, "make it work, make it understandable, make it fast" where making it fast often is optional.

Body:
I've created a Java/Appium/Cucumber project using the page object model.

I have a BaseCapabilities class which creates a driver for me:

import io.appium.java_client.android.AndroidDriver;
import io.appium.java_client.android.AndroidElement;
import io.appium.java_client.remote.MobileCapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;

public class BaseCapabilities {

    public static AndroidDriver<AndroidElement> capabilities() throws MalformedURLException{

    AndroidDriver<AndroidElement> driver;

    File filepath = new File("src");
    File fs = new File(filepath,"ApiDemos-debug.apk");

    DesiredCapabilities cap = new DesiredCapabilities();

    cap.setCapability(MobileCapabilityType.DEVICE_NAME, "Nexus_5_API_25");
    cap.setCapability(MobileCapabilityType.APP, fs.getAbsolutePath());
    driver = new AndroidDriver<AndroidElement>
            (new URL("http://127.0.0.1:4723/wd/hub"),cap);

    return driver;
    }
}

I have some page object classes:

public class LandingPageElements {

    public LandingPageElements(AppiumDriver<AndroidElement> driver) {
    PageFactory.initElements(new AppiumFieldDecorator(driver), this);
    }

    @AndroidFindBy(uiAutomator = "text(\"Media\")")
    private AndroidElement media;

    public void clickOnMediaButton() {
    media.click();
    }
}

If I create a simple unit test with Junit, the tests run fine:

public class TestSteps {

@Test
public void firstTest() throws Throwable{
    AndroidDriver<AndroidElement> driver = capabilities();
    driver.manage().timeouts().implicitlyWait(15, TimeUnit.SECONDS);

    LandingPageElements l1 = new LandingPageElements(driver);
    MediaElements m1 = new MediaElements(driver);
    AudioFxElements a1 = new AudioFxElements(driver);

    l1.clickOnMediaButton();
    m1.clickOnAudioFxButton();
    a1.check60HzIsDisplayed();
}

}

However I'm at a complete loss as to how I will implement these in my "Steps" glue code for Cucumber. For example, if I have a given/when/then, I'm not able to initialise my page objects as I need to pass my driver, however when I do it throws an "unhandled exception" error. There is no way for me to handle this exception as it means I have to contain it within a method then it won't be accessible to each given/when/then step. The "capabilities()" method call below is saying there is an unhandled exception. How do I handle this, but still allow my steps to access the initialised objects?

public class Steps extends BaseCapabilities{

LandingPageElements l1 = new LandingPageElements(capabilities());
MediaElements m1 = new MediaElements(capabilities());
AudioFxElements a1 = new AudioFxElements(capabilities());

@Given("^I click on Media$")
public void i_click_on_media()throws Throwable{
    l1.clickOnMediaButton();
}

@When("^I click AudioFx$")
public void i_click_audiofx(){
    m1.clickOnAudioFxButton();
}

@Then("^I can see the 60 hz option$")
public void i_can_see_the_60hz_option() throws Throwable{
    Assert.assertTrue(a1.check60HzIsDisplayed());
}

}

Thank you!


问:
Getting error while installing tizen wearable packages from update manager
I have installed Tizen IDE on Mac OS Sierra. But when I'm trying to install additional packages such as emulator and wearable native app development, I'm getting an error as:

[Emulator] Downloading/extracting failed!Cannot install the Tizen SDK
  package.

Attached screenshot of error. Need Help!

答: Issue resolved after changing proxy settings.Existing proxy was blocking access to file download.</p>


问:
Replace NaN in any of specific columns to value in another column
In MATLAB, I have a table like this:

```<code>date        foo   bar   mitzva  baz
1995-1-1    21    54    12      37
1995-1-2    NaN   52    11      36
1995-1-3    39    56    NaN     38
1995-1-4    25    NaN   NaN     50
</code>```

How do I set any column with NaN to the value of its row's baz?

Or in other words:

How do I set a filter to check row-by-row for an NaN in any of the three columns before baz?

How can I set the three values without copying the good value 3 times?

What do I change in the following to get it to work? Or am I in the wrong direction?

```<code>colsToUpdate = {colidxFoo : colidxMitzva);
baddataFilter = any(isnan(data(:,colsToUpdate));
    % corrected from isnull. thanks @SardarUsama my mistake...

data(baddataFilter, colsToUpdate) = data(baddataFilter, colidxBaz);
</code>```

I want to get:

```<code>date        foo   bar   mitzva  baz
1995-1-1    21    54    12      37
1995-1-2    36    52    11      36
1995-1-3    39    56    38      38
1995-1-4    25    50    50      50
</code>```

答:
```<code>Val = table2array(T(:,2:end));  %Extracting the elements of all columns except 1st one
IndBadV = isnan(Val);           %Finding NaNs
Val(IndBadV) = 0;               %Replacing NaNs with zeros
Val = Val+repmat(Val(:,end),1,size(Val,2)) .* IndBadV; %Updating the values
T = [T(:,1) array2table(Val, ...%Updating the table
    'VariableNames',T.Properties.VariableNames(2:end))];
</code>```

Body:
In MATLAB, I have a table like this:

date        foo   bar   mitzva  baz
1995-1-1    21    54    12      37
1995-1-2    NaN   52    11      36
1995-1-3    39    56    NaN     38
1995-1-4    25    NaN   NaN     50

How do I set any column with NaN to the value of its row's baz?

Or in other words:

How do I set a filter to check row-by-row for an NaN in any of the three columns before baz?

How can I set the three values without copying the good value 3 times?

What do I change in the following to get it to work? Or am I in the wrong direction?

colsToUpdate = {colidxFoo : colidxMitzva);
baddataFilter = any(isnan(data(:,colsToUpdate));
    % corrected from isnull. thanks @SardarUsama my mistake...

data(baddataFilter, colsToUpdate) = data(baddataFilter, colidxBaz);

I want to get:

date        foo   bar   mitzva  baz
1995-1-1    21    54    12      37
1995-1-2    36    52    11      36
1995-1-3    39    56    38      38
1995-1-4    25    50    50      50